CCMain.m 117 KB

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