CCMain.m 114 KB

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