CCMain.m 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651
  1. //
  2. // CCMain.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 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 "NCAutoUpload.h"
  26. #import "NCBridgeSwift.h"
  27. #import "PKDownloadButton.h"
  28. @interface CCMain () <UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, NCSelectDelegate, UITextFieldDelegate, UIAdaptivePresentationControllerDelegate>
  29. {
  30. AppDelegate *appDelegate;
  31. BOOL _isRoot;
  32. BOOL _isViewDidLoad;
  33. NSMutableDictionary *_selectedocIdsMetadatas;
  34. UIImageView *_imageTitleHome;
  35. NSUInteger _failedAttempts;
  36. NSDate *_lockUntilDate;
  37. UIRefreshControl *refreshControl;
  38. CCHud *_hud;
  39. // Datasource
  40. CCSectionDataSourceMetadata *sectionDataSource;
  41. // Search
  42. NSString *_searchFileName;
  43. NSMutableArray *_searchResultMetadatas;
  44. NSString *_noFilesSearchTitle;
  45. NSString *_noFilesSearchDescription;
  46. NSTimer *_timerWaitInput;
  47. // Automatic Upload Folder
  48. NSString *_autoUploadFileName;
  49. NSString *_autoUploadDirectory;
  50. // Folder
  51. BOOL _loadingFolder;
  52. tableMetadata *_metadataFolder;
  53. CGFloat heightRichWorkspace;
  54. CGFloat heightSearchBar;
  55. //
  56. NSMutableArray *arrayDeleteMetadata;
  57. NSMutableArray *arrayMoveMetadata;
  58. NSMutableArray *arrayMoveServerUrlTo;
  59. NSMutableArray *arrayCopyMetadata;
  60. NSMutableArray *arrayCopyServerUrlTo;
  61. }
  62. @end
  63. @implementation CCMain
  64. #pragma --------------------------------------------------------------------------------------------
  65. #pragma mark ===== Init =====
  66. #pragma --------------------------------------------------------------------------------------------
  67. - (id)initWithCoder:(NSCoder *)aDecoder
  68. {
  69. if (self = [super initWithCoder:aDecoder]) {
  70. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  71. appDelegate.activeMain = self;
  72. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:k_notificationCenter_initializeMain object:nil];
  73. }
  74. return self;
  75. }
  76. #pragma --------------------------------------------------------------------------------------------
  77. #pragma mark ===== View =====
  78. #pragma --------------------------------------------------------------------------------------------
  79. - (void)viewDidLoad
  80. {
  81. [super viewDidLoad];
  82. // init object
  83. self.metadata = [tableMetadata new];
  84. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  85. _selectedocIdsMetadatas = [NSMutableDictionary new];
  86. _isViewDidLoad = YES;
  87. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  88. _searchResultMetadatas = [NSMutableArray new];
  89. _searchFileName = @"";
  90. _noFilesSearchTitle = @"";
  91. _noFilesSearchDescription = @"";
  92. _cellFavouriteImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:[UIColor whiteColor]];
  93. _cellTrashImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"trash"] width:50 height:50 color:[UIColor whiteColor]];
  94. arrayDeleteMetadata = [NSMutableArray new];
  95. arrayMoveMetadata = [NSMutableArray new];
  96. arrayMoveServerUrlTo = [NSMutableArray new];
  97. arrayCopyMetadata = [NSMutableArray new];
  98. arrayCopyServerUrlTo = [NSMutableArray new];
  99. // delegate
  100. self.tableView.tableFooterView = [UIView new];
  101. self.tableView.emptyDataSetDelegate = self;
  102. self.tableView.emptyDataSetSource = self;
  103. self.searchController.delegate = self;
  104. self.searchController.searchBar.delegate = self;
  105. // Notification
  106. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasource:) name:k_notificationCenter_reloadDataSource object:nil];
  107. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:k_notificationCenter_setTitleMain object:nil];
  108. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:k_notificationCenter_progressTask object:nil];
  109. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  110. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(favoriteFile:) name:k_notificationCenter_favoriteFile object:nil];
  111. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  112. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  113. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:k_notificationCenter_changeTheming object:nil];
  114. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createFolder:) name:k_notificationCenter_createFolder object:nil];
  115. // Search
  116. self.definesPresentationContext = YES;
  117. self.searchController.searchResultsUpdater = self;
  118. self.searchController.dimsBackgroundDuringPresentation = NO;
  119. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  120. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  121. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  122. }
  123. UITextField *searchTextField = [self.searchController.searchBar valueForKey:@"searchField"];
  124. if (searchTextField && [searchTextField isKindOfClass:[UITextField class]]) {
  125. searchTextField.textColor = NCBrandColor.sharedInstance.textView;
  126. }
  127. // Load Rich Workspace
  128. self.viewRichWorkspace = [[[NSBundle mainBundle] loadNibNamed:@"NCRichWorkspace" owner:self options:nil] firstObject];
  129. UITapGestureRecognizer *viewRichWorkspaceTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewRichWorkspaceTapAction:)];
  130. viewRichWorkspaceTapped.numberOfTapsRequired = 1;
  131. viewRichWorkspaceTapped.delegate = self;
  132. [self.viewRichWorkspace.richView addGestureRecognizer:viewRichWorkspaceTapped];
  133. self.sortButton = self.viewRichWorkspace.sortButton;
  134. heightSearchBar = self.viewRichWorkspace.topView.frame.size.height;
  135. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  136. [self.sortButton addTarget:self action:@selector(toggleSortMenu) forControlEvents:UIControlEventTouchUpInside];
  137. heightRichWorkspace = UIScreen.mainScreen.bounds.size.height / 4 + heightSearchBar;
  138. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, heightRichWorkspace)];
  139. self.navigationItem.searchController = self.searchController;
  140. self.searchController.hidesNavigationBarDuringPresentation = true;
  141. self.navigationController.navigationBar.prefersLargeTitles = true;
  142. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  143. // Table Header View
  144. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  145. // Register cell
  146. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  147. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  148. self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 35, 0);
  149. // long press recognizer TableView
  150. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  151. [self.tableView addGestureRecognizer:longPressRecognizer];
  152. // Pull-to-Refresh
  153. [self createRefreshControl];
  154. // Register for 3D Touch Previewing if available
  155. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  156. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  157. }
  158. // if this is not Main (the Main uses inizializeMain)
  159. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  160. // Read (File) Folder
  161. [self readFileReloadFolder];
  162. }
  163. // Title
  164. [self setTitle];
  165. // changeTheming
  166. [self changeTheming];
  167. }
  168. - (void)willDismissSearchController:(UISearchController *)searchController
  169. {
  170. [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
  171. }
  172. - (void)willPresentSearchController:(UISearchController *)searchController
  173. {
  174. [self updateNavBarShadow:self.tableView force:true];
  175. }
  176. - (void)viewWillAppear:(BOOL)animated
  177. {
  178. [super viewWillAppear:animated];
  179. [self updateNavBarShadow:self.tableView force:false];
  180. if(_isViewDidLoad && _isRoot) {
  181. self.navigationItem.hidesSearchBarWhenScrolling = false;
  182. [self.navigationController.navigationBar sizeToFit];
  183. }
  184. // test
  185. if (appDelegate.activeAccount.length == 0)
  186. return;
  187. if (_isSelectedMode)
  188. [self setUINavigationBarSelected];
  189. else
  190. [self setUINavigationBarDefault];
  191. // If not editing mode remove _selectedocIds
  192. if (!self.tableView.editing)
  193. [_selectedocIdsMetadatas removeAllObjects];
  194. // Check server URL "/"
  195. if (self.navigationController.viewControllers.firstObject == self && self.serverUrl == nil) {
  196. self.serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  197. }
  198. // RichWorkspace
  199. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  200. if (![self.richWorkspaceText isEqualToString:directory.richWorkspace]) {
  201. self.richWorkspaceText = directory.richWorkspace;
  202. [self setTableViewHeader];
  203. }
  204. // Query data source
  205. if (self.searchController.isActive == false) {
  206. [self reloadDatasource:self.serverUrl ocId:nil];
  207. }
  208. }
  209. - (void)viewDidAppear:(BOOL)animated
  210. {
  211. [super viewDidAppear:animated];
  212. if(_isViewDidLoad && _isRoot) {
  213. self.navigationItem.hidesSearchBarWhenScrolling = true;
  214. }
  215. // Active Main
  216. appDelegate.activeMain = self;
  217. // Test viewDidLoad
  218. if (_isViewDidLoad) {
  219. _isViewDidLoad = NO;
  220. } else {
  221. if (appDelegate.activeAccount.length > 0 && [_selectedocIdsMetadatas count] == 0) {
  222. // Read (file) Folder
  223. [self readFileReloadFolder];
  224. }
  225. }
  226. // Title
  227. [self setTitle];
  228. }
  229. - (void)viewWillDisappear:(BOOL)animated
  230. {
  231. [super viewWillDisappear:animated];
  232. }
  233. - (void) viewDidLayoutSubviews
  234. {
  235. [super viewDidLayoutSubviews];
  236. [self setTableViewHeader];
  237. }
  238. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  239. {
  240. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  241. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  242. [self.tableView beginUpdates];
  243. [self.tableView endUpdates];
  244. [self setTableViewHeader];
  245. } completion:^(id<UIViewControllerTransitionCoordinatorContext> context){
  246. [self updateNavBarShadow:self.tableView force:false];
  247. }];
  248. }
  249. - (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController
  250. {
  251. [self viewDidAppear:true];
  252. }
  253. - (BOOL)prefersStatusBarHidden
  254. {
  255. return NO;
  256. }
  257. // detect scroll for remove keyboard in search mode
  258. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  259. {
  260. if (self.searchController.isActive && scrollView == self.tableView) {
  261. [self.searchController.searchBar endEditing:YES];
  262. }
  263. }
  264. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  265. [self updateNavBarShadow:self.tableView force:false];
  266. }
  267. - (void)changeTheming
  268. {
  269. [appDelegate changeTheming:self tableView:self.tableView collectionView:nil form:false];
  270. // Refresh control
  271. refreshControl.tintColor = UIColor.lightGrayColor;
  272. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  273. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  274. // color searchbar
  275. self.searchController.searchBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  276. // color searchbbar button text (cancel)
  277. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  278. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  279. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  280. }
  281. // color textview searchbbar
  282. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  283. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  284. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  285. }
  286. // Rich Workspace
  287. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  288. // Title
  289. [self setTitle];
  290. // Reload Table View
  291. [self tableViewReloadData];
  292. }
  293. #pragma --------------------------------------------------------------------------------------------
  294. #pragma mark ===== Initialization =====
  295. #pragma --------------------------------------------------------------------------------------------
  296. //
  297. // Callers :
  298. //
  299. // ChangeDefaultAccount (delegate)
  300. // Split : inizialize
  301. // Settings Advanced : removeAllFiles
  302. //
  303. - (void)initializeMain:(NSNotification *)notification
  304. {
  305. // test
  306. if (appDelegate.activeAccount.length == 0)
  307. return;
  308. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  309. // This is Root home main add list
  310. appDelegate.homeMain = self;
  311. _isRoot = YES;
  312. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  313. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  314. // go Home
  315. [self.navigationController popToRootViewControllerAnimated:NO];
  316. // Remove search mode
  317. [self cancelSearchBar];
  318. // Clear error certificate
  319. [CCUtility setCertificateError:appDelegate.activeAccount error:NO];
  320. // Setting Theming
  321. [appDelegate settingThemingColorBrand];
  322. // Detail
  323. // If AVPlayer in play -> Stop
  324. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  325. [appDelegate.player pause];
  326. }
  327. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_menuDetailClose object:nil];
  328. // Not Photos Video in library ? then align and Init Auto Upload
  329. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.activeAccount]];
  330. if ([recordsPhotoLibrary count] == 0) {
  331. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  332. }
  333. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  334. NSLog(@"[LOG] Request Service Server Nextcloud");
  335. [[NCService shared] startRequestServicesServer];
  336. // Read this folder
  337. [self readFileReloadFolder];
  338. } else {
  339. // reload datasource
  340. [self reloadDatasource:_serverUrl ocId:nil];
  341. }
  342. // Registeration push notification
  343. [appDelegate pushNotification];
  344. // Registeration domain File Provider
  345. if (k_fileProvider_domain) {
  346. [FileProviderDomain.sharedInstance registerDomain];
  347. } else {
  348. [FileProviderDomain.sharedInstance removeAllDomain];
  349. }
  350. }
  351. #pragma --------------------------------------------------------------------------------------------
  352. #pragma mark ==== NotificationCenter ====
  353. #pragma --------------------------------------------------------------------------------------------
  354. - (void)createFolder:(NSNotification *)notification
  355. {
  356. NSDictionary *userInfo = notification.userInfo;
  357. NSString *serverUrl = userInfo[@"serverUrl"];
  358. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  359. if (![serverUrl isEqualToString:self.serverUrl]) { return; }
  360. if (errorCode == 0) {
  361. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:nil account:appDelegate.activeAccount];
  362. if (isFolderEncrypted) {
  363. [self readFolder:serverUrl];
  364. }
  365. }
  366. }
  367. - (void)deleteFile:(NSNotification *)notification
  368. {
  369. NSDictionary *userInfo = notification.userInfo;
  370. tableMetadata *metadata = userInfo[@"metadata"];
  371. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  372. NSString *errorDescription = userInfo[@"errorDescription"];
  373. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  374. if (arrayDeleteMetadata.count > 0) {
  375. tableMetadata *metadata = arrayDeleteMetadata.firstObject;
  376. [arrayDeleteMetadata removeObjectAtIndex:0];
  377. [[NCNetworking shared] deleteMetadata:metadata account:metadata.account url:metadata.url completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  378. }
  379. if (errorCode == 0 ) {
  380. if ([metadata.fileNameView.lowercaseString isEqualToString:k_fileNameRichWorkspace.lowercaseString]) {
  381. [self readFileReloadFolder];
  382. } else {
  383. if (self.searchController.isActive) {
  384. [self readFolder:self.serverUrl];
  385. }
  386. }
  387. }
  388. if (errorCode != 0 && self.view.window != nil) {
  389. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  390. }
  391. }
  392. - (void)moveFile:(NSNotification *)notification
  393. {
  394. NSDictionary *userInfo = notification.userInfo;
  395. tableMetadata *metadata = userInfo[@"metadata"];
  396. // tableMetadata *metadataNew = userInfo[@"metadataNew"];
  397. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  398. NSString *errorDescription = userInfo[@"errorDescription"];
  399. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  400. if (arrayMoveMetadata.count > 0) {
  401. tableMetadata *metadata = arrayMoveMetadata.firstObject;
  402. NSString *serverUrlTo = arrayMoveServerUrlTo.firstObject;
  403. [arrayMoveMetadata removeObjectAtIndex:0];
  404. [arrayMoveServerUrlTo removeObjectAtIndex:0];
  405. [[NCNetworking shared] moveMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  406. }
  407. if (errorCode != 0 && self.view.window != nil) {
  408. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  409. }
  410. }
  411. - (void)copyFile:(NSNotification *)notification
  412. {
  413. NSDictionary *userInfo = notification.userInfo;
  414. tableMetadata *metadata = userInfo[@"metadata"];
  415. // NSString *serverUrlTo = userInfo[@"serverUrlTo"];
  416. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  417. NSString *errorDescription = userInfo[@"errorDescription"];
  418. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  419. if (arrayCopyMetadata.count > 0) {
  420. tableMetadata *metadata = arrayCopyMetadata.firstObject;
  421. NSString *serverUrlTo = arrayCopyServerUrlTo.firstObject;
  422. [arrayCopyMetadata removeObjectAtIndex:0];
  423. [arrayCopyServerUrlTo removeObjectAtIndex:0];
  424. [[NCNetworking shared] copyMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  425. }
  426. if (errorCode != 0 && self.view.window != nil) {
  427. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  428. }
  429. }
  430. - (void)favoriteFile:(NSNotification *)notification
  431. {
  432. if (self.view.window == nil) { return; }
  433. NSDictionary *userInfo = notification.userInfo;
  434. tableMetadata *metadata = userInfo[@"metadata"];
  435. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  436. NSString *errorDescription = userInfo[@"errorDescription"];
  437. BOOL favorite = [userInfo[@"favorite"] boolValue];
  438. if (errorCode == 0) {
  439. if (self.searchController.isActive) {
  440. [self readFolder:self.serverUrl];
  441. }
  442. if (metadata.directory && favorite) {
  443. if ([CCUtility getFavoriteOffline]) {
  444. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorDownloadSynchronize];
  445. } else {
  446. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorSynchronize];
  447. }
  448. } else if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  449. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorDownloadSynchronize setFavorite:true completion:^(NSInteger errorCode) { }];
  450. }
  451. } else {
  452. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  453. }
  454. }
  455. #pragma --------------------------------------------------------------------------------------------
  456. #pragma mark ==== DZNEmptyDataSetSource ====
  457. #pragma --------------------------------------------------------------------------------------------
  458. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  459. {
  460. if (_loadingFolder)
  461. return NO;
  462. else
  463. return YES;
  464. }
  465. - (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
  466. {
  467. CGFloat height = self.tabBarController.tabBar.frame.size.height;
  468. return -height;
  469. }
  470. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  471. {
  472. return NCBrandColor.sharedInstance.backgroundView;
  473. }
  474. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  475. {
  476. if (self.searchController.isActive)
  477. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  478. else
  479. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  480. }
  481. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  482. {
  483. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  484. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  485. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  486. activityView.color = NCBrandColor.sharedInstance.brandElement;
  487. [activityView startAnimating];
  488. return activityView;
  489. }
  490. return nil;
  491. }
  492. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  493. {
  494. NSString *text;
  495. if (self.searchController.isActive) {
  496. text = _noFilesSearchTitle;
  497. } else {
  498. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  499. }
  500. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  501. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  502. }
  503. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  504. {
  505. NSString *text;
  506. if (self.searchController.isActive) {
  507. text = _noFilesSearchDescription;
  508. } else {
  509. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  510. }
  511. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  512. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  513. paragraph.alignment = NSTextAlignmentCenter;
  514. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  515. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  516. }
  517. #pragma --------------------------------------------------------------------------------------------
  518. #pragma mark ===== Text Field =====
  519. #pragma --------------------------------------------------------------------------------------------
  520. - (void)minCharTextFieldDidChange:(UITextField *)sender
  521. {
  522. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  523. if (alertController)
  524. {
  525. UITextField *fileName = alertController.textFields.firstObject;
  526. UIAlertAction *okAction = alertController.actions.lastObject;
  527. okAction.enabled = fileName.text.length > 0;
  528. }
  529. }
  530. - (void)textFieldDidBeginEditing:(UITextField *)textField
  531. {
  532. [CCUtility selectFileNameFrom:textField];
  533. }
  534. #pragma --------------------------------------------------------------------------------------------
  535. #pragma mark ===== Graphic Window =====
  536. #pragma --------------------------------------------------------------------------------------------
  537. - (void)createRefreshControl
  538. {
  539. refreshControl = [NCMainRefreshControl new];
  540. self.tableView.refreshControl = refreshControl;
  541. refreshControl.tintColor = UIColor.lightGrayColor;
  542. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  543. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  544. }
  545. - (void)deleteRefreshControl
  546. {
  547. [refreshControl endRefreshing];
  548. [refreshControl removeFromSuperview];
  549. refreshControl = nil;
  550. }
  551. - (void)refreshControlTarget
  552. {
  553. [self readFolder:_serverUrl];
  554. // Actuate `Peek` feedback (weak boom)
  555. AudioServicesPlaySystemSound(1519);
  556. }
  557. - (void)setTitle
  558. {
  559. if (_isSelectedMode) {
  560. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  561. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  562. self.navigationItem.titleView = nil;
  563. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  564. } else {
  565. if (_isRoot) {
  566. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  567. } else {
  568. self.navigationItem.title = _titleMain;
  569. }
  570. }
  571. [self SetSortButtonText];
  572. }
  573. - (void)setUINavigationBarDefault
  574. {
  575. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  576. self.navigationController.navigationBar.hidden = NO;
  577. self.navigationItem.rightBarButtonItem = buttonSelect;
  578. self.navigationItem.leftBarButtonItem = nil;
  579. }
  580. - (void)setUINavigationBarSelected
  581. {
  582. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationMore"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleSelectMenu)];
  583. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  584. self.navigationItem.leftBarButtonItem = leftButton;
  585. self.navigationItem.rightBarButtonItem = buttonMore; //[[NSArray alloc] initWithObjects:buttonMore, nil];
  586. }
  587. - (void)cancelSelect
  588. {
  589. [self tableViewSelect:false];
  590. }
  591. #pragma --------------------------------------------------------------------------------------------
  592. #pragma mark ===== Document Picker =====
  593. #pragma --------------------------------------------------------------------------------------------
  594. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  595. {
  596. NSLog(@"[LOG] Cancelled");
  597. }
  598. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  599. {
  600. NSLog(@"[LOG] Cancelled");
  601. }
  602. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  603. {
  604. documentPicker.delegate = self;
  605. [self presentViewController:documentPicker animated:YES completion:nil];
  606. }
  607. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  608. {
  609. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  610. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  611. __block NSError *error;
  612. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  613. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  614. NSString *fileName = [url lastPathComponent];
  615. NSString *ocId = [[NSUUID UUID] UUIDString];
  616. NSData *data = [NSData dataWithContentsOfURL:newURL];
  617. if (data && error == nil) {
  618. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  619. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:ocId serverUrl:serverUrl urlBase:appDelegate.activeUrl url:@"" contentType:@""];
  620. metadataForUpload.session = NCCommunicationCommon.shared.sessionIdentifierBackground;
  621. metadataForUpload.sessionSelector = selectorUploadFile;
  622. metadataForUpload.size = data.length;
  623. metadataForUpload.status = k_metadataStatusWaitUpload;
  624. if ([[NCUtility sharedInstance] getMetadataConflictWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileName] != nil) {
  625. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  626. conflict.serverUrl = self.serverUrl;
  627. conflict.metadatasUploadInConflict = @[metadataForUpload];
  628. [self presentViewController:conflict animated:YES completion:nil];
  629. } else {
  630. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  631. [[appDelegate networkingAutoUpload] startProcess];
  632. }
  633. } else {
  634. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  635. }
  636. } else {
  637. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  638. }
  639. }];
  640. }
  641. }
  642. - (void)openImportDocumentPicker
  643. {
  644. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  645. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  646. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  647. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  648. documentProviderMenu.delegate = self;
  649. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  650. }
  651. #pragma --------------------------------------------------------------------------------------------
  652. #pragma mark ===== Assets Picker =====
  653. #pragma --------------------------------------------------------------------------------------------
  654. -(void)dismissFormUploadAssets
  655. {
  656. }
  657. - (void)openAssetsPickerController
  658. {
  659. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  660. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets, NSArray<NSURL *> * urls) {
  661. if (assets.count > 0) {
  662. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  663. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  664. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets urls:(NSMutableArray *)urls cryptated:NO session:NCCommunicationCommon.shared.sessionIdentifierBackground delegate:self];
  665. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  666. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  667. [self presentViewController:navigationController animated:YES completion:nil];
  668. });
  669. }
  670. }];
  671. }
  672. #pragma --------------------------------------------------------------------------------------------
  673. #pragma mark ===== Save selected File =====
  674. #pragma --------------------------------------------------------------------------------------------
  675. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  676. {
  677. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  678. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  679. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  680. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  681. if (image)
  682. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  683. else
  684. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  685. }
  686. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  687. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  688. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  689. } else {
  690. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  691. }
  692. }
  693. if (status != PHAuthorizationStatusAuthorized) {
  694. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  695. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  696. [alertController addAction:okAction];
  697. [self presentViewController:alertController animated:YES completion:nil];
  698. }
  699. }
  700. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  701. {
  702. if (error) {
  703. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  704. }
  705. }
  706. - (void)saveSelectedFiles
  707. {
  708. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  709. return;
  710. NSLog(@"[LOG] Start download selected files ...");
  711. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  712. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  713. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  714. for (tableMetadata *metadata in metadatas) {
  715. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  716. [[NCOperationQueue shared] downloadWithMetadata:metadata selector:selectorSave setFavorite:false];
  717. }
  718. }
  719. [_hud hideHud];
  720. });
  721. [self tableViewSelect:false];
  722. }
  723. #pragma mark -
  724. #pragma --------------------------------------------------------------------------------------------
  725. #pragma mark ===== Peek & Pop =====
  726. #pragma --------------------------------------------------------------------------------------------
  727. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  728. {
  729. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  730. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  731. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  732. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  733. if (cell) {
  734. previewingContext.sourceRect = cell.frame;
  735. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  736. viewController.metadata = metadata;
  737. viewController.imageFile = cell.file.image;
  738. viewController.showOpenIn = true;
  739. viewController.showShare = true;
  740. viewController.showOpenQuickLook = [[NCUtility sharedInstance] isQuickLookDisplayableWithMetadata:metadata];
  741. return viewController;
  742. }
  743. return nil;
  744. }
  745. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  746. {
  747. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  748. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  749. }
  750. #pragma --------------------------------------------------------------------------------------------
  751. #pragma mark ==== Download ====
  752. #pragma --------------------------------------------------------------------------------------------
  753. - (void)downloadSelectedFilesFolders
  754. {
  755. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  756. return;
  757. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  758. for (tableMetadata *metadata in selectedMetadatas) {
  759. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorDownloadSynchronize];
  760. }
  761. [self tableViewSelect:false];
  762. }
  763. #pragma --------------------------------------------------------------------------------------------
  764. #pragma mark ===== Upload new Photos/Videos =====
  765. #pragma --------------------------------------------------------------------------------------------
  766. - (void)uploadFileAsset:(NSMutableArray *)assets urls:(NSMutableArray *)urls serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  767. {
  768. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  769. // if request create the folder for Auto Upload & the subfolders
  770. if ([autoUploadPath isEqualToString:serverUrl]) {
  771. if ([[NCNetworking shared] createFoloderWithAssets:(PHFetchResult *)assets selector:selectorUploadFile useSubFolder:useSubFolder account:appDelegate.activeAccount url:appDelegate.activeUrl]) {
  772. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError forced:true];
  773. return;
  774. }
  775. }
  776. [self uploadFileAsset:assets urls:urls serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  777. }
  778. - (void)uploadFileAsset:(NSArray *)assets urls:(NSArray *)urls serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  779. {
  780. NSMutableArray *metadatasNOConflict = [NSMutableArray new];
  781. NSMutableArray *metadatasMOV = [NSMutableArray new];
  782. NSMutableArray *metadatasUploadInConflict = [NSMutableArray new];
  783. for (PHAsset *asset in assets) {
  784. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  785. NSDate *assetDate = asset.creationDate;
  786. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  787. // Create serverUrl if use sub folder
  788. if (useSubFolder) {
  789. [formatter setDateFormat:@"yyyy"];
  790. NSString *yearString = [formatter stringFromDate:assetDate];
  791. [formatter setDateFormat:@"MM"];
  792. NSString *monthString = [formatter stringFromDate:assetDate];
  793. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  794. }
  795. // Check if is in upload
  796. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.activeAccount, serverUrl, fileName] page:0 limit:0 sorted:@"fileName" ascending:NO];
  797. if ([isRecordInSessions count] > 0)
  798. continue;
  799. // Prepare record metadata
  800. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase:appDelegate.activeUrl url:@"" contentType:@""];
  801. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  802. metadataForUpload.session = session;
  803. metadataForUpload.sessionSelector = selectorUploadFile;
  804. metadataForUpload.size = [[NCUtilityFileSystem shared] getFileSizeWithAsset:asset];
  805. metadataForUpload.status = k_metadataStatusWaitUpload;
  806. if ([[NCUtility sharedInstance] getMetadataConflictWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileName] != nil) {
  807. [metadatasUploadInConflict addObject:metadataForUpload];
  808. } else {
  809. [metadatasNOConflict addObject:metadataForUpload];
  810. }
  811. // Add Medtadata MOV LIVE PHOTO for upload
  812. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto && urls.count == assets.count) {
  813. NSUInteger index = [assets indexOfObject:asset];
  814. NSURL *url = [urls objectAtIndex:index];
  815. NSString *fileNameNoExt = [fileName stringByDeletingPathExtension];
  816. NSString *fileName = [NSString stringWithFormat:@"%@.mov", fileNameNoExt];
  817. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  818. tableMetadata *metadataMOVForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase:appDelegate.activeUrl url:@"" contentType:@""];
  819. metadataMOVForUpload.session = session;
  820. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  821. metadataMOVForUpload.size = fileSize;
  822. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  823. // Prepare file and directory
  824. [CCUtility copyFileAtPath:url.path toPath:[CCUtility getDirectoryProviderStorageOcId:metadataMOVForUpload.ocId fileNameView:fileName]];
  825. [metadatasMOV addObject:metadataMOVForUpload];
  826. }
  827. }
  828. // Verify if file(s) exists
  829. if (metadatasUploadInConflict.count > 0) {
  830. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  831. conflict.serverUrl = self.serverUrl;
  832. conflict.metadatasNOConflict = metadatasNOConflict;
  833. conflict.metadatasMOV = metadatasMOV;
  834. conflict.metadatasUploadInConflict = metadatasUploadInConflict;
  835. [self presentViewController:conflict animated:YES completion:nil];
  836. } else {
  837. [[NCManageDatabase sharedInstance] addMetadatas:metadatasNOConflict];
  838. [[NCManageDatabase sharedInstance] addMetadatas:metadatasMOV];
  839. [[appDelegate networkingAutoUpload] startProcess];
  840. }
  841. }
  842. #pragma --------------------------------------------------------------------------------------------
  843. #pragma mark ==== Read Folder ====
  844. #pragma --------------------------------------------------------------------------------------------
  845. - (void)readFolder:(NSString *)serverUrl
  846. {
  847. // init control
  848. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  849. [refreshControl endRefreshing];
  850. return;
  851. }
  852. // Search Mode
  853. if (self.searchController.isActive) {
  854. _searchFileName = @""; // forced reload searchg
  855. [self updateSearchResultsForSearchController:self.searchController];
  856. return;
  857. }
  858. _loadingFolder = YES;
  859. [refreshControl endRefreshing];
  860. [self tableViewReloadData];
  861. [[NCNetworking shared] readFolderWithServerUrl:serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSArray *metadatasChanged, NSInteger errorCode, NSString *errorDescription) {
  862. if (errorCode == 0 ) {
  863. _metadataFolder = metadataFolder;
  864. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.activeAccount];
  865. [self setTitle];
  866. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  867. for (tableMetadata *metadata in metadatasChanged) {
  868. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  869. if (localFile != nil) {
  870. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorDownloadSynchronize setFavorite:false completion:^(NSInteger errorCode) { }];
  871. }
  872. }
  873. });
  874. // E2EE Is encrypted folder get metadata
  875. if (isFolderEncrypted) {
  876. if ([CCUtility isEndToEndEnabled:account]) {
  877. [[NCCommunication shared] getE2EEMetadataWithFileId:metadataFolder.fileId e2eToken:nil customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *e2eMetadata, NSInteger errorCode, NSString *errorDescription) {
  878. if (errorCode == 0 && e2eMetadata != nil) {
  879. BOOL result = [[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eMetadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:appDelegate.activeUrl];
  880. if (result == false) {
  881. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorDecodeMetadata forced:true];
  882. }
  883. } else if (errorCode != 404) {
  884. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  885. }
  886. [self reloadDatasource:_serverUrl ocId:nil];
  887. }];
  888. } else {
  889. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  890. }
  891. }
  892. } else {
  893. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  894. }
  895. _loadingFolder = NO;
  896. [self reloadDatasource:serverUrl ocId:nil];
  897. }];
  898. }
  899. - (void)readFileReloadFolder
  900. {
  901. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  902. return;
  903. [[NCNetworking shared] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  904. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  905. // Rich Workspace
  906. [[NCManageDatabase sharedInstance] setDirectoryWithRichWorkspace:metadata.richWorkspace serverUrl:self.serverUrl account:appDelegate.activeAccount];
  907. if (![self.richWorkspaceText isEqualToString:metadata.richWorkspace]) {
  908. self.richWorkspaceText = metadata.richWorkspace;
  909. }
  910. [self setTableViewHeader];
  911. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  912. // Read folder: No record, Change etag or BLINK
  913. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  914. [self readFolder:self.serverUrl];
  915. }
  916. } else if (errorCode != 0) {
  917. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  918. }
  919. }];
  920. }
  921. #pragma mark -
  922. #pragma --------------------------------------------------------------------------------------------
  923. #pragma mark ===== Search =====
  924. #pragma --------------------------------------------------------------------------------------------
  925. - (void)searchStartTimer
  926. {
  927. if (self.searchController.isActive == false) {
  928. return;
  929. }
  930. [[NCCommunication shared] searchLiteralWithServerUrl:appDelegate.activeUrl depth:@"infinity" literal:_searchFileName showHiddenFiles:[CCUtility getShowHiddenFiles] customUserAgent:nil addCustomHeaders:nil user:appDelegate.activeUser completionHandler:^(NSString *account, NSArray *files, NSInteger errorCode, NSString *errorDescription) {
  931. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount] && files != nil) {
  932. [[NCManageDatabase sharedInstance] convertNCCommunicationFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  933. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  934. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  935. _metadataFolder = nil;
  936. [self reloadDatasource:_serverUrl ocId:nil];
  937. [self tableViewReloadData];
  938. [self setTitle];
  939. }];
  940. } else {
  941. if (errorCode != 0) {
  942. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  943. }
  944. _searchFileName = @"";
  945. [self cancelSearchBar];
  946. }
  947. }];
  948. _noFilesSearchTitle = @"";
  949. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  950. [self.tableView reloadEmptyDataSet];
  951. }
  952. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  953. {
  954. // Color text "Cancel"
  955. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brandElement];
  956. if (searchController.isActive) {
  957. [self deleteRefreshControl];
  958. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  959. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  960. _searchFileName = fileName;
  961. _metadataFolder = nil;
  962. // First : filter
  963. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] page:0 limit:0 sorted:@"fileName" ascending:NO];
  964. [_searchResultMetadatas removeAllObjects];
  965. for (tableMetadata *record in records) {
  966. [_searchResultMetadatas addObject:record];
  967. }
  968. // Version >= 12
  969. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.activeAccount elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  970. if (serverVersionMajor >= 12) {
  971. [_timerWaitInput invalidate];
  972. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  973. }
  974. [self setTitle];
  975. }
  976. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  977. [self reloadDatasource:_serverUrl ocId:nil];
  978. }
  979. } else {
  980. [self createRefreshControl];
  981. [self reloadDatasource:_serverUrl ocId:nil];
  982. }
  983. }
  984. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  985. {
  986. [self cancelSearchBar];
  987. }
  988. - (void)cancelSearchBar
  989. {
  990. if (self.searchController.active) {
  991. [self.searchController setActive:NO];
  992. _searchFileName = @"";
  993. _searchResultMetadatas = [NSMutableArray new];
  994. [self reloadDatasource:_serverUrl ocId:nil];
  995. }
  996. }
  997. #pragma mark -
  998. #pragma --------------------------------------------------------------------------------------------
  999. #pragma mark ===== Delete File or Folder =====
  1000. #pragma --------------------------------------------------------------------------------------------
  1001. - (void)deleteMetadatas
  1002. {
  1003. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1004. return;
  1005. if ([_selectedocIdsMetadatas count] > 0) {
  1006. [arrayDeleteMetadata addObjectsFromArray:[_selectedocIdsMetadatas allValues]];
  1007. } else {
  1008. [arrayDeleteMetadata addObject:self.metadata];
  1009. }
  1010. [[NCNetworking shared] deleteMetadata:arrayDeleteMetadata.firstObject account:appDelegate.activeAccount url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1011. [arrayDeleteMetadata removeObjectAtIndex:0];
  1012. // End Select Table View
  1013. [self tableViewSelect:false];
  1014. }
  1015. #pragma --------------------------------------------------------------------------------------------
  1016. #pragma mark ===== Move / Copy =====
  1017. #pragma --------------------------------------------------------------------------------------------
  1018. - (void)moveCopyFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo move:(BOOL)move overwrite:(BOOL)overwrite
  1019. {
  1020. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1021. return;
  1022. NSMutableArray *arrayMetadata, *arrayServerUrlTo;
  1023. if (move) {
  1024. arrayMetadata = arrayMoveMetadata;
  1025. arrayServerUrlTo = arrayMoveServerUrlTo;
  1026. } else {
  1027. arrayMetadata = arrayCopyMetadata;
  1028. arrayServerUrlTo = arrayCopyServerUrlTo;
  1029. }
  1030. if ([_selectedocIdsMetadatas count] > 0) {
  1031. for (NSString *key in _selectedocIdsMetadatas) {
  1032. tableMetadata *metadata = [_selectedocIdsMetadatas objectForKey:key];
  1033. [arrayMetadata addObject:metadata];
  1034. [arrayServerUrlTo addObject:serverUrlTo];
  1035. }
  1036. } else {
  1037. [arrayMetadata addObject:metadata];
  1038. [arrayServerUrlTo addObject:serverUrlTo];
  1039. }
  1040. if (move) {
  1041. [[NCNetworking shared] moveMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1042. } else {
  1043. [[NCNetworking shared] copyMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1044. }
  1045. [arrayMetadata removeObjectAtIndex:0];
  1046. [arrayServerUrlTo removeObjectAtIndex:0];
  1047. // End Select Table View
  1048. [self tableViewSelect:false];
  1049. }
  1050. // DELEGATE : Select
  1051. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  1052. {
  1053. if (serverUrl != nil) {
  1054. // E2EE DENIED
  1055. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1056. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"_e2e_error_not_move_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotMove forced:true];
  1057. return;
  1058. }
  1059. BOOL move = true;
  1060. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  1061. if ([_selectedocIdsMetadatas count] > 0) {
  1062. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1063. [self moveCopyFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl move:move overwrite:overwrite];
  1064. } else {
  1065. [self moveCopyFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl move:move overwrite:overwrite];
  1066. }
  1067. }
  1068. }
  1069. - (void)moveOpenWindow:(NSArray *)indexPaths
  1070. {
  1071. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1072. return;
  1073. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1074. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1075. viewController.delegate = self;
  1076. viewController.hideButtonCreateFolder = false;
  1077. viewController.selectFile = false;
  1078. viewController.includeDirectoryE2EEncryption = false;
  1079. viewController.includeImages = false;
  1080. viewController.type = @"";
  1081. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1082. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  1083. viewController.isButtonDone1Hide = false;
  1084. viewController.isOverwriteHide = false;
  1085. viewController.layoutViewSelect = k_layout_view_move;
  1086. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1087. [self presentViewController:navigationController animated:YES completion:nil];
  1088. }
  1089. #pragma --------------------------------------------------------------------------------------------
  1090. #pragma mark ===== Create folder =====
  1091. #pragma --------------------------------------------------------------------------------------------
  1092. - (void)createFolder
  1093. {
  1094. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1095. NSString *message;
  1096. UIAlertController *alertController;
  1097. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1098. message = @"/";
  1099. } else {
  1100. message = [serverUrl lastPathComponent];
  1101. }
  1102. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1103. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1104. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1105. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1106. }];
  1107. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1108. NSLog(@"[LOG] Cancel action");
  1109. }];
  1110. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1111. UITextField *fileName = alertController.textFields.firstObject;
  1112. [[NCNetworking shared] createFolderWithFileName:[fileName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] serverUrl:serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl overwrite:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1113. }];
  1114. okAction.enabled = NO;
  1115. [alertController addAction:cancelAction];
  1116. [alertController addAction:okAction];
  1117. [self presentViewController:alertController animated:YES completion:nil];
  1118. }
  1119. #pragma --------------------------------------------------------------------------------------------
  1120. #pragma mark ===== Progress & Task Button =====
  1121. #pragma --------------------------------------------------------------------------------------------
  1122. - (void)triggerProgressTask:(NSNotification *)notification
  1123. {
  1124. if (sectionDataSource.ocIdIndexPath != nil) {
  1125. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1126. }
  1127. }
  1128. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1129. {
  1130. UITouch *touch = [[event allTouches] anyObject];
  1131. CGPoint location = [touch locationInView:self.tableView];
  1132. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1133. if ([self indexPathIsValid:indexPath]) {
  1134. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1135. if (metadataSection) {
  1136. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadataSection reloadDatasource:true uploadStatusForcedStart:false];
  1137. }
  1138. }
  1139. }
  1140. - (void)cancelAllTask:(id)sender
  1141. {
  1142. CGPoint location = [sender locationInView:self.tableView];
  1143. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1144. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1145. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1146. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1147. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1148. [NCUtility.sharedInstance stopActivityIndicator];
  1149. }]];
  1150. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1151. alertController.popoverPresentationController.sourceView = self.tableView;
  1152. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1153. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1154. [alertController.view layoutIfNeeded];
  1155. [self presentViewController:alertController animated:YES completion:nil];
  1156. }
  1157. #pragma --------------------------------------------------------------------------------------------
  1158. #pragma mark ===== Tap =====
  1159. #pragma --------------------------------------------------------------------------------------------
  1160. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1161. {
  1162. CGPoint location = [tapGesture locationInView:self.tableView];
  1163. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1164. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1165. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1166. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1167. }
  1168. }
  1169. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1170. {
  1171. CGPoint location = [tapGesture locationInView:self.tableView];
  1172. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1173. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1174. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1175. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1176. }
  1177. }
  1178. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1179. {
  1180. CGPoint location = [tapGesture locationInView:self.tableView];
  1181. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1182. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1183. if (metadata) {
  1184. }
  1185. }
  1186. #pragma --------------------------------------------------------------------------------------------
  1187. #pragma mark ===== Rich Workspace =====
  1188. #pragma --------------------------------------------------------------------------------------------
  1189. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1190. {
  1191. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1192. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1193. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1194. viewerRichWorkspace.serverUrl = self.serverUrl;
  1195. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1196. [self presentViewController:navigationController animated:NO completion:NULL];
  1197. }
  1198. - (void)createRichWorkspace
  1199. {
  1200. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1201. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1202. if (metadata) {
  1203. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1204. } else {
  1205. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1206. }
  1207. }
  1208. - (void)toggleSortMenu
  1209. {
  1210. [self toggleMenuWithViewController:self.navigationController];
  1211. }
  1212. - (void)toggleSelectMenu
  1213. {
  1214. [self toggleSelectMenuWithViewController:self.navigationController];
  1215. }
  1216. #pragma --------------------------------------------------------------------------------------------
  1217. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1218. #pragma --------------------------------------------------------------------------------------------
  1219. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1220. {
  1221. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1222. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1223. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1224. NSMutableArray *items = [NSMutableArray new];
  1225. if ([self indexPathIsValid:indexPath])
  1226. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1227. [self becomeFirstResponder];
  1228. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1229. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1230. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1231. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1232. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1233. }
  1234. if ([[NCUtility sharedInstance] isQuickLookDisplayableWithMetadata:self.metadata]) {
  1235. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_quicklook_", nil) action:@selector(openQuickLookTouch:)]];
  1236. }
  1237. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1238. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1239. [menuController setMenuItems:items];
  1240. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1241. [menuController setMenuVisible:YES animated:YES];
  1242. }
  1243. }
  1244. - (BOOL)canBecomeFirstResponder
  1245. {
  1246. return YES;
  1247. }
  1248. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1249. {
  1250. // For copy file, copy files, Open in ... :
  1251. //
  1252. // NO Directory
  1253. // NO Error Passcode
  1254. // NO In Session mode (download/upload)
  1255. // NO Template
  1256. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openQuickLookTouch:) == action) {
  1257. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1258. else return NO;
  1259. }
  1260. if (@selector(copyTouchFiles:) == action) {
  1261. if (_isSelectedMode) {
  1262. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1263. for (tableMetadata *metadata in selectedMetadatas) {
  1264. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1265. return YES;
  1266. }
  1267. }
  1268. return NO;
  1269. }
  1270. if (@selector(pasteTouchFile:) == action) {
  1271. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1272. NSArray *items = [pasteboard items];
  1273. if ([items count] == 1) {
  1274. // Value : (NSData) ocId
  1275. NSDictionary *dic = [items objectAtIndex:0];
  1276. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1277. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1278. if (ocId) {
  1279. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1280. if (metadata) {
  1281. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1282. } else {
  1283. return NO;
  1284. }
  1285. }
  1286. }
  1287. return NO;
  1288. }
  1289. if (@selector(pasteTouchFiles:) == action) {
  1290. BOOL isValid = NO;
  1291. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1292. NSArray *items = [pasteboard items];
  1293. if ([items count] <= 1) return NO;
  1294. for (NSDictionary *dic in items) {
  1295. // Value : (NSData) ocId
  1296. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1297. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1298. if (ocId) {
  1299. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1300. if (metadata) {
  1301. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1302. isValid = YES;
  1303. } else {
  1304. isValid = NO;
  1305. break;
  1306. }
  1307. } else {
  1308. isValid = NO;
  1309. break;
  1310. }
  1311. } else {
  1312. isValid = NO;
  1313. break;
  1314. }
  1315. }
  1316. return isValid;
  1317. }
  1318. return NO;
  1319. }
  1320. /************************************ COPY ************************************/
  1321. - (void)copyTouchFile:(id)sender
  1322. {
  1323. // Remove all item
  1324. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1325. pasteboard.items = [[NSArray alloc] init];
  1326. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1327. [self copyFileToPasteboard:self.metadata];
  1328. } else {
  1329. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1330. }
  1331. }
  1332. - (void)copyTouchFiles:(id)sender
  1333. {
  1334. // Remove all item
  1335. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1336. pasteboard.items = [[NSArray alloc] init];
  1337. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1338. for (tableMetadata *metadata in selectedMetadatas) {
  1339. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1340. [self copyFileToPasteboard:metadata];
  1341. } else {
  1342. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1343. }
  1344. }
  1345. [self tableViewSelect:false];
  1346. }
  1347. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1348. {
  1349. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1350. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1351. // Value : (NSData) ocId
  1352. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1353. [items addObject:item];
  1354. [pasteboard setItems:items];
  1355. }
  1356. /************************************ OPEN IN ... ******************************/
  1357. - (void)openinTouchFile:(id)sender
  1358. {
  1359. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1360. }
  1361. /************************************ OPEN QUICK LOOK ******************************/
  1362. - (void)openQuickLookTouch:(id)sender
  1363. {
  1364. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileQuickLook];
  1365. }
  1366. /************************************ PASTE ************************************/
  1367. - (void)pasteTouchFile:(id)sender
  1368. {
  1369. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1370. [self uploadFilePasteArray:[pasteboard items]];
  1371. }
  1372. - (void)pasteTouchFiles:(id)sender
  1373. {
  1374. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1375. [self uploadFilePasteArray:[pasteboard items]];
  1376. }
  1377. - (void)uploadFilePasteArray:(NSArray *)items
  1378. {
  1379. for (NSDictionary *dic in items) {
  1380. // Value : (NSData) ocId
  1381. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1382. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1383. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1384. if (metadata) {
  1385. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1386. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1387. NSString *ocId = [[NSUUID UUID] UUIDString];
  1388. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1389. // Prepare record metadata
  1390. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:ocId serverUrl:self.serverUrl urlBase:appDelegate.activeUrl url:@"" contentType:@""];
  1391. metadataForUpload.session = NCCommunicationCommon.shared.sessionIdentifierBackground;
  1392. metadataForUpload.sessionSelector = selectorUploadFile;
  1393. metadataForUpload.size = metadata.size;
  1394. metadataForUpload.status = k_metadataStatusWaitUpload;
  1395. // Add Medtadata for upload
  1396. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1397. }
  1398. }
  1399. }
  1400. [[appDelegate networkingAutoUpload] startProcess];
  1401. }
  1402. #pragma mark -
  1403. #pragma --------------------------------------------------------------------------------------------
  1404. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1405. #pragma --------------------------------------------------------------------------------------------
  1406. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1407. {
  1408. if (metadata == nil)
  1409. return NO;
  1410. // E2EE
  1411. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  1412. return NO;
  1413. return YES;
  1414. }
  1415. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1416. {
  1417. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1418. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1419. return [self canOpenMenuAction:metadata];
  1420. }
  1421. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1422. {
  1423. }
  1424. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1425. {
  1426. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1427. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1428. if (direction == MGSwipeDirectionRightToLeft) {
  1429. [self actionDelete:indexPath];
  1430. }
  1431. if (direction == MGSwipeDirectionLeftToRight) {
  1432. [[NCNetworking shared] favoriteMetadata:self.metadata url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1433. }
  1434. return YES;
  1435. }
  1436. - (void)actionDelete:(NSIndexPath *)indexPath
  1437. {
  1438. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1439. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1440. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1441. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1442. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1443. }]];
  1444. if (localFile) {
  1445. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1446. tableMetadata *metadataLivePhoto = [[NCManageDatabase sharedInstance] isLivePhotoWithMetadata:metadata];
  1447. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1448. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1449. if (metadataLivePhoto) {
  1450. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1451. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1452. }
  1453. [self reloadDatasource:metadata.serverUrl ocId:metadata.ocId];
  1454. }]];
  1455. }
  1456. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1457. }]];
  1458. alertController.popoverPresentationController.sourceView = self.tableView;
  1459. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1460. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1461. [alertController.view layoutIfNeeded];
  1462. [self presentViewController:alertController animated:YES completion:nil];
  1463. }
  1464. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1465. {
  1466. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1467. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1468. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1469. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1470. }
  1471. #pragma --------------------------------------------------------------------------------------------
  1472. #pragma mark - ==== Datasource ====
  1473. #pragma --------------------------------------------------------------------------------------------
  1474. - (void)reloadDatasource:(NSNotification *)notification
  1475. {
  1476. NSDictionary *userInfo = notification.userInfo;
  1477. NSString *ocId = userInfo[@"ocId"];
  1478. NSString *serverUrl = userInfo[@"serverUrl"];
  1479. [self reloadDatasource:serverUrl ocId:ocId];
  1480. }
  1481. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId
  1482. {
  1483. // test
  1484. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil) // || self.view.window == nil)
  1485. return;
  1486. // Se non siamo nella dir appropriata esci
  1487. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil)
  1488. return;
  1489. // load share
  1490. appDelegate.shares = [[NCManageDatabase sharedInstance] getTableSharesWithAccount:appDelegate.activeAccount];
  1491. // Search Mode
  1492. if (self.searchController.isActive) {
  1493. // Create metadatas
  1494. NSMutableArray *metadatas = [NSMutableArray new];
  1495. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1496. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  1497. if (metadata) {
  1498. [metadatas addObject:metadata];
  1499. }
  1500. }
  1501. // [CCUtility getGroupBySettings]
  1502. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  1503. [self tableViewReloadData];
  1504. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1505. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1506. _noFilesSearchDescription = @"";
  1507. }
  1508. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1509. _noFilesSearchTitle = @"";
  1510. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1511. }
  1512. [self.tableView reloadEmptyDataSet];
  1513. return;
  1514. }
  1515. // Get MetadataFolder
  1516. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  1517. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  1518. else
  1519. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1520. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1521. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  1522. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1523. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl] page:0 limit:0 sorted:@"fileName" ascending:NO];
  1524. // [CCUtility getGroupBySettings]
  1525. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO filterLivePhoto:YES sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  1526. dispatch_async(dispatch_get_main_queue(), ^{
  1527. sectionDataSource = sectionDataSourceTemp;
  1528. [self tableViewReloadData];
  1529. });
  1530. });
  1531. // BLINK
  1532. if (self.blinkFileNamePath != nil) {
  1533. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1534. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1535. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1536. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1537. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1538. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1539. if ([key isEqualToString:metadata.ocId]) {
  1540. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1541. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1542. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1543. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1544. if (cell) {
  1545. self.blinkFileNamePath = nil;
  1546. [[NCUtility sharedInstance] blinkWithCell:cell];
  1547. }
  1548. });
  1549. }
  1550. }
  1551. }
  1552. }
  1553. });
  1554. }
  1555. }
  1556. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1557. {
  1558. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1559. if (selectedRows.count > 0) {
  1560. for (NSIndexPath *selectionIndex in selectedRows) {
  1561. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1562. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1563. [metadatas addObject:metadata];
  1564. }
  1565. }
  1566. return metadatas;
  1567. }
  1568. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1569. {
  1570. NSInteger totSections =[sectionDataSource.sections count] ;
  1571. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1572. return nil;
  1573. }
  1574. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1575. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1576. }
  1577. #pragma --------------------------------------------------------------------------------------------
  1578. #pragma mark - ==== Table ====
  1579. #pragma --------------------------------------------------------------------------------------------
  1580. - (void)tableViewToggle
  1581. {
  1582. [self tableViewSelect:!_isSelectedMode];
  1583. }
  1584. - (void)tableViewSelect:(BOOL)toggle
  1585. {
  1586. _isSelectedMode = toggle;
  1587. // chiudiamo eventuali swipe aperti
  1588. if (_isSelectedMode)
  1589. [self.tableView setEditing:NO animated:NO];
  1590. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1591. [self.tableView setEditing:_isSelectedMode animated:YES];
  1592. if (_isSelectedMode)
  1593. [self setUINavigationBarSelected];
  1594. else
  1595. [self setUINavigationBarDefault];
  1596. [_selectedocIdsMetadatas removeAllObjects];
  1597. [self setTitle];
  1598. }
  1599. - (void)tableViewReloadData
  1600. {
  1601. // store selected cells before relod
  1602. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1603. // reload table view
  1604. [self.tableView reloadData];
  1605. // selected cells stored
  1606. for (NSIndexPath *path in indexPaths)
  1607. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  1608. [self setTableViewHeader];
  1609. [self setTableViewFooter];
  1610. if (self.tableView.editing)
  1611. [self setTitle];
  1612. [self.tableView reloadEmptyDataSet];
  1613. }
  1614. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  1615. {
  1616. if (tableView.editing == 1) {
  1617. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1618. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  1619. return NO;
  1620. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  1621. return NO;
  1622. else
  1623. return YES;
  1624. } else {
  1625. [_selectedocIdsMetadatas removeAllObjects];
  1626. }
  1627. return YES;
  1628. }
  1629. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  1630. {
  1631. return 60;
  1632. }
  1633. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  1634. {
  1635. return [[sectionDataSource.sectionArrayRow allKeys] count];
  1636. }
  1637. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1638. {
  1639. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  1640. }
  1641. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  1642. {
  1643. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  1644. NSString *sectionTitle = [sections objectAtIndex:section];
  1645. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  1646. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  1647. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  1648. return 20.f;
  1649. }
  1650. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  1651. {
  1652. float shift;
  1653. UIVisualEffectView *visualEffectView;
  1654. NSString *titleSection;
  1655. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  1656. return nil;
  1657. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  1658. titleSection = [sectionDataSource.sections objectAtIndex:section];
  1659. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  1660. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  1661. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  1662. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  1663. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  1664. else titleSection = NSLocalizedString(titleSection,nil);
  1665. // Format title
  1666. UIVisualEffect *blurEffect;
  1667. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  1668. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  1669. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brandElement colorWithAlphaComponent:0.2];
  1670. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  1671. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1672. shift = - 35;
  1673. else
  1674. shift = - 20;
  1675. } else shift = - 10;
  1676. // Title
  1677. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  1678. titleLabel.backgroundColor = [UIColor clearColor];
  1679. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  1680. titleLabel.font = [UIFont systemFontOfSize:12];
  1681. titleLabel.textAlignment = NSTextAlignmentLeft;
  1682. titleLabel.text = titleSection;
  1683. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1684. [visualEffectView.contentView addSubview:titleLabel];
  1685. // Elements
  1686. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  1687. elementLabel.backgroundColor = [UIColor clearColor];
  1688. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  1689. elementLabel.font = [UIFont systemFontOfSize:12];
  1690. elementLabel.textAlignment = NSTextAlignmentRight;
  1691. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1692. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  1693. NSUInteger rowsCount = [metadatas count];
  1694. if (rowsCount == 0) return nil;
  1695. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  1696. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  1697. [visualEffectView.contentView addSubview:elementLabel];
  1698. return visualEffectView;
  1699. }
  1700. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  1701. {
  1702. return [sectionDataSource.sections indexOfObject:title];
  1703. }
  1704. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  1705. {
  1706. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  1707. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  1708. else
  1709. return nil;
  1710. }
  1711. /*
  1712. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  1713. {
  1714. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  1715. }
  1716. }
  1717. */
  1718. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1719. {
  1720. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1721. tableShare *shareCell;
  1722. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  1723. return [CCCellMain new];
  1724. }
  1725. for (tableShare *share in appDelegate.shares) {
  1726. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  1727. shareCell = share;
  1728. break;
  1729. }
  1730. }
  1731. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  1732. // NORMAL - > MAIN
  1733. if ([cell isKindOfClass:[CCCellMain class]]) {
  1734. // Comment tap
  1735. if (metadata.commentsUnread) {
  1736. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  1737. [tapComment setNumberOfTapsRequired:1];
  1738. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  1739. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  1740. }
  1741. // Share add Tap
  1742. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  1743. [tapShare setNumberOfTapsRequired:1];
  1744. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  1745. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  1746. // More
  1747. if ([self canOpenMenuAction:metadata]) {
  1748. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  1749. [tapMore setNumberOfTapsRequired:1];
  1750. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  1751. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  1752. }
  1753. // MGSwipeButton
  1754. ((CCCellMain *)cell).delegate = self;
  1755. // LEFT
  1756. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  1757. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  1758. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  1759. //centerIconOverText
  1760. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  1761. [favoriteButton centerIconOverText];
  1762. // RIGHT
  1763. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  1764. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  1765. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  1766. //centerIconOverText
  1767. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  1768. [deleteButton centerIconOverText];
  1769. }
  1770. // TRANSFER
  1771. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  1772. // gesture Transfer
  1773. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  1774. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  1775. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  1776. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  1777. }
  1778. return cell;
  1779. }
  1780. - (void)setTableViewHeader
  1781. {
  1782. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.activeAccount elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  1783. NSString *trimmedRichWorkspaceText = [self.richWorkspaceText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  1784. if (serverVersionMajor < k_nextcloud_version_18_0 || trimmedRichWorkspaceText.length == 0 ) {
  1785. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  1786. } else {
  1787. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  1788. }
  1789. if (self.searchController.isActive == true) {
  1790. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, 0)];
  1791. }
  1792. [self.viewRichWorkspace setNeedsLayout];
  1793. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  1794. }
  1795. - (void)setTableViewFooter
  1796. {
  1797. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1798. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1799. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1800. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1801. UIFont *appFont = [UIFont systemFontOfSize:12];
  1802. footerLabel.font = appFont;
  1803. footerLabel.textColor = [UIColor grayColor];
  1804. footerLabel.backgroundColor = [UIColor clearColor];
  1805. footerLabel.textAlignment = NSTextAlignmentCenter;
  1806. NSString *folders;
  1807. NSString *files;
  1808. NSString *footerText;
  1809. if (sectionDataSource.directories > 1) {
  1810. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  1811. } else if (sectionDataSource.directories == 1){
  1812. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  1813. } else {
  1814. folders = @"";
  1815. }
  1816. if (sectionDataSource.files > 1) {
  1817. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1818. } else if (sectionDataSource.files == 1){
  1819. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  1820. } else {
  1821. files = @"";
  1822. }
  1823. if ([folders isEqualToString:@""]) {
  1824. footerText = files;
  1825. } else if ([files isEqualToString:@""]) {
  1826. footerText = folders;
  1827. } else {
  1828. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  1829. }
  1830. footerLabel.text = footerText;
  1831. [footerView addSubview:footerLabel];
  1832. [self.tableView setTableFooterView:footerView];
  1833. }
  1834. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  1835. {
  1836. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  1837. // settiamo il record file.
  1838. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1839. if (!self.metadata)
  1840. return;
  1841. // se non può essere selezionata deseleziona
  1842. if ([cell isEditing] == NO)
  1843. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  1844. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  1845. if (self.tableView.editing) {
  1846. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  1847. [self setTitle];
  1848. return;
  1849. }
  1850. if (self.metadata.status != k_metadataStatusNormal && self.metadata.status != k_metadataStatusDownloadError) {
  1851. return;
  1852. }
  1853. // file
  1854. if (self.metadata.directory == NO) {
  1855. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  1856. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1857. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  1858. } else {
  1859. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1860. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  1861. } else {
  1862. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  1863. [self shouldPerformSegue:self.metadata selector:@""];
  1864. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditingWithAccount:self.metadata.account contentType:self.metadata.contentType] != nil) {
  1865. if (NCCommunication.shared.isNetworkReachable) {
  1866. [self shouldPerformSegue:self.metadata selector:@""];
  1867. } else {
  1868. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1869. }
  1870. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  1871. if (NCCommunication.shared.isNetworkReachable) {
  1872. [self shouldPerformSegue:self.metadata selector:@""];
  1873. } else {
  1874. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorOffline forced:true];
  1875. }
  1876. } else {
  1877. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1878. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  1879. }
  1880. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadFileView setFavorite:false completion:^(NSInteger errorCode) { }];
  1881. }
  1882. }
  1883. }
  1884. }
  1885. if (self.metadata.directory) {
  1886. [self performSegueDirectoryWithMetadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  1887. }
  1888. }
  1889. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  1890. {
  1891. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1892. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  1893. [self setTitle];
  1894. }
  1895. - (void)didSelectAll
  1896. {
  1897. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  1898. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  1899. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  1900. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1901. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  1902. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  1903. }
  1904. }
  1905. [self setTitle];
  1906. }
  1907. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  1908. {
  1909. if (!indexPath)
  1910. return NO;
  1911. NSInteger section = indexPath.section;
  1912. NSInteger row = indexPath.row;
  1913. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  1914. if (section > lastSectionIndex || lastSectionIndex < 0)
  1915. return NO;
  1916. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  1917. if (rowCount < 0)
  1918. return NO;
  1919. return row <= rowCount;
  1920. }
  1921. #pragma --------------------------------------------------------------------------------------------
  1922. #pragma mark ===== Navigation ====
  1923. #pragma --------------------------------------------------------------------------------------------
  1924. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  1925. {
  1926. // if background return
  1927. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  1928. if (self.view.window == NO)
  1929. return;
  1930. // Collapsed ma siamo già in detail esci
  1931. if (self.splitViewController.isCollapsed) {
  1932. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  1933. }
  1934. // Metadata for push detail
  1935. self.metadataForPushDetail = metadata;
  1936. self.selectorForPushDetail = selector;
  1937. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1938. }
  1939. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  1940. {
  1941. tableMetadata *metadata;
  1942. NSMutableArray *photoDataSource = [NSMutableArray new];
  1943. UINavigationController *navigationController = segue.destinationViewController;
  1944. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  1945. if ([sender isKindOfClass:[tableMetadata class]]) {
  1946. metadata = sender;
  1947. [photoDataSource addObject:sender];
  1948. } else {
  1949. metadata = self.metadataForPushDetail;
  1950. for (NSString *ocId in sectionDataSource.allOcId) {
  1951. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1952. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1953. [photoDataSource addObject:metadata];
  1954. }
  1955. }
  1956. detailViewController.metadata = metadata;
  1957. detailViewController.selector = self.selectorForPushDetail;
  1958. [detailViewController setTitle:metadata.fileNameView];
  1959. }
  1960. // can i go to next viewcontroller
  1961. - (void)performSegueDirectoryWithMetadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  1962. {
  1963. NSString *nomeDir;
  1964. if (self.tableView.editing == NO) {
  1965. // E2EE Check enable
  1966. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  1967. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  1968. return;
  1969. }
  1970. nomeDir = metadata.fileName;
  1971. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  1972. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  1973. if (!viewController) {
  1974. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  1975. viewController.serverUrl = serverUrlPush;
  1976. viewController.titleMain = metadata.fileNameView;
  1977. viewController.blinkFileNamePath = blinkFileNamePath;
  1978. // save self
  1979. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  1980. [self.navigationController pushViewController:viewController animated:YES];
  1981. } else {
  1982. if (viewController.isViewLoaded) {
  1983. viewController.titleMain = metadata.fileNameView;
  1984. viewController.blinkFileNamePath = blinkFileNamePath;
  1985. // Fix : Application tried to present modally an active controller
  1986. if ([self.navigationController isBeingPresented]) {
  1987. // being presented
  1988. } else if ([self.navigationController isMovingToParentViewController]) {
  1989. // being pushed
  1990. } else {
  1991. [self.navigationController pushViewController:viewController animated:YES];
  1992. }
  1993. }
  1994. }
  1995. }
  1996. }
  1997. @end