CCMain.m 112 KB

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