CCMain.m 114 KB

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