CCMain.m 117 KB

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