CCMain.m 115 KB

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