CCMain.m 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224
  1. //
  2. // CCMain.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCSynchronize.h"
  26. #import "OCActivity.h"
  27. #import "OCNotifications.h"
  28. #import "OCNotificationsAction.h"
  29. #import "OCFrameworkConstants.h"
  30. #import "OCCapabilities.h"
  31. #import "NCAutoUpload.h"
  32. #import "NCBridgeSwift.h"
  33. #import "NCNetworkingEndToEnd.h"
  34. #import "PKDownloadButton.h"
  35. @interface CCMain () <UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, NCSelectDelegate, UITextFieldDelegate, UIAdaptivePresentationControllerDelegate, NCCreateFormUploadConflictDelegate>
  36. {
  37. AppDelegate *appDelegate;
  38. BOOL _isRoot;
  39. BOOL _isViewDidLoad;
  40. NSMutableDictionary *_selectedocIdsMetadatas;
  41. UIImageView *_imageTitleHome;
  42. NSUInteger _failedAttempts;
  43. NSDate *_lockUntilDate;
  44. UIRefreshControl *refreshControl;
  45. CCHud *_hud;
  46. // Datasource
  47. CCSectionDataSourceMetadata *sectionDataSource;
  48. NSDate *_dateReadDataSource;
  49. // Search
  50. NSString *_searchFileName;
  51. NSMutableArray *_searchResultMetadatas;
  52. NSString *_noFilesSearchTitle;
  53. NSString *_noFilesSearchDescription;
  54. NSTimer *_timerWaitInput;
  55. // Automatic Upload Folder
  56. NSString *_autoUploadFileName;
  57. NSString *_autoUploadDirectory;
  58. // Folder
  59. BOOL _loadingFolder;
  60. tableMetadata *_metadataFolder;
  61. CGFloat heightRichWorkspace;
  62. CGFloat heightSearchBar;
  63. }
  64. @end
  65. @implementation CCMain
  66. #pragma --------------------------------------------------------------------------------------------
  67. #pragma mark ===== Init =====
  68. #pragma --------------------------------------------------------------------------------------------
  69. - (id)initWithCoder:(NSCoder *)aDecoder
  70. {
  71. if (self = [super initWithCoder:aDecoder]) {
  72. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  73. appDelegate.activeMain = self;
  74. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:k_notificationCenter_initializeMain object:nil];
  75. }
  76. return self;
  77. }
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== View =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (void)viewDidLoad
  82. {
  83. [super viewDidLoad];
  84. // init object
  85. self.metadata = [tableMetadata new];
  86. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  87. _selectedocIdsMetadatas = [NSMutableDictionary new];
  88. _isViewDidLoad = YES;
  89. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  90. _searchResultMetadatas = [NSMutableArray new];
  91. _searchFileName = @"";
  92. _noFilesSearchTitle = @"";
  93. _noFilesSearchDescription = @"";
  94. _cellFavouriteImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]];
  95. _cellTrashImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]];
  96. // delegate
  97. self.tableView.delegate = self;
  98. self.tableView.tableFooterView = [UIView new];
  99. self.tableView.emptyDataSetDelegate = self;
  100. self.tableView.emptyDataSetSource = self;
  101. self.searchController.delegate = self;
  102. self.searchController.searchBar.delegate = self;
  103. // Notification
  104. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:k_notificationCenter_clearDateReadDataSource object:nil];
  105. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:k_notificationCenter_setTitleMain object:nil];
  106. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:k_notificationCenter_progressTask object:nil];
  107. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  108. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(favoriteFile:) name:k_notificationCenter_favoriteFile object:nil];
  109. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(renameFile:) name:k_notificationCenter_renameFile object:nil];
  110. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  111. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  112. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createFolder:) name:k_notificationCenter_createFolder object:nil];
  113. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:k_notificationCenter_changeTheming object:nil];
  114. // Search
  115. self.definesPresentationContext = YES;
  116. self.searchController.searchResultsUpdater = self;
  117. self.searchController.dimsBackgroundDuringPresentation = NO;
  118. self.searchController.searchBar.translucent = NO;
  119. self.searchController.searchBar.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  120. self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
  121. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  122. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  123. [searchButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  124. }
  125. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  126. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  127. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  128. }
  129. // Load Rich Workspace
  130. self.viewRichWorkspace = [[[NSBundle mainBundle] loadNibNamed:@"NCRichWorkspace" owner:self options:nil] firstObject];
  131. if (@available(iOS 11, *)) {
  132. UITapGestureRecognizer *viewRichWorkspaceTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewRichWorkspaceTapAction:)];
  133. viewRichWorkspaceTapped.numberOfTapsRequired = 1;
  134. viewRichWorkspaceTapped.delegate = self;
  135. [self.viewRichWorkspace.richView addGestureRecognizer:viewRichWorkspaceTapped];
  136. }
  137. self.sortButton = self.viewRichWorkspace.sortButton;
  138. heightSearchBar = self.viewRichWorkspace.topView.frame.size.height;
  139. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  140. [self.sortButton setTitle: [NSString stringWithFormat:@"Sorted by %@ ", [CCUtility getOrderSettings]] forState:UIControlStateNormal];
  141. [self.sortButton addTarget:self action:@selector(toggleReMainMenu) forControlEvents:UIControlEventTouchUpInside];
  142. heightRichWorkspace = UIScreen.mainScreen.bounds.size.height / 4 + heightSearchBar;
  143. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, heightRichWorkspace)];
  144. self.navigationItem.searchController = self.searchController;
  145. // Table Header View
  146. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  147. // Register cell
  148. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  149. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  150. // long press recognizer TableView
  151. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  152. [self.tableView addGestureRecognizer:longPressRecognizer];
  153. // Pull-to-Refresh
  154. [self createRefreshControl];
  155. // Register for 3D Touch Previewing if available
  156. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  157. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  158. }
  159. // if this is not Main (the Main uses inizializeMain)
  160. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  161. // Read (File) Folder
  162. [self readFileReloadFolder];
  163. }
  164. // Title
  165. [self setTitle];
  166. // changeTheming
  167. [self changeTheming];
  168. }
  169. - (void)willDismissSearchController:(UISearchController *)searchController
  170. {
  171. [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
  172. }
  173. - (void)viewWillAppear:(BOOL)animated
  174. {
  175. [super viewWillAppear:animated];
  176. [self updateNavBarShadow:self.tableView];
  177. // test
  178. if (appDelegate.activeAccount.length == 0)
  179. return;
  180. if (_isSelectedMode)
  181. [self setUINavigationBarSelected];
  182. else
  183. [self setUINavigationBarDefault];
  184. // If not editing mode remove _selectedocIds
  185. if (!self.tableView.editing)
  186. [_selectedocIdsMetadatas removeAllObjects];
  187. // Check server URL "/"
  188. if (self.navigationController.viewControllers.firstObject == self && self.serverUrl == nil) {
  189. self.serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  190. }
  191. // Query data source
  192. if (self.searchController.isActive == false) {
  193. [self queryDatasourceWithReloadData:YES serverUrl:self.serverUrl];
  194. }
  195. }
  196. - (void)viewDidAppear:(BOOL)animated
  197. {
  198. [super viewDidAppear:animated];
  199. // Active Main
  200. appDelegate.activeMain = self;
  201. // Test viewDidLoad
  202. if (_isViewDidLoad) {
  203. _isViewDidLoad = NO;
  204. } else {
  205. if (appDelegate.activeAccount.length > 0 && [_selectedocIdsMetadatas count] == 0) {
  206. // Read (file) Folder
  207. [self readFileReloadFolder];
  208. }
  209. }
  210. if (appDelegate.activeAccount.length > 0 && self.serverUrl != nil) {
  211. // Get Shares
  212. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.activeAccount serverUrl:self.serverUrl];
  213. // Get RichWorkspace
  214. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  215. self.richWorkspaceText = directory.richWorkspace;
  216. }
  217. // Title
  218. [self setTitle];
  219. }
  220. - (void)viewWillDisappear:(BOOL)animated
  221. {
  222. [super viewWillDisappear:animated];
  223. }
  224. - (void) viewDidLayoutSubviews
  225. {
  226. [super viewDidLayoutSubviews];
  227. [self setTableViewHeader];
  228. }
  229. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  230. {
  231. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  232. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  233. [self setTableViewHeader];
  234. } completion:nil];
  235. }
  236. - (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController
  237. {
  238. [self viewDidAppear:true];
  239. }
  240. - (BOOL)prefersStatusBarHidden
  241. {
  242. return NO;
  243. }
  244. // detect scroll for remove keyboard in search mode
  245. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  246. {
  247. if (self.searchController.isActive && scrollView == self.tableView) {
  248. [self.searchController.searchBar endEditing:YES];
  249. }
  250. }
  251. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  252. [self updateNavBarShadow:scrollView];
  253. }
  254. - (void)changeTheming
  255. {
  256. [appDelegate changeTheming:self tableView:self.tableView collectionView:nil form:false];
  257. // createImagesThemingColor
  258. [[NCMainCommon sharedInstance] createImagesThemingColor];
  259. // Refresh control
  260. refreshControl.tintColor = UIColor.lightGrayColor;
  261. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  262. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  263. // color searchbar
  264. self.searchController.searchBar.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  265. self.searchController.searchBar.tintColor = NCBrandColor.sharedInstance.brand;
  266. // color searchbbar button text (cancel)
  267. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  268. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  269. [searchButton setTitleColor:NCBrandColor.sharedInstance.brand forState:UIControlStateNormal];
  270. }
  271. // color textview searchbbar
  272. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  273. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  274. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  275. }
  276. // Rich Workspace
  277. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  278. // Title
  279. [self setTitle];
  280. // Reload Table View
  281. [self tableViewReloadData];
  282. }
  283. #pragma --------------------------------------------------------------------------------------------
  284. #pragma mark ===== Initialization =====
  285. #pragma --------------------------------------------------------------------------------------------
  286. //
  287. // Callers :
  288. //
  289. // ChangeDefaultAccount (delegate)
  290. // Split : inizialize
  291. // Settings Advanced : removeAllFiles
  292. //
  293. - (void)initializeMain:(NSNotification *)notification
  294. {
  295. _dateReadDataSource = nil;
  296. // test
  297. if (appDelegate.activeAccount.length == 0)
  298. return;
  299. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  300. // This is Root home main add list
  301. appDelegate.homeMain = self;
  302. _isRoot = YES;
  303. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  304. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  305. // go Home
  306. [self.navigationController popToRootViewControllerAnimated:NO];
  307. // Remove search mode
  308. [self cancelSearchBar];
  309. // Clear error certificate
  310. [CCUtility setCertificateError:appDelegate.activeAccount error:NO];
  311. // Setting Theming
  312. [appDelegate settingThemingColorBrand];
  313. // Detail
  314. // If AVPlayer in play -> Stop
  315. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  316. [appDelegate.player pause];
  317. }
  318. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_menuDetailClose object:nil];
  319. // remove all Notification Messages
  320. [appDelegate.listOfNotifications removeAllObjects];
  321. // Not Photos Video in library ? then align and Init Auto Upload
  322. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.activeAccount]];
  323. if ([recordsPhotoLibrary count] == 0) {
  324. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  325. }
  326. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  327. NSLog(@"[LOG] Request Service Server Nextcloud");
  328. [[NCService sharedInstance] startRequestServicesServer];
  329. // Clear datasorce
  330. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  331. // Read this folder
  332. [self readFileReloadFolder];
  333. } else {
  334. // reload datasource
  335. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  336. }
  337. // Registeration push notification
  338. [appDelegate pushNotification];
  339. // Registeration domain File Provider
  340. if (@available(iOS 11, *) ) {
  341. if (k_fileProvider_domain) {
  342. [FileProviderDomain.sharedInstance registerDomain];
  343. } else {
  344. [FileProviderDomain.sharedInstance removeAllDomain];
  345. }
  346. }
  347. }
  348. #pragma --------------------------------------------------------------------------------------------
  349. #pragma mark ==== NotificationCenter ====
  350. #pragma --------------------------------------------------------------------------------------------
  351. - (void)deleteFile:(NSNotification *)notification
  352. {
  353. if (self.view.window == nil) { return; }
  354. NSDictionary *userInfo = notification.userInfo;
  355. tableMetadata *metadata = userInfo[@"metadata"];
  356. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  357. NSString *errorDescription = userInfo[@"errorDescription"];
  358. if (errorCode == 0 && metadata) {
  359. if ([metadata.serverUrl isEqualToString:self.serverUrl]) {
  360. if ([metadata.fileNameView.lowercaseString isEqualToString:k_fileNameRichWorkspace.lowercaseString]) {
  361. [self readFileReloadFolder];
  362. } else {
  363. if (self.searchController.isActive) {
  364. [self readFolder:self.serverUrl];
  365. } else {
  366. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  367. }
  368. }
  369. }
  370. } else {
  371. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  372. }
  373. }
  374. - (void)moveFile:(NSNotification *)notification
  375. {
  376. if (self.view.window == nil) { return; }
  377. NSDictionary *userInfo = notification.userInfo;
  378. tableMetadata *metadata = userInfo[@"metadata"];
  379. tableMetadata *metadataNew = userInfo[@"metadataNew"];
  380. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  381. NSString *errorDescription = userInfo[@"errorDescription"];
  382. if (errorCode == 0) {
  383. if ([metadata.serverUrl isEqualToString:self.serverUrl] || [metadataNew.serverUrl isEqualToString:self.serverUrl]) {
  384. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  385. }
  386. } else {
  387. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  388. }
  389. }
  390. - (void)copyFile:(NSNotification *)notification
  391. {
  392. if (self.view.window == nil) { return; }
  393. NSDictionary *userInfo = notification.userInfo;
  394. tableMetadata *metadata = userInfo[@"metadata"];
  395. NSString *serverUrlTo = userInfo[@"serverUrlTo"];
  396. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  397. NSString *errorDescription = userInfo[@"errorDescription"];
  398. if (errorCode == 0) {
  399. if ([metadata.serverUrl isEqualToString:self.serverUrl] || [serverUrlTo isEqualToString:self.serverUrl]) {
  400. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  401. }
  402. } else {
  403. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  404. }
  405. }
  406. - (void)favoriteFile:(NSNotification *)notification
  407. {
  408. if (self.view.window == nil) { return; }
  409. NSDictionary *userInfo = notification.userInfo;
  410. tableMetadata *metadata = userInfo[@"metadata"];
  411. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  412. NSString *errorDescription = userInfo[@"errorDescription"];
  413. BOOL favorite = [userInfo[@"favorite"] boolValue];
  414. if (errorCode == 0) {
  415. _dateReadDataSource = nil;
  416. if (self.searchController.isActive) {
  417. [self readFolder:self.serverUrl];
  418. } else {
  419. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  420. }
  421. if (metadata.directory && favorite) {
  422. NSString *selector;
  423. if ([CCUtility getFavoriteOffline])
  424. selector = selectorReadFolderWithDownload;
  425. else
  426. selector = selectorReadFolder;
  427. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName] selector:selector account:appDelegate.activeAccount];
  428. }
  429. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  430. metadata.favorite = favorite;
  431. metadata.session = k_download_session;
  432. metadata.sessionError = @"";
  433. metadata.sessionSelector = selectorDownloadSynchronize;
  434. metadata.status = k_metadataStatusWaitDownload;
  435. // Add Metadata for Download
  436. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  437. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  438. [appDelegate startLoadAutoDownloadUpload];
  439. }
  440. } else {
  441. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  442. }
  443. }
  444. - (void)renameFile:(NSNotification *)notification {
  445. if (self.view.window == nil) { return; }
  446. NSDictionary *userInfo = notification.userInfo;
  447. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  448. NSString *errorDescription = userInfo[@"errorDescription"];
  449. if (errorCode == 0) {
  450. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  451. } else {
  452. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  453. }
  454. }
  455. - (void)createFolder:(NSNotification *)notification {
  456. if (self.view.window == nil) { return; }
  457. NSDictionary *userInfo = notification.userInfo;
  458. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  459. NSString *errorDescription = userInfo[@"errorDescription"];
  460. if (errorCode == 0) {
  461. [self readFolder:self.serverUrl];
  462. } else {
  463. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  464. }
  465. }
  466. #pragma --------------------------------------------------------------------------------------------
  467. #pragma mark ==== DZNEmptyDataSetSource ====
  468. #pragma --------------------------------------------------------------------------------------------
  469. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  470. {
  471. if (_loadingFolder)
  472. return NO;
  473. else
  474. return YES;
  475. }
  476. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  477. {
  478. return NCBrandColor.sharedInstance.backgroundView;
  479. }
  480. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  481. {
  482. if (self.searchController.isActive)
  483. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  484. else
  485. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  486. }
  487. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  488. {
  489. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  490. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  491. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  492. activityView.color = NCBrandColor.sharedInstance.brandElement;
  493. [activityView startAnimating];
  494. return activityView;
  495. }
  496. return nil;
  497. }
  498. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  499. {
  500. NSString *text;
  501. if (self.searchController.isActive) {
  502. text = _noFilesSearchTitle;
  503. } else {
  504. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  505. }
  506. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  507. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  508. }
  509. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  510. {
  511. NSString *text;
  512. if (self.searchController.isActive) {
  513. text = _noFilesSearchDescription;
  514. } else {
  515. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  516. }
  517. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  518. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  519. paragraph.alignment = NSTextAlignmentCenter;
  520. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  521. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  522. }
  523. #pragma --------------------------------------------------------------------------------------------
  524. #pragma mark ===== Text Field =====
  525. #pragma --------------------------------------------------------------------------------------------
  526. - (void)minCharTextFieldDidChange:(UITextField *)sender
  527. {
  528. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  529. if (alertController)
  530. {
  531. UITextField *fileName = alertController.textFields.firstObject;
  532. UIAlertAction *okAction = alertController.actions.lastObject;
  533. okAction.enabled = fileName.text.length > 0;
  534. }
  535. }
  536. - (void)textFieldDidBeginEditing:(UITextField *)textField
  537. {
  538. [CCUtility selectFileNameFrom:textField];
  539. }
  540. #pragma --------------------------------------------------------------------------------------------
  541. #pragma mark ===== Graphic Window =====
  542. #pragma --------------------------------------------------------------------------------------------
  543. - (void)createRefreshControl
  544. {
  545. refreshControl = [NCMainRefreshControl new];
  546. self.tableView.refreshControl = refreshControl;
  547. refreshControl.tintColor = UIColor.lightGrayColor;
  548. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  549. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  550. }
  551. - (void)deleteRefreshControl
  552. {
  553. [refreshControl endRefreshing];
  554. for (UIView *subview in [_tableView subviews]) {
  555. if (subview == refreshControl)
  556. [subview removeFromSuperview];
  557. }
  558. if (@available(iOS 10, *)) {
  559. self.tableView.refreshControl = nil;
  560. }
  561. refreshControl = nil;
  562. }
  563. - (void)refreshControlTarget
  564. {
  565. [self readFolder:_serverUrl];
  566. // Actuate `Peek` feedback (weak boom)
  567. AudioServicesPlaySystemSound(1519);
  568. }
  569. - (void)setTitle
  570. {
  571. if (_isSelectedMode) {
  572. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  573. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  574. self.navigationItem.titleView = nil;
  575. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  576. } else {
  577. if (@available(iOS 11.0, *)) {
  578. if (_isRoot) {
  579. self.navigationController.navigationBar.prefersLargeTitles = true;
  580. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  581. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  582. } else {
  583. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeNever;
  584. }
  585. }
  586. }
  587. }
  588. - (UIImage *)getImageLogoHome
  589. {
  590. UIImage *image = [UIImage imageNamed:@"themingLogo"];
  591. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  592. if ([NCBrandOptions sharedInstance].use_themingColor && [capabilities.themingColorText isEqualToString:@"#000000"] && [UIImage imageNamed:@"themingLogoBlack"]) {
  593. image = [UIImage imageNamed:@"themingLogoBlack"];
  594. }
  595. if ([NCBrandOptions sharedInstance].use_themingLogo) {
  596. image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@-themingLogo.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl]]];
  597. if (image == nil) image = [UIImage imageNamed:@"themingLogo"];
  598. }
  599. if ([appDelegate.reachability isReachable] == NO) {
  600. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"nonetwork"] width:50 height:50 color:NCBrandColor.sharedInstance.icon];
  601. } else {
  602. return image;
  603. }
  604. }
  605. - (void)setUINavigationBarDefault
  606. {
  607. UIBarButtonItem *buttonNotification, *buttonSelect;
  608. buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  609. buttonSelect.enabled = true;
  610. // <
  611. self.navigationController.navigationBar.hidden = NO;
  612. // Notification
  613. if ([appDelegate.listOfNotifications count] > 0) {
  614. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  615. buttonNotification.tintColor = NCBrandColor.sharedInstance.brandText;
  616. buttonNotification.enabled = true;
  617. }
  618. if (buttonNotification)
  619. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, buttonNotification, nil];
  620. else
  621. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  622. self.navigationItem.leftBarButtonItem = nil;
  623. }
  624. - (void)setUINavigationBarSelected
  625. {
  626. UIImage *icon = [UIImage imageNamed:@"navigationMore"];
  627. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  628. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  629. self.navigationItem.leftBarButtonItem = leftButton;
  630. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  631. }
  632. - (void)cancelSelect
  633. {
  634. [self tableViewSelect:false];
  635. }
  636. #pragma --------------------------------------------------------------------------------------------
  637. #pragma mark ===== Document Picker =====
  638. #pragma --------------------------------------------------------------------------------------------
  639. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  640. {
  641. NSLog(@"[LOG] Cancelled");
  642. }
  643. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  644. {
  645. NSLog(@"[LOG] Cancelled");
  646. }
  647. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  648. {
  649. documentPicker.delegate = self;
  650. [self presentViewController:documentPicker animated:YES completion:nil];
  651. }
  652. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  653. {
  654. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  655. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  656. __block NSError *error;
  657. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  658. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  659. NSString *fileName = [[NCUtility sharedInstance] createFileName:[url lastPathComponent] serverUrl:serverUrl account:appDelegate.activeAccount];
  660. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  661. NSData *data = [NSData dataWithContentsOfURL:newURL];
  662. if (data && error == nil) {
  663. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  664. tableMetadata *metadataForUpload = [tableMetadata new];
  665. metadataForUpload.account = appDelegate.activeAccount;
  666. metadataForUpload.date = [NSDate new];
  667. metadataForUpload.ocId = ocId;
  668. metadataForUpload.fileName = fileName;
  669. metadataForUpload.fileNameView = fileName;
  670. metadataForUpload.serverUrl = serverUrl;
  671. metadataForUpload.session = k_upload_session;
  672. metadataForUpload.sessionSelector = selectorUploadFile;
  673. metadataForUpload.size = data.length;
  674. metadataForUpload.status = k_metadataStatusWaitUpload;
  675. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  676. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  677. [appDelegate startLoadAutoDownloadUpload];
  678. } else {
  679. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  680. }
  681. } else {
  682. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  683. }
  684. }];
  685. }
  686. }
  687. - (void)openImportDocumentPicker
  688. {
  689. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  690. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  691. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  692. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  693. documentProviderMenu.delegate = self;
  694. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  695. }
  696. #pragma --------------------------------------------------------------------------------------------
  697. #pragma mark ===== Assets Picker =====
  698. #pragma --------------------------------------------------------------------------------------------
  699. -(void)dismissFormUploadAssets
  700. {
  701. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  702. }
  703. - (void)openAssetsPickerController
  704. {
  705. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  706. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets, NSArray<NSURL *> * urls) {
  707. if (assets.count > 0) {
  708. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  709. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  710. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets urls:(NSMutableArray *)urls cryptated:NO session:k_upload_session delegate:self];
  711. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  712. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  713. [self presentViewController:navigationController animated:YES completion:nil];
  714. });
  715. }
  716. }];
  717. }
  718. #pragma --------------------------------------------------------------------------------------------
  719. #pragma mark ===== Save selected File =====
  720. #pragma --------------------------------------------------------------------------------------------
  721. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  722. {
  723. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  724. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  725. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  726. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  727. if (image)
  728. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  729. else
  730. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  731. }
  732. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  733. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  734. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  735. } else {
  736. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  737. }
  738. }
  739. if (status != PHAuthorizationStatusAuthorized) {
  740. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  741. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  742. [alertController addAction:okAction];
  743. [self presentViewController:alertController animated:YES completion:nil];
  744. }
  745. }
  746. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  747. {
  748. if (error) {
  749. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  750. }
  751. }
  752. - (void)saveSelectedFiles
  753. {
  754. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  755. return;
  756. NSLog(@"[LOG] Start download selected files ...");
  757. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  758. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  759. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  760. for (tableMetadata *metadata in metadatas) {
  761. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  762. metadata.session = k_download_session;
  763. metadata.sessionError = @"";
  764. metadata.sessionSelector = selectorSave;
  765. metadata.status = k_metadataStatusWaitDownload;
  766. // Add Metadata for Download
  767. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  768. [appDelegate startLoadAutoDownloadUpload];
  769. }
  770. }
  771. [_hud hideHud];
  772. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  773. });
  774. [self tableViewSelect:false];
  775. }
  776. #pragma --------------------------------------------------------------------------------------------
  777. #pragma mark ==== View Notification ====
  778. #pragma --------------------------------------------------------------------------------------------
  779. - (void)viewNotification
  780. {
  781. if ([appDelegate.listOfNotifications count] > 0) {
  782. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  783. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  784. [self presentViewController:notificationVC animated:YES completion:nil];
  785. }
  786. }
  787. #pragma mark -
  788. #pragma --------------------------------------------------------------------------------------------
  789. #pragma mark ===== Peek & Pop =====
  790. #pragma --------------------------------------------------------------------------------------------
  791. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  792. {
  793. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  794. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  795. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  796. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  797. if (cell) {
  798. previewingContext.sourceRect = cell.frame;
  799. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  800. viewController.metadata = metadata;
  801. viewController.imageFile = cell.file.image;
  802. viewController.showOpenIn = true;
  803. viewController.showShare = true;
  804. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  805. viewController.showOpenInternalViewer = true;
  806. }
  807. return viewController;
  808. }
  809. return nil;
  810. }
  811. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  812. {
  813. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  814. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  815. }
  816. #pragma --------------------------------------------------------------------------------------------
  817. #pragma mark ==== Download ====
  818. #pragma --------------------------------------------------------------------------------------------
  819. - (void)downloadSelectedFilesFolders
  820. {
  821. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  822. return;
  823. NSLog(@"[LOG] Start download selected ...");
  824. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  825. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  826. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  827. for (tableMetadata *metadata in selectedMetadatas) {
  828. if (metadata.directory) {
  829. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  830. } else {
  831. [[CCSynchronize sharedSynchronize] readFile:metadata.ocId fileName:metadata.fileName serverUrl:metadata.serverUrl selector:selectorReadFileWithDownload account:appDelegate.activeAccount];
  832. }
  833. }
  834. [_hud hideHud];
  835. });
  836. [self tableViewSelect:false];
  837. }
  838. #pragma --------------------------------------------------------------------------------------------
  839. #pragma mark ===== Upload new Photos/Videos =====
  840. #pragma --------------------------------------------------------------------------------------------
  841. //
  842. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  843. //
  844. - (void)uploadFileAsset:(NSMutableArray *)assets urls:(NSMutableArray *)urls serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  845. {
  846. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  847. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  848. // if request create the folder for Auto Upload & the subfolders
  849. if ([autoUploadPath isEqualToString:serverUrl])
  850. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  851. return;
  852. dispatch_async(dispatch_get_main_queue(), ^{
  853. [self uploadFileAsset:assets urls:urls serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  854. });
  855. });
  856. }
  857. - (void)uploadFileAsset:(NSArray *)assets urls:(NSArray *)urls serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  858. {
  859. NSMutableArray *metadatas = [NSMutableArray new];
  860. NSMutableArray *metadatasMOV = [NSMutableArray new];
  861. NSMutableArray *metadatasConflict = [NSMutableArray new];
  862. for (PHAsset *asset in assets) {
  863. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  864. NSDate *assetDate = asset.creationDate;
  865. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  866. // Create serverUrl if use sub folder
  867. if (useSubFolder) {
  868. [formatter setDateFormat:@"yyyy"];
  869. NSString *yearString = [formatter stringFromDate:assetDate];
  870. [formatter setDateFormat:@"MM"];
  871. NSString *monthString = [formatter stringFromDate:assetDate];
  872. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  873. }
  874. // Check if is in upload
  875. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.activeAccount, serverUrl, fileName] sorted:nil ascending:NO];
  876. if ([isRecordInSessions count] > 0)
  877. continue;
  878. // Prepare record metadata
  879. tableMetadata *metadataForUpload = [tableMetadata new];
  880. metadataForUpload.account = appDelegate.activeAccount;
  881. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  882. metadataForUpload.date = [NSDate new];
  883. metadataForUpload.ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  884. metadataForUpload.fileName = fileName;
  885. metadataForUpload.fileNameView = fileName;
  886. metadataForUpload.serverUrl = serverUrl;
  887. metadataForUpload.session = session;
  888. metadataForUpload.sessionSelector = selectorUploadFile;
  889. metadataForUpload.size = [[NCUtility sharedInstance] getFileSizeWithAsset:asset];
  890. metadataForUpload.status = k_metadataStatusWaitUpload;
  891. [CCUtility insertTypeFileIconName:fileName metadata:metadataForUpload];
  892. // verify exists conflict
  893. NSString *fileNameExtension = [fileName pathExtension].lowercaseString;
  894. NSString *fileNameWithoutExtension = [fileName stringByDeletingPathExtension];
  895. NSString *fileNameConflict = fileName;
  896. if ([fileNameExtension isEqualToString:@"heic"] && [CCUtility getFormatCompatibility]) {
  897. fileNameConflict = [fileNameWithoutExtension stringByAppendingString:@".jpg"];
  898. }
  899. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, serverUrl, fileNameConflict]];
  900. if (metadata) {
  901. [metadatasConflict addObject:metadataForUpload];
  902. } else {
  903. [metadatas addObject:metadataForUpload];
  904. }
  905. // Add Medtadata MOV LIVE PHOTO for upload
  906. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto && urls.count == assets.count) {
  907. NSUInteger index = [assets indexOfObject:asset];
  908. NSURL *url = [urls objectAtIndex:index];
  909. tableMetadata *metadataMOVForUpload = [tableMetadata new];
  910. NSString *fileNameNoExt = [fileName stringByDeletingPathExtension];
  911. NSString *fileName = [NSString stringWithFormat:@"%@.mov", fileNameNoExt];
  912. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  913. metadataMOVForUpload.account = appDelegate.activeAccount;
  914. metadataMOVForUpload.date = [NSDate new];
  915. metadataMOVForUpload.ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:serverUrl fileNameView:fileName directory:false];
  916. metadataMOVForUpload.fileName = fileName;
  917. metadataMOVForUpload.fileNameView = fileName;
  918. metadataMOVForUpload.serverUrl = serverUrl;
  919. metadataMOVForUpload.session = session;
  920. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  921. metadataMOVForUpload.size = fileSize;
  922. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  923. // Prepare file and directory
  924. [CCUtility moveFileAtPath:url.path toPath:[CCUtility getDirectoryProviderStorageOcId:metadataMOVForUpload.ocId fileNameView:fileName]];
  925. [metadatasMOV addObject:metadataMOVForUpload];
  926. }
  927. }
  928. // Verify if file(s) exists
  929. if (metadatasConflict.count > 0) {
  930. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  931. conflict.delegate = self;
  932. conflict.metadatas = metadatas;
  933. conflict.metadatasMOV = metadatasMOV;
  934. conflict.metadatasConflict = metadatasConflict;
  935. [self presentViewController:conflict animated:YES completion:nil];
  936. } else {
  937. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  938. [[NCManageDatabase sharedInstance] addMetadatas:metadatasMOV];
  939. [appDelegate startLoadAutoDownloadUpload];
  940. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  941. }
  942. }
  943. #pragma --------------------------------------------------------------------------------------------
  944. #pragma mark ==== NCCreateFormUploadConflictDelegate ====
  945. #pragma --------------------------------------------------------------------------------------------
  946. - (void)dismissCreateFormUploadConflictWithMetadatas:(NSArray *)metadatas
  947. {
  948. if (metadatas.count > 0) {
  949. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  950. [appDelegate startLoadAutoDownloadUpload];
  951. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  952. }
  953. }
  954. #pragma --------------------------------------------------------------------------------------------
  955. #pragma mark ==== Read Folder ====
  956. #pragma --------------------------------------------------------------------------------------------
  957. - (void)readFolder:(NSString *)serverUrl
  958. {
  959. // init control
  960. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  961. [refreshControl endRefreshing];
  962. return;
  963. }
  964. // Search Mode
  965. if (self.searchController.isActive) {
  966. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  967. _searchFileName = @""; // forced reload searchg
  968. [self updateSearchResultsForSearchController:self.searchController];
  969. return;
  970. }
  971. _loadingFolder = YES;
  972. [self tableViewReloadData];
  973. [[NCNetworking sharedInstance] readFolderWithServerUrl:serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSInteger errorCode, NSString *errorDescription) {
  974. [refreshControl endRefreshing];
  975. if (errorCode == 0 ) {
  976. _metadataFolder = metadataFolder;
  977. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.activeAccount];
  978. [self setTitle];
  979. // File is changed ??
  980. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  981. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:serverUrl account:account withDownload:NO];
  982. });
  983. // E2EE Is encrypted folder get metadata
  984. if (isFolderEncrypted) {
  985. NSString *metadataFolderFileId = metadataFolder.fileId;
  986. // Read Metadata
  987. if ([CCUtility isEndToEndEnabled:account]) {
  988. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  989. NSString *metadata;
  990. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileId:metadataFolderFileId user:appDelegate.activeUser userID:appDelegate.activeUserID password:[CCUtility getPassword:appDelegate.activeAccount] url:appDelegate.activeUrl];
  991. dispatch_async(dispatch_get_main_queue(), ^{
  992. if (error) {
  993. if (error.code != kOCErrorServerPathNotFound)
  994. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  995. } else {
  996. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:appDelegate.activeUrl] == false)
  997. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  998. else
  999. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  1000. }
  1001. });
  1002. });
  1003. } else {
  1004. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1005. }
  1006. }
  1007. if ([serverUrl isEqualToString:_serverUrl]) {
  1008. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  1009. [self tableViewReloadData];
  1010. }
  1011. } else {
  1012. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1013. }
  1014. _loadingFolder = NO;
  1015. }];
  1016. }
  1017. - (void)readFileReloadFolder
  1018. {
  1019. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  1020. return;
  1021. // RichWorkspace
  1022. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  1023. self.richWorkspaceText = directory.richWorkspace;
  1024. [self setTableViewHeader];
  1025. // Load Datasource
  1026. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1027. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1028. });
  1029. [[NCNetworking sharedInstance] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  1030. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1031. // Rich Workspace
  1032. [[NCManageDatabase sharedInstance] setDirectoryWithOcId:metadata.ocId serverUrl:self.serverUrl richWorkspace:metadata.richWorkspace account:account];
  1033. self.richWorkspaceText = metadata.richWorkspace;
  1034. [self setTableViewHeader];
  1035. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  1036. // Read folder: No record, Change etag or BLINK
  1037. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  1038. [self readFolder:self.serverUrl];
  1039. }
  1040. } else if (errorCode != 0) {
  1041. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1042. }
  1043. }];
  1044. }
  1045. #pragma mark -
  1046. #pragma --------------------------------------------------------------------------------------------
  1047. #pragma mark ===== Search =====
  1048. #pragma --------------------------------------------------------------------------------------------
  1049. - (void)searchStartTimer
  1050. {
  1051. if (self.searchController.isActive == false) {
  1052. return;
  1053. }
  1054. [[NCCommunication sharedInstance] searchLiteralWithServerUrl:appDelegate.activeUrl depth:@"infinity" literal:_searchFileName showHiddenFiles:[CCUtility getShowHiddenFiles] customUserAgent:nil addCustomHeaders:nil user:appDelegate.activeUser account:appDelegate.activeAccount completionHandler:^(NSString *account, NSArray *files, NSInteger errorCode, NSString *errorDescription) {
  1055. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount] && files != nil) {
  1056. [[NCManageDatabase sharedInstance] convertNCFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  1057. NSMutableArray *metadatasDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  1058. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasDB];
  1059. _metadataFolder = nil;
  1060. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  1061. [self tableViewReloadData];
  1062. [self setTitle];
  1063. }];
  1064. } else {
  1065. if (errorCode != 0) {
  1066. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1067. }
  1068. _searchFileName = @"";
  1069. }
  1070. }];
  1071. _noFilesSearchTitle = @"";
  1072. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1073. [self.tableView reloadEmptyDataSet];
  1074. }
  1075. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1076. {
  1077. // Color text "Cancel"
  1078. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brand];
  1079. if (searchController.isActive) {
  1080. [self deleteRefreshControl];
  1081. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1082. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1083. _searchFileName = fileName;
  1084. _metadataFolder = nil;
  1085. // First : filter
  1086. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1087. [_searchResultMetadatas removeAllObjects];
  1088. for (tableMetadata *record in records) {
  1089. [_searchResultMetadatas addObject:record];
  1090. }
  1091. // Version >= 12
  1092. if ([[NCManageDatabase sharedInstance] getServerVersionWithAccount:appDelegate.activeAccount] >= 12) {
  1093. [_timerWaitInput invalidate];
  1094. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1095. }
  1096. [self setTitle];
  1097. }
  1098. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1099. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1100. }
  1101. } else {
  1102. [self createRefreshControl];
  1103. [self reloadDatasource:self.serverUrl ocId:nil action:k_action_NULL];
  1104. }
  1105. }
  1106. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1107. {
  1108. [self cancelSearchBar];
  1109. }
  1110. - (void)cancelSearchBar
  1111. {
  1112. if (self.searchController.active) {
  1113. [self.searchController setActive:NO];
  1114. _searchFileName = @"";
  1115. _dateReadDataSource = nil;
  1116. _searchResultMetadatas = [NSMutableArray new];
  1117. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1118. }
  1119. }
  1120. #pragma mark -
  1121. #pragma --------------------------------------------------------------------------------------------
  1122. #pragma mark ===== Delete File or Folder =====
  1123. #pragma --------------------------------------------------------------------------------------------
  1124. - (void)deleteMetadatas
  1125. {
  1126. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1127. return;
  1128. if ([_selectedocIdsMetadatas count] > 0) {
  1129. [appDelegate.arrayDeleteMetadata addObjectsFromArray:[_selectedocIdsMetadatas allValues]];
  1130. } else {
  1131. [appDelegate.arrayDeleteMetadata addObject:self.metadata];
  1132. }
  1133. [[NCNetworking sharedInstance] deleteMetadata:appDelegate.arrayDeleteMetadata.firstObject user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1134. [appDelegate.arrayDeleteMetadata removeObjectAtIndex:0];
  1135. // End Select Table View
  1136. [self tableViewSelect:false];
  1137. }
  1138. #pragma --------------------------------------------------------------------------------------------
  1139. #pragma mark ===== Move / Copy =====
  1140. #pragma --------------------------------------------------------------------------------------------
  1141. - (void)moveCopyFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo move:(BOOL)move overwrite:(BOOL)overwrite
  1142. {
  1143. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1144. return;
  1145. NSMutableArray *arrayMetadata, *arrayServerUrlTo;
  1146. if (move) {
  1147. arrayMetadata = appDelegate.arrayMoveMetadata;
  1148. arrayServerUrlTo = appDelegate.arrayMoveServerUrlTo;
  1149. } else {
  1150. arrayMetadata = appDelegate.arrayCopyMetadata;
  1151. arrayServerUrlTo = appDelegate.arrayCopyServerUrlTo;
  1152. }
  1153. if ([_selectedocIdsMetadatas count] > 0) {
  1154. for (NSString *key in _selectedocIdsMetadatas) {
  1155. tableMetadata *metadata = [_selectedocIdsMetadatas objectForKey:key];
  1156. [arrayMetadata addObject:metadata];
  1157. [arrayServerUrlTo addObject:serverUrlTo];
  1158. }
  1159. } else {
  1160. [arrayMetadata addObject:metadata];
  1161. [arrayServerUrlTo addObject:serverUrlTo];
  1162. }
  1163. if (move) {
  1164. [[NCNetworking sharedInstance] moveMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1165. } else {
  1166. [[NCNetworking sharedInstance] copyMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1167. }
  1168. [arrayMetadata removeObjectAtIndex:0];
  1169. [arrayServerUrlTo removeObjectAtIndex:0];
  1170. // End Select Table View
  1171. [self tableViewSelect:false];
  1172. }
  1173. // DELEGATE : Select
  1174. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  1175. {
  1176. if (serverUrl == nil) {
  1177. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1178. } else {
  1179. // E2EE DENIED
  1180. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1181. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1182. return;
  1183. }
  1184. BOOL move = true;
  1185. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  1186. if ([_selectedocIdsMetadatas count] > 0) {
  1187. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1188. [self moveCopyFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl move:move overwrite:overwrite];
  1189. } else {
  1190. [self moveCopyFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl move:move overwrite:overwrite];
  1191. }
  1192. }
  1193. }
  1194. - (void)moveOpenWindow:(NSArray *)indexPaths
  1195. {
  1196. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1197. return;
  1198. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1199. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1200. viewController.delegate = self;
  1201. viewController.hideButtonCreateFolder = false;
  1202. viewController.selectFile = false;
  1203. viewController.includeDirectoryE2EEncryption = false;
  1204. viewController.includeImages = false;
  1205. viewController.type = @"";
  1206. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1207. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  1208. viewController.isButtonDone1Hide = false;
  1209. viewController.isOverwriteHide = false;
  1210. viewController.layoutViewSelect = k_layout_view_move;
  1211. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1212. [self presentViewController:navigationController animated:YES completion:nil];
  1213. }
  1214. #pragma --------------------------------------------------------------------------------------------
  1215. #pragma mark ===== Create folder =====
  1216. #pragma --------------------------------------------------------------------------------------------
  1217. - (void)createFolder
  1218. {
  1219. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1220. NSString *message;
  1221. UIAlertController *alertController;
  1222. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1223. message = @"/";
  1224. } else {
  1225. message = [serverUrl lastPathComponent];
  1226. }
  1227. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1228. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1229. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1230. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1231. }];
  1232. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1233. NSLog(@"[LOG] Cancel action");
  1234. }];
  1235. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1236. UITextField *fileName = alertController.textFields.firstObject;
  1237. [[NCNetworking sharedInstance] createFolderWithFileName:fileName.text serverUrl:serverUrl account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1238. }];
  1239. okAction.enabled = NO;
  1240. [alertController addAction:cancelAction];
  1241. [alertController addAction:okAction];
  1242. [self presentViewController:alertController animated:YES completion:nil];
  1243. }
  1244. #pragma --------------------------------------------------------------------------------------------
  1245. #pragma mark ===== Progress & Task Button =====
  1246. #pragma --------------------------------------------------------------------------------------------
  1247. - (void)triggerProgressTask:(NSNotification *)notification
  1248. {
  1249. if (sectionDataSource.ocIdIndexPath != nil) {
  1250. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1251. }
  1252. }
  1253. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1254. {
  1255. UITouch *touch = [[event allTouches] anyObject];
  1256. CGPoint location = [touch locationInView:self.tableView];
  1257. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1258. if ([self indexPathIsValid:indexPath]) {
  1259. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1260. if (metadataSection) {
  1261. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataSection.ocId]];
  1262. if (metadata)
  1263. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1264. }
  1265. }
  1266. }
  1267. - (void)cancelAllTask:(id)sender
  1268. {
  1269. CGPoint location = [sender locationInView:self.tableView];
  1270. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1271. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1272. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1273. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1274. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1275. [NCUtility.sharedInstance stopActivityIndicator];
  1276. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil ocId:nil action:k_action_NULL];
  1277. }]];
  1278. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1279. alertController.popoverPresentationController.sourceView = self.tableView;
  1280. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1281. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1282. [alertController.view layoutIfNeeded];
  1283. [self presentViewController:alertController animated:YES completion:nil];
  1284. }
  1285. #pragma --------------------------------------------------------------------------------------------
  1286. #pragma mark ===== Tap =====
  1287. #pragma --------------------------------------------------------------------------------------------
  1288. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1289. {
  1290. CGPoint location = [tapGesture locationInView:self.tableView];
  1291. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1292. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1293. if (metadata) {
  1294. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1295. }
  1296. }
  1297. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1298. {
  1299. CGPoint location = [tapGesture locationInView:self.tableView];
  1300. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1301. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1302. if (metadata) {
  1303. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1304. }
  1305. }
  1306. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1307. {
  1308. CGPoint location = [tapGesture locationInView:self.tableView];
  1309. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1310. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1311. if (metadata) {
  1312. }
  1313. }
  1314. #pragma --------------------------------------------------------------------------------------------
  1315. #pragma mark ===== Rich Workspace =====
  1316. #pragma --------------------------------------------------------------------------------------------
  1317. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1318. {
  1319. [UIView animateWithDuration:0.5 animations:^{
  1320. [self.tableView setContentOffset:CGPointMake(0, heightSearchBar)];
  1321. } completion:^(BOOL finished) {
  1322. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1323. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1324. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1325. viewerRichWorkspace.serverUrl = self.serverUrl;
  1326. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1327. [self presentViewController:navigationController animated:NO completion:NULL];
  1328. }];
  1329. }
  1330. - (void)createRichWorkspace
  1331. {
  1332. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1333. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1334. if (metadata) {
  1335. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1336. } else {
  1337. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1338. }
  1339. }
  1340. #pragma --------------------------------------------------------------------------------------------
  1341. #pragma mark ==== Menu LOGO ====
  1342. #pragma --------------------------------------------------------------------------------------------
  1343. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1344. {
  1345. // Brand
  1346. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1347. return;
  1348. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1349. NSMutableArray *menuArray = [NSMutableArray new];
  1350. for (NSString *account in listAccount) {
  1351. CCMenuItem *item = [[CCMenuItem alloc] init];
  1352. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1353. item.argument = account;
  1354. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1355. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1356. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1357. if (avatar) {
  1358. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1359. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1360. CGSize imageSize = avatarImageView.bounds.size;
  1361. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1362. CGContextRef context = UIGraphicsGetCurrentContext();
  1363. [avatarImageView.layer renderInContext:context];
  1364. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1365. UIGraphicsEndImageContext();
  1366. } else {
  1367. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1368. }
  1369. item.image = avatar;
  1370. item.target = self;
  1371. if ([account isEqualToString:appDelegate.activeAccount]) {
  1372. item.action = nil;
  1373. [menuArray insertObject:item atIndex:0];
  1374. } else {
  1375. item.action = @selector(changeDefaultAccount:);
  1376. [menuArray addObject:item];
  1377. }
  1378. }
  1379. // Add + new account
  1380. CCMenuItem *item = [[CCMenuItem alloc] init];
  1381. item.title = NSLocalizedString(@"_add_account_", nil);
  1382. item.argument = @"";
  1383. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"add"] width:50 height:50 color:NCBrandColor.sharedInstance.textView];
  1384. item.target = self;
  1385. item.action = @selector(addNewAccount:);
  1386. [menuArray addObject:item];
  1387. OptionalConfiguration options;
  1388. Color backgroundColor;
  1389. const CGFloat *componentsBackgroundColor = CGColorGetComponents(NCBrandColor.sharedInstance.backgroundForm.CGColor);
  1390. backgroundColor.R = componentsBackgroundColor[0];
  1391. backgroundColor.G = componentsBackgroundColor[1];
  1392. backgroundColor.B = componentsBackgroundColor[2];
  1393. options.arrowSize = 9;
  1394. options.marginXSpacing = 7;
  1395. options.marginYSpacing = 10;
  1396. options.intervalSpacing = 20;
  1397. options.menuCornerRadius = 6.5;
  1398. options.maskToBackground = NO;
  1399. options.shadowOfMenu = YES;
  1400. options.hasSeperatorLine = YES;
  1401. options.seperatorLineHasInsets = YES;
  1402. options.textColor = NCBrandColor.sharedInstance.textView;
  1403. options.menuBackgroundColor = backgroundColor;
  1404. options.separatorColor = NCBrandColor.sharedInstance.separator;
  1405. CGRect rect = self.view.frame;
  1406. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1407. CGFloat safeAreaTop = 0;
  1408. CGFloat offsetY = 35;
  1409. if (@available(iOS 11, *)) {
  1410. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1411. }
  1412. rect.origin.y = locationY + safeAreaTop + offsetY;
  1413. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1414. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1415. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1416. }
  1417. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1418. {
  1419. // LOGOUT
  1420. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1421. if (tableAccount) {
  1422. // LOGIN
  1423. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1424. // go to home sweet home
  1425. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1426. }
  1427. }
  1428. - (void)addNewAccount:(CCMenuItem *)sender
  1429. {
  1430. [appDelegate openLoginView:self selector:k_intro_login openLoginWeb:false];
  1431. }
  1432. - (void)toggleReMainMenu
  1433. {
  1434. [self toggleMenuWithViewController:self.navigationController];
  1435. }
  1436. - (void)toggleReSelectMenu
  1437. {
  1438. [self toggleSelectMenuWithViewController:self.navigationController];
  1439. }
  1440. #pragma --------------------------------------------------------------------------------------------
  1441. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1442. #pragma --------------------------------------------------------------------------------------------
  1443. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1444. {
  1445. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1446. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1447. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1448. NSMutableArray *items = [NSMutableArray new];
  1449. if ([self indexPathIsValid:indexPath])
  1450. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1451. else
  1452. self.metadata = nil;
  1453. [self becomeFirstResponder];
  1454. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1455. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1456. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1457. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1458. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1459. }
  1460. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  1461. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_internal_view_", nil) action:@selector(openInternalViewerTouch:)]];
  1462. }
  1463. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1464. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1465. [menuController setMenuItems:items];
  1466. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1467. [menuController setMenuVisible:YES animated:YES];
  1468. }
  1469. }
  1470. - (BOOL)canBecomeFirstResponder
  1471. {
  1472. return YES;
  1473. }
  1474. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1475. {
  1476. // For copy file, copy files, Open in ... :
  1477. //
  1478. // NO Directory
  1479. // NO Error Passcode
  1480. // NO In Session mode (download/upload)
  1481. // NO Template
  1482. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openInternalViewerTouch:) == action) {
  1483. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1484. else return NO;
  1485. }
  1486. if (@selector(copyTouchFiles:) == action) {
  1487. if (_isSelectedMode) {
  1488. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1489. for (tableMetadata *metadata in selectedMetadatas) {
  1490. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1491. return YES;
  1492. }
  1493. }
  1494. return NO;
  1495. }
  1496. if (@selector(pasteTouchFile:) == action) {
  1497. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1498. NSArray *items = [pasteboard items];
  1499. if ([items count] == 1) {
  1500. // Value : (NSData) ocId
  1501. NSDictionary *dic = [items objectAtIndex:0];
  1502. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1503. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1504. if (ocId) {
  1505. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1506. if (metadata) {
  1507. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1508. } else {
  1509. return NO;
  1510. }
  1511. }
  1512. }
  1513. return NO;
  1514. }
  1515. if (@selector(pasteTouchFiles:) == action) {
  1516. BOOL isValid = NO;
  1517. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1518. NSArray *items = [pasteboard items];
  1519. if ([items count] <= 1) return NO;
  1520. for (NSDictionary *dic in items) {
  1521. // Value : (NSData) ocId
  1522. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1523. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1524. if (ocId) {
  1525. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1526. if (metadata) {
  1527. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1528. isValid = YES;
  1529. } else {
  1530. isValid = NO;
  1531. break;
  1532. }
  1533. } else {
  1534. isValid = NO;
  1535. break;
  1536. }
  1537. } else {
  1538. isValid = NO;
  1539. break;
  1540. }
  1541. }
  1542. return isValid;
  1543. }
  1544. return NO;
  1545. }
  1546. /************************************ COPY ************************************/
  1547. - (void)copyTouchFile:(id)sender
  1548. {
  1549. // Remove all item
  1550. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1551. pasteboard.items = [[NSArray alloc] init];
  1552. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1553. [self copyFileToPasteboard:self.metadata];
  1554. } else {
  1555. self.metadata.session = k_download_session;
  1556. self.metadata.sessionError = @"";
  1557. self.metadata.sessionSelector = selectorLoadCopy;
  1558. self.metadata.status = k_metadataStatusWaitDownload;
  1559. // Add Metadata for Download
  1560. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  1561. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  1562. [appDelegate startLoadAutoDownloadUpload];
  1563. }
  1564. }
  1565. - (void)copyTouchFiles:(id)sender
  1566. {
  1567. // Remove all item
  1568. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1569. pasteboard.items = [[NSArray alloc] init];
  1570. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1571. for (tableMetadata *metadata in selectedMetadatas) {
  1572. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1573. [self copyFileToPasteboard:metadata];
  1574. } else {
  1575. metadata.session = k_download_session;
  1576. metadata.sessionError = @"";
  1577. metadata.sessionSelector = selectorLoadCopy;
  1578. metadata.status = k_metadataStatusWaitDownload;
  1579. // Add Metadata for Download
  1580. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1581. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1582. [appDelegate startLoadAutoDownloadUpload];
  1583. }
  1584. }
  1585. [self tableViewSelect:false];
  1586. }
  1587. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1588. {
  1589. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1590. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1591. // Value : (NSData) ocId
  1592. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1593. [items addObject:item];
  1594. [pasteboard setItems:items];
  1595. }
  1596. /************************************ OPEN IN ... ******************************/
  1597. - (void)openinTouchFile:(id)sender
  1598. {
  1599. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1600. }
  1601. /************************************ OPEN INTERNAL VIEWER ... ******************************/
  1602. - (void)openInternalViewerTouch:(id)sender
  1603. {
  1604. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileInternalView];
  1605. }
  1606. /************************************ PASTE ************************************/
  1607. - (void)pasteTouchFile:(id)sender
  1608. {
  1609. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1610. [self uploadFilePasteArray:[pasteboard items]];
  1611. }
  1612. - (void)pasteTouchFiles:(id)sender
  1613. {
  1614. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1615. [self uploadFilePasteArray:[pasteboard items]];
  1616. }
  1617. - (void)uploadFilePasteArray:(NSArray *)items
  1618. {
  1619. for (NSDictionary *dic in items) {
  1620. // Value : (NSData) ocId
  1621. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1622. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1623. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1624. if (metadata) {
  1625. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1626. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1627. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:self.serverUrl fileNameView:fileName directory:false];
  1628. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1629. tableMetadata *metadataForUpload = [tableMetadata new];
  1630. metadataForUpload.account = appDelegate.activeAccount;
  1631. metadataForUpload.date = [NSDate new];
  1632. metadataForUpload.ocId = ocId;
  1633. metadataForUpload.fileName = fileName;
  1634. metadataForUpload.fileNameView = fileName;
  1635. metadataForUpload.serverUrl = self.serverUrl;
  1636. metadataForUpload.session = k_upload_session;
  1637. metadataForUpload.sessionSelector = selectorUploadFile;
  1638. metadataForUpload.size = metadata.size;
  1639. metadataForUpload.status = k_metadataStatusWaitUpload;
  1640. // Add Medtadata for upload
  1641. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1642. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1643. }
  1644. }
  1645. }
  1646. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1647. [appDelegate startLoadAutoDownloadUpload];
  1648. }
  1649. #pragma --------------------------------------------------------------------------------------------
  1650. #pragma mark ===== Lock Passcode =====
  1651. #pragma --------------------------------------------------------------------------------------------
  1652. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  1653. {
  1654. return _failedAttempts;
  1655. }
  1656. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  1657. {
  1658. return _lockUntilDate;
  1659. }
  1660. - (void)passcodeViewCloseButtonPressed:(id)sender
  1661. {
  1662. [self dismissViewControllerAnimated:YES completion:nil];
  1663. }
  1664. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  1665. {
  1666. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  1667. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  1668. _lockUntilDate = nil;
  1669. _failedAttempts = 0;
  1670. aResultHandler(YES);
  1671. } else aResultHandler(NO);
  1672. } else aResultHandler(YES);
  1673. }
  1674. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  1675. {
  1676. [aViewController dismissViewControllerAnimated:YES completion:nil];
  1677. switch (aViewController.type) {
  1678. case BKPasscodeViewControllerCheckPasscodeType: {
  1679. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  1680. // possiamo procedere alla prossima directory
  1681. [self performSegueDirectoryWithControlPasscode:false metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  1682. // avviamo la sessione Passcode Lock con now
  1683. appDelegate.sessionePasscodeLock = [NSDate date];
  1684. }
  1685. // disattivazione lock cartella
  1686. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  1687. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  1688. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO account:appDelegate.activeAccount]) {
  1689. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1690. }
  1691. [self tableViewReloadData];
  1692. }
  1693. }
  1694. break;
  1695. default:
  1696. break;
  1697. }
  1698. }
  1699. - (void)comandoLockPassword
  1700. {
  1701. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  1702. // se non è abilitato il Lock Passcode esci
  1703. if ([[CCUtility getBlockCode] length] == 0) {
  1704. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1705. UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_go_to_app_settings_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1706. [self.tabBarController setSelectedIndex:4];
  1707. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1708. NSIndexPath *selectedIndex = [NSIndexPath indexPathForRow:0 inSection:1];
  1709. [appDelegate.activeMore.tableView selectRowAtIndexPath:selectedIndex animated:true scrollPosition: UITableViewScrollPositionNone];
  1710. [appDelegate.activeMore tableView:appDelegate.activeMore.tableView didSelectRowAtIndexPath:selectedIndex];
  1711. });
  1712. }];
  1713. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1714. [alertController addAction:goToSettingsAction];
  1715. [alertController addAction:okAction];
  1716. [self presentViewController:alertController animated:YES completion:nil];
  1717. return;
  1718. }
  1719. // se è richiesta la disattivazione si chiede la password
  1720. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  1721. if (directory.lock) {
  1722. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  1723. viewController.delegate = self;
  1724. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  1725. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  1726. viewController.inputViewTitlePassword = YES;
  1727. if ([CCUtility getSimplyBlockCode]) {
  1728. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  1729. viewController.passcodeInputView.maximumLength = 6;
  1730. } else {
  1731. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  1732. viewController.passcodeInputView.maximumLength = 64;
  1733. }
  1734. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  1735. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  1736. viewController.touchIDManager = touchIDManager;
  1737. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  1738. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  1739. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  1740. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  1741. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1742. [self presentViewController:navigationController animated:YES completion:nil];
  1743. return;
  1744. }
  1745. // ---------------- ACTIVATE PASSWORD
  1746. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES account:appDelegate.activeAccount]) {
  1747. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:self.metadata.ocId];
  1748. if ([self indexPathIsValid:indexPath])
  1749. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  1750. } else {
  1751. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1752. }
  1753. }
  1754. #pragma mark -
  1755. #pragma --------------------------------------------------------------------------------------------
  1756. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1757. #pragma --------------------------------------------------------------------------------------------
  1758. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1759. {
  1760. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  1761. return NO;
  1762. // E2EE
  1763. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  1764. return NO;
  1765. return YES;
  1766. }
  1767. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1768. {
  1769. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1770. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1771. return [self canOpenMenuAction:metadata];
  1772. }
  1773. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1774. {
  1775. }
  1776. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1777. {
  1778. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1779. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1780. if (direction == MGSwipeDirectionRightToLeft) {
  1781. [self actionDelete:indexPath];
  1782. }
  1783. if (direction == MGSwipeDirectionLeftToRight) {
  1784. [[NCNetworking sharedInstance] favoriteMetadata:self.metadata url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1785. }
  1786. return YES;
  1787. }
  1788. - (void)actionDelete:(NSIndexPath *)indexPath
  1789. {
  1790. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1791. // Directory locked ?
  1792. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:metadata.fileName];
  1793. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  1794. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1795. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  1796. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_folder_blocked_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1797. return;
  1798. }
  1799. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1800. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1801. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1802. }]];
  1803. if (localFile) {
  1804. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1805. tableMetadata *metadataLivePhoto = [[NCUtility sharedInstance] isLivePhotoWithMetadata:metadata];
  1806. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1807. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1808. if (metadataLivePhoto) {
  1809. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1810. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1811. }
  1812. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1813. }]];
  1814. }
  1815. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1816. }]];
  1817. alertController.popoverPresentationController.sourceView = self.tableView;
  1818. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1819. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1820. [alertController.view layoutIfNeeded];
  1821. [self presentViewController:alertController animated:YES completion:nil];
  1822. }
  1823. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1824. {
  1825. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1826. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1827. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1828. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1829. }
  1830. #pragma --------------------------------------------------------------------------------------------
  1831. #pragma mark - ==== Datasource ====
  1832. #pragma --------------------------------------------------------------------------------------------
  1833. - (void)clearDateReadDataSource:(NSNotification *)notification
  1834. {
  1835. _dateReadDataSource = Nil;
  1836. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1837. }
  1838. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId action:(NSInteger)action
  1839. {
  1840. // test
  1841. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  1842. return;
  1843. // Search Mode
  1844. if (self.searchController.isActive) {
  1845. // Create metadatas
  1846. NSMutableArray *metadatas = [NSMutableArray new];
  1847. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1848. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  1849. if (metadata) {
  1850. [metadatas addObject:metadata];
  1851. }
  1852. }
  1853. // [CCUtility getGroupBySettings]
  1854. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  1855. [self tableViewReloadData];
  1856. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1857. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1858. _noFilesSearchDescription = @"";
  1859. }
  1860. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1861. _noFilesSearchTitle = @"";
  1862. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1863. }
  1864. [self.tableView reloadEmptyDataSet];
  1865. return;
  1866. }
  1867. // Se non siamo nella dir appropriata esci
  1868. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  1869. return;
  1870. }
  1871. // Controllo data lettura Data Source
  1872. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1873. if (tableDirectory == nil) {
  1874. return;
  1875. }
  1876. // Get MetadataFolder
  1877. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  1878. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  1879. else
  1880. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tableDirectory.ocId]];
  1881. // Remove optimization for encrypted directory
  1882. if (_metadataFolder.e2eEncrypted)
  1883. _dateReadDataSource = nil;
  1884. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  1885. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  1886. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  1887. _dateReadDataSource = [NSDate date];
  1888. // Data Source
  1889. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1890. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  1891. dispatch_async(dispatch_get_main_queue(), ^{
  1892. sectionDataSource = sectionDataSourceTemp;
  1893. [self tableViewReloadData];
  1894. });
  1895. });
  1896. } else {
  1897. [self tableViewReloadData];
  1898. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  1899. }
  1900. // BLINK
  1901. if (self.blinkFileNamePath != nil) {
  1902. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1903. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1904. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1905. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1906. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1907. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1908. if ([key isEqualToString:metadata.ocId]) {
  1909. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1910. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1911. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1912. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1913. if (cell) {
  1914. self.blinkFileNamePath = nil;
  1915. [[NCUtility sharedInstance] blinkWithCell:cell];
  1916. }
  1917. });
  1918. }
  1919. }
  1920. }
  1921. }
  1922. });
  1923. }
  1924. }
  1925. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  1926. {
  1927. // test
  1928. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  1929. return nil;
  1930. }
  1931. // get auto upload folder
  1932. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1933. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  1934. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  1935. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl] sorted:nil ascending:NO];
  1936. // [CCUtility getGroupBySettings]
  1937. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  1938. if (withReloadData) {
  1939. sectionDataSource = sectionDataSourceTemp;
  1940. [self tableViewReloadData];
  1941. }
  1942. return sectionDataSourceTemp;
  1943. }
  1944. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1945. {
  1946. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1947. if (selectedRows.count > 0) {
  1948. for (NSIndexPath *selectionIndex in selectedRows) {
  1949. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1950. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1951. [metadatas addObject:metadata];
  1952. }
  1953. }
  1954. return metadatas;
  1955. }
  1956. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1957. {
  1958. NSInteger totSections =[sectionDataSource.sections count] ;
  1959. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1960. return nil;
  1961. }
  1962. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1963. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1964. }
  1965. #pragma --------------------------------------------------------------------------------------------
  1966. #pragma mark - ==== Table ====
  1967. #pragma --------------------------------------------------------------------------------------------
  1968. - (void)tableViewToggle
  1969. {
  1970. [self tableViewSelect:!_isSelectedMode];
  1971. }
  1972. - (void)tableViewSelect:(BOOL)toggle
  1973. {
  1974. _isSelectedMode = toggle;
  1975. // chiudiamo eventuali swipe aperti
  1976. if (_isSelectedMode)
  1977. [self.tableView setEditing:NO animated:NO];
  1978. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1979. [self.tableView setEditing:_isSelectedMode animated:YES];
  1980. if (_isSelectedMode)
  1981. [self setUINavigationBarSelected];
  1982. else
  1983. [self setUINavigationBarDefault];
  1984. [_selectedocIdsMetadatas removeAllObjects];
  1985. [self setTitle];
  1986. }
  1987. - (void)tableViewReloadData
  1988. {
  1989. // store selected cells before relod
  1990. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1991. // reload table view
  1992. [self.tableView reloadData];
  1993. // selected cells stored
  1994. for (NSIndexPath *path in indexPaths)
  1995. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  1996. [self setTableViewHeader];
  1997. [self setTableViewFooter];
  1998. if (self.tableView.editing)
  1999. [self setTitle];
  2000. [self.tableView reloadEmptyDataSet];
  2001. }
  2002. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2003. {
  2004. if (tableView.editing == 1) {
  2005. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2006. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2007. return NO;
  2008. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2009. return NO;
  2010. else
  2011. return YES;
  2012. } else {
  2013. [_selectedocIdsMetadatas removeAllObjects];
  2014. }
  2015. return YES;
  2016. }
  2017. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2018. {
  2019. return 60;
  2020. }
  2021. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2022. {
  2023. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2024. }
  2025. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2026. {
  2027. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2028. }
  2029. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2030. {
  2031. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2032. NSString *sectionTitle = [sections objectAtIndex:section];
  2033. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2034. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2035. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2036. return 20.f;
  2037. }
  2038. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2039. {
  2040. float shift;
  2041. UIVisualEffectView *visualEffectView;
  2042. NSString *titleSection;
  2043. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2044. return nil;
  2045. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2046. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2047. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2048. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2049. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2050. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2051. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2052. else titleSection = NSLocalizedString(titleSection,nil);
  2053. // Format title
  2054. UIVisualEffect *blurEffect;
  2055. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2056. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2057. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brand colorWithAlphaComponent:0.2];
  2058. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  2059. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2060. shift = - 35;
  2061. else
  2062. shift = - 20;
  2063. } else shift = - 10;
  2064. // Title
  2065. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2066. titleLabel.backgroundColor = [UIColor clearColor];
  2067. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  2068. titleLabel.font = [UIFont systemFontOfSize:12];
  2069. titleLabel.textAlignment = NSTextAlignmentLeft;
  2070. titleLabel.text = titleSection;
  2071. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2072. [visualEffectView.contentView addSubview:titleLabel];
  2073. // Elements
  2074. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2075. elementLabel.backgroundColor = [UIColor clearColor];
  2076. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  2077. elementLabel.font = [UIFont systemFontOfSize:12];
  2078. elementLabel.textAlignment = NSTextAlignmentRight;
  2079. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2080. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2081. NSUInteger rowsCount = [metadatas count];
  2082. if (rowsCount == 0) return nil;
  2083. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2084. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2085. [visualEffectView.contentView addSubview:elementLabel];
  2086. return visualEffectView;
  2087. }
  2088. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2089. {
  2090. return [sectionDataSource.sections indexOfObject:title];
  2091. }
  2092. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2093. {
  2094. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  2095. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2096. else
  2097. return nil;
  2098. }
  2099. /*
  2100. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2101. {
  2102. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  2103. }
  2104. }
  2105. */
  2106. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2107. {
  2108. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2109. tableShare *shareCell;
  2110. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  2111. return [CCCellMain new];
  2112. }
  2113. for (tableShare *share in appDelegate.shares) {
  2114. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  2115. shareCell = share;
  2116. break;
  2117. }
  2118. }
  2119. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  2120. // NORMAL - > MAIN
  2121. if ([cell isKindOfClass:[CCCellMain class]]) {
  2122. // Comment tap
  2123. if (metadata.commentsUnread) {
  2124. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  2125. [tapComment setNumberOfTapsRequired:1];
  2126. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  2127. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  2128. }
  2129. // Share add Tap
  2130. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  2131. [tapShare setNumberOfTapsRequired:1];
  2132. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  2133. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  2134. // More
  2135. if ([self canOpenMenuAction:metadata]) {
  2136. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  2137. [tapMore setNumberOfTapsRequired:1];
  2138. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  2139. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  2140. }
  2141. // MGSwipeButton
  2142. ((CCCellMain *)cell).delegate = self;
  2143. // LEFT
  2144. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  2145. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  2146. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  2147. //centerIconOverText
  2148. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  2149. [favoriteButton centerIconOverText];
  2150. // RIGHT
  2151. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  2152. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  2153. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  2154. //centerIconOverText
  2155. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  2156. [deleteButton centerIconOverText];
  2157. }
  2158. // TRANSFER
  2159. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  2160. // gesture Transfer
  2161. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  2162. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  2163. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  2164. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  2165. }
  2166. return cell;
  2167. }
  2168. - (void)setTableViewHeader
  2169. {
  2170. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  2171. if (capabilities.versionMajor < k_nextcloud_version_18_0 || self.richWorkspaceText.length == 0 || self.searchController.isActive) {
  2172. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  2173. } else {
  2174. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  2175. }
  2176. [self.searchController.searchBar sizeToFit];
  2177. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  2178. [self.tableView reloadData];
  2179. }
  2180. - (void)setTableViewFooter
  2181. {
  2182. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2183. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2184. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2185. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2186. UIFont *appFont = [UIFont systemFontOfSize:12];
  2187. footerLabel.font = appFont;
  2188. footerLabel.textColor = [UIColor grayColor];
  2189. footerLabel.backgroundColor = [UIColor clearColor];
  2190. footerLabel.textAlignment = NSTextAlignmentCenter;
  2191. NSString *folders;
  2192. NSString *files;
  2193. NSString *footerText;
  2194. if (sectionDataSource.directories > 1) {
  2195. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2196. } else if (sectionDataSource.directories == 1){
  2197. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2198. } else {
  2199. folders = @"";
  2200. }
  2201. if (sectionDataSource.files > 1) {
  2202. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2203. } else if (sectionDataSource.files == 1){
  2204. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2205. } else {
  2206. files = @"";
  2207. }
  2208. if ([folders isEqualToString:@""]) {
  2209. footerText = files;
  2210. } else if ([files isEqualToString:@""]) {
  2211. footerText = folders;
  2212. } else {
  2213. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2214. }
  2215. footerLabel.text = footerText;
  2216. [footerView addSubview:footerLabel];
  2217. [self.tableView setTableFooterView:footerView];
  2218. }
  2219. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2220. {
  2221. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2222. // settiamo il record file.
  2223. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2224. if (!self.metadata)
  2225. return;
  2226. // se non può essere selezionata deseleziona
  2227. if ([cell isEditing] == NO)
  2228. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2229. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2230. if (self.tableView.editing) {
  2231. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  2232. [self setTitle];
  2233. return;
  2234. }
  2235. // se è in corso una sessione
  2236. if (self.metadata.status != k_metadataStatusNormal)
  2237. return;
  2238. // file
  2239. if (self.metadata.directory == NO) {
  2240. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  2241. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2242. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  2243. } else {
  2244. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2245. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2246. } else {
  2247. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  2248. [self shouldPerformSegue:self.metadata selector:@""];
  2249. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditing:self.metadata] != nil) {
  2250. if (appDelegate.reachability.isReachable) {
  2251. [self shouldPerformSegue:self.metadata selector:@""];
  2252. } else {
  2253. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2254. }
  2255. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  2256. if (appDelegate.reachability.isReachable) {
  2257. [self shouldPerformSegue:self.metadata selector:@""];
  2258. } else {
  2259. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2260. }
  2261. } else {
  2262. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  2263. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  2264. }
  2265. self.metadata.session = k_download_session;
  2266. self.metadata.sessionError = @"";
  2267. self.metadata.sessionSelector = selectorLoadFileView;
  2268. self.metadata.status = k_metadataStatusWaitDownload;
  2269. // Add Metadata for Download
  2270. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2271. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2272. [appDelegate startLoadAutoDownloadUpload];
  2273. }
  2274. }
  2275. }
  2276. }
  2277. if (self.metadata.directory) {
  2278. [self performSegueDirectoryWithControlPasscode:true metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2279. }
  2280. }
  2281. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  2282. {
  2283. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2284. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  2285. [self setTitle];
  2286. }
  2287. - (void)didSelectAll
  2288. {
  2289. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  2290. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  2291. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  2292. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2293. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  2294. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  2295. }
  2296. }
  2297. [self setTitle];
  2298. }
  2299. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  2300. {
  2301. if (!indexPath)
  2302. return NO;
  2303. NSInteger section = indexPath.section;
  2304. NSInteger row = indexPath.row;
  2305. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  2306. if (section > lastSectionIndex || lastSectionIndex < 0)
  2307. return NO;
  2308. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  2309. if (rowCount < 0)
  2310. return NO;
  2311. return row <= rowCount;
  2312. }
  2313. #pragma --------------------------------------------------------------------------------------------
  2314. #pragma mark ===== Navigation ====
  2315. #pragma --------------------------------------------------------------------------------------------
  2316. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  2317. {
  2318. // if background return
  2319. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  2320. if (self.view.window == NO)
  2321. return;
  2322. // Collapsed ma siamo già in detail esci
  2323. if (self.splitViewController.isCollapsed) {
  2324. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  2325. }
  2326. // Metadata for push detail
  2327. self.metadataForPushDetail = metadata;
  2328. self.selectorForPushDetail = selector;
  2329. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  2330. }
  2331. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  2332. {
  2333. tableMetadata *metadata;
  2334. NSMutableArray *photoDataSource = [NSMutableArray new];
  2335. UINavigationController *navigationController = segue.destinationViewController;
  2336. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  2337. if ([sender isKindOfClass:[tableMetadata class]]) {
  2338. metadata = sender;
  2339. [photoDataSource addObject:sender];
  2340. } else {
  2341. metadata = self.metadataForPushDetail;
  2342. for (NSString *ocId in sectionDataSource.allOcId) {
  2343. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2344. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  2345. [photoDataSource addObject:metadata];
  2346. }
  2347. }
  2348. detailViewController.metadata = metadata;
  2349. detailViewController.selector = self.selectorForPushDetail;
  2350. [detailViewController setTitle:metadata.fileNameView];
  2351. }
  2352. // can i go to next viewcontroller
  2353. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode metadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  2354. {
  2355. NSString *nomeDir;
  2356. if (self.tableView.editing == NO) {
  2357. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  2358. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadata.account, lockServerUrl]];
  2359. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  2360. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  2361. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2362. viewController.delegate = self;
  2363. viewController.fromType = CCBKPasscodeFromLockDirectory;
  2364. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2365. viewController.inputViewTitlePassword = YES;
  2366. if ([CCUtility getSimplyBlockCode]) {
  2367. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2368. viewController.passcodeInputView.maximumLength = 6;
  2369. } else {
  2370. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2371. viewController.passcodeInputView.maximumLength = 64;
  2372. }
  2373. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2374. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2375. viewController.touchIDManager = touchIDManager;
  2376. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  2377. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2378. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2379. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2380. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  2381. [self presentViewController:navigationController animated:YES completion:nil];
  2382. return;
  2383. }
  2384. // E2EE Check enable
  2385. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  2386. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2387. return;
  2388. }
  2389. nomeDir = metadata.fileName;
  2390. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  2391. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  2392. if (!viewController) {
  2393. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  2394. viewController.serverUrl = serverUrlPush;
  2395. viewController.titleMain = metadata.fileNameView;
  2396. viewController.blinkFileNamePath = blinkFileNamePath;
  2397. // save self
  2398. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  2399. [self.navigationController pushViewController:viewController animated:YES];
  2400. } else {
  2401. if (viewController.isViewLoaded) {
  2402. viewController.titleMain = metadata.fileNameView;
  2403. viewController.blinkFileNamePath = blinkFileNamePath;
  2404. // Fix : Application tried to present modally an active controller
  2405. if ([self.navigationController isBeingPresented]) {
  2406. // being presented
  2407. } else if ([self.navigationController isMovingToParentViewController]) {
  2408. // being pushed
  2409. } else {
  2410. [self.navigationController pushViewController:viewController animated:YES];
  2411. }
  2412. }
  2413. }
  2414. }
  2415. }
  2416. @end