CCMain.m 116 KB

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