CCMain.m 112 KB

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