CCMain.m 117 KB

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