CCMain.m 115 KB

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