CCMain.m 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694
  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(changeTheming) name:k_notificationCenter_changeTheming 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(createFolder:) name:k_notificationCenter_createFolder object:nil];
  115. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDatasourceTransfer:) name:k_notificationCenter_renameFile 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. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:k_notificationCenter_progressTask object:nil];
  123. // Search
  124. self.definesPresentationContext = YES;
  125. self.searchController.searchResultsUpdater = self;
  126. self.searchController.dimsBackgroundDuringPresentation = NO;
  127. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  128. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  129. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  130. }
  131. UITextField *searchTextField = [self.searchController.searchBar valueForKey:@"searchField"];
  132. if (searchTextField && [searchTextField isKindOfClass:[UITextField class]]) {
  133. searchTextField.textColor = NCBrandColor.sharedInstance.textView;
  134. }
  135. // Load Rich Workspace
  136. self.viewRichWorkspace = [[[NSBundle mainBundle] loadNibNamed:@"NCRichWorkspace" owner:self options:nil] firstObject];
  137. UITapGestureRecognizer *viewRichWorkspaceTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewRichWorkspaceTapAction:)];
  138. viewRichWorkspaceTapped.numberOfTapsRequired = 1;
  139. viewRichWorkspaceTapped.delegate = self;
  140. [self.viewRichWorkspace.richView addGestureRecognizer:viewRichWorkspaceTapped];
  141. self.sortButton = self.viewRichWorkspace.sortButton;
  142. heightSearchBar = self.viewRichWorkspace.topView.frame.size.height;
  143. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  144. [self.sortButton addTarget:self action:@selector(toggleSortMenu) forControlEvents:UIControlEventTouchUpInside];
  145. heightRichWorkspace = UIScreen.mainScreen.bounds.size.height / 4 + heightSearchBar;
  146. [self.viewRichWorkspace setFrame:CGRectMake(0, 0, self.tableView.frame.size.width, heightRichWorkspace)];
  147. self.navigationItem.searchController = self.searchController;
  148. self.searchController.hidesNavigationBarDuringPresentation = true;
  149. self.navigationController.navigationBar.prefersLargeTitles = true;
  150. self.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAlways;
  151. // Table Header View
  152. [self.tableView setTableHeaderView:self.viewRichWorkspace];
  153. // Register cell
  154. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  155. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  156. self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 35, 0);
  157. // long press recognizer TableView
  158. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  159. [self.tableView addGestureRecognizer:longPressRecognizer];
  160. // Pull-to-Refresh
  161. [self createRefreshControl];
  162. // Register for 3D Touch Previewing if available
  163. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)) {
  164. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  165. }
  166. // if this is not Main (the Main uses inizializeMain)
  167. if (_isRoot == NO && appDelegate.account.length > 0) {
  168. // Read (File) Folder
  169. [self readFileReloadFolder];
  170. }
  171. // Title
  172. [self setTitle];
  173. // changeTheming
  174. [self changeTheming];
  175. }
  176. - (void)willDismissSearchController:(UISearchController *)searchController
  177. {
  178. [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
  179. }
  180. - (void)willPresentSearchController:(UISearchController *)searchController
  181. {
  182. [self updateNavBarShadow:self.tableView force:true];
  183. }
  184. - (void)viewWillAppear:(BOOL)animated
  185. {
  186. [super viewWillAppear:animated];
  187. [self updateNavBarShadow:self.tableView force:false];
  188. if(_isViewDidLoad && _isRoot) {
  189. self.navigationItem.hidesSearchBarWhenScrolling = false;
  190. [self.navigationController.navigationBar sizeToFit];
  191. }
  192. // test
  193. if (appDelegate.account.length == 0)
  194. return;
  195. if (_isSelectedMode)
  196. [self setUINavigationBarSelected];
  197. else
  198. [self setUINavigationBarDefault];
  199. // If not editing mode remove _selectedocIds
  200. if (!self.tableView.editing)
  201. [_selectedocIdsMetadatas removeAllObjects];
  202. // Check server URL "/"
  203. if (self.navigationController.viewControllers.firstObject == self && self.serverUrl == nil) {
  204. self.serverUrl = [[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  205. }
  206. // RichWorkspace
  207. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.account, self.serverUrl]];
  208. if (![self.richWorkspaceText isEqualToString:directory.richWorkspace]) {
  209. self.richWorkspaceText = directory.richWorkspace;
  210. [self setTableViewHeader];
  211. }
  212. // Query data source
  213. if (self.searchController.isActive == false) {
  214. [self reloadDatasource:self.serverUrl ocId:nil];
  215. }
  216. }
  217. - (void)viewDidAppear:(BOOL)animated
  218. {
  219. [super viewDidAppear:animated];
  220. if(_isViewDidLoad && _isRoot) {
  221. self.navigationItem.hidesSearchBarWhenScrolling = true;
  222. }
  223. // Active Main
  224. appDelegate.activeMain = self;
  225. // Test viewDidLoad
  226. if (_isViewDidLoad) {
  227. _isViewDidLoad = NO;
  228. } else {
  229. if (appDelegate.account.length > 0 && [_selectedocIdsMetadatas count] == 0) {
  230. // Read (file) Folder
  231. [self readFileReloadFolder];
  232. }
  233. }
  234. // Title
  235. [self setTitle];
  236. }
  237. - (void)viewWillDisappear:(BOOL)animated
  238. {
  239. [super viewWillDisappear:animated];
  240. }
  241. - (void) viewDidLayoutSubviews
  242. {
  243. [super viewDidLayoutSubviews];
  244. [self setTableViewHeader];
  245. }
  246. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  247. {
  248. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  249. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  250. [self.tableView beginUpdates];
  251. [self.tableView endUpdates];
  252. [self setTableViewHeader];
  253. } completion:^(id<UIViewControllerTransitionCoordinatorContext> context){
  254. [self updateNavBarShadow:self.tableView force:false];
  255. }];
  256. }
  257. - (void)presentationControllerWillDismiss:(UIPresentationController *)presentationController
  258. {
  259. [self viewDidAppear:true];
  260. }
  261. - (BOOL)prefersStatusBarHidden
  262. {
  263. return NO;
  264. }
  265. // detect scroll for remove keyboard in search mode
  266. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  267. {
  268. if (self.searchController.isActive && scrollView == self.tableView) {
  269. [self.searchController.searchBar endEditing:YES];
  270. }
  271. }
  272. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  273. [self updateNavBarShadow:self.tableView force:false];
  274. }
  275. - (void)changeTheming
  276. {
  277. [appDelegate changeTheming:self tableView:self.tableView collectionView:nil form:false];
  278. // Refresh control
  279. refreshControl.tintColor = UIColor.lightGrayColor;
  280. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  281. [self.sortButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  282. // color searchbar
  283. self.searchController.searchBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  284. // color searchbbar button text (cancel)
  285. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  286. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  287. [searchButton setTitleColor:NCBrandColor.sharedInstance.brandElement forState:UIControlStateNormal];
  288. }
  289. // color textview searchbbar
  290. UITextField *searchTextView = [self.searchController.searchBar valueForKey:@"searchField"];
  291. if (searchTextView && [searchTextView isKindOfClass:[UITextField class]]) {
  292. searchTextView.textColor = NCBrandColor.sharedInstance.textView;
  293. }
  294. // Rich Workspace
  295. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  296. // Title
  297. [self setTitle];
  298. // Reload Table View
  299. [self tableViewReloadData];
  300. }
  301. #pragma --------------------------------------------------------------------------------------------
  302. #pragma mark ===== Initialization =====
  303. #pragma --------------------------------------------------------------------------------------------
  304. //
  305. // Callers :
  306. //
  307. // ChangeDefaultAccount (delegate)
  308. // Split : inizialize
  309. // Settings Advanced : removeAllFiles
  310. //
  311. - (void)initializeMain:(NSNotification *)notification
  312. {
  313. // test
  314. if (appDelegate.account.length == 0)
  315. return;
  316. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  317. // This is Root home main add list
  318. appDelegate.homeMain = self;
  319. _isRoot = YES;
  320. _serverUrl = [[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  321. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  322. // go Home
  323. [self.navigationController popToRootViewControllerAnimated:NO];
  324. // Remove search mode
  325. [self cancelSearchBar];
  326. // Clear error certificate
  327. [CCUtility setCertificateError:appDelegate.account error:NO];
  328. // Setting Theming
  329. [appDelegate settingThemingColorBrand];
  330. // Detail
  331. // If AVPlayer in play -> Stop
  332. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  333. [appDelegate.player pause];
  334. }
  335. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_menuDetailClose object:nil];
  336. // Not Photos Video in library ? then align and Init Auto Upload
  337. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.account]];
  338. if ([recordsPhotoLibrary count] == 0) {
  339. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  340. }
  341. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  342. [[NCCommunicationCommon shared] writeLog:@"Request Service Server Nextcloud"];
  343. [[NCService shared] startRequestServicesServer];
  344. // Read this folder
  345. [self readFileReloadFolder];
  346. } else {
  347. // reload datasource
  348. [self reloadDatasource:_serverUrl ocId:nil];
  349. }
  350. // Registeration push notification
  351. [appDelegate pushNotification];
  352. // Registeration domain File Provider
  353. if (k_fileProvider_domain) {
  354. [FileProviderDomain.sharedInstance registerDomain];
  355. } else {
  356. [FileProviderDomain.sharedInstance removeAllDomain];
  357. }
  358. }
  359. #pragma --------------------------------------------------------------------------------------------
  360. #pragma mark ==== NotificationCenter ====
  361. #pragma --------------------------------------------------------------------------------------------
  362. - (void)createFolder:(NSNotification *)notification
  363. {
  364. NSDictionary *userInfo = notification.userInfo;
  365. tableMetadata *metadata = userInfo[@"metadata"];
  366. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  367. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:nil account:appDelegate.account urlBase: appDelegate.urlBase];
  368. if (isFolderEncrypted) {
  369. [self readFolder:metadata.serverUrl];
  370. } else {
  371. [self reloadDatasource:self.serverUrl ocId:nil];
  372. }
  373. }
  374. - (void)deleteFile:(NSNotification *)notification
  375. {
  376. NSDictionary *userInfo = notification.userInfo;
  377. tableMetadata *metadata = userInfo[@"metadata"];
  378. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  379. if (arrayDeleteMetadata.count > 0) {
  380. tableMetadata *metadata = arrayDeleteMetadata.firstObject;
  381. [arrayDeleteMetadata removeObjectAtIndex:0];
  382. [[NCNetworking shared] deleteMetadata:metadata account:metadata.account urlBase:metadata.urlBase onlyLocal:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  383. }
  384. if ([metadata.fileNameView.lowercaseString isEqualToString:k_fileNameRichWorkspace.lowercaseString]) {
  385. [self readFileReloadFolder];
  386. } else {
  387. if (self.searchController.isActive) {
  388. [self readFolder:self.serverUrl];
  389. }
  390. }
  391. [self reloadDatasource:self.serverUrl ocId:nil];
  392. }
  393. - (void)moveFile:(NSNotification *)notification
  394. {
  395. NSDictionary *userInfo = notification.userInfo;
  396. tableMetadata *metadata = userInfo[@"metadata"];
  397. // tableMetadata *metadataNew = userInfo[@"metadataNew"];
  398. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  399. NSString *errorDescription = userInfo[@"errorDescription"];
  400. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  401. if (arrayMoveMetadata.count > 0) {
  402. tableMetadata *metadata = arrayMoveMetadata.firstObject;
  403. NSString *serverUrlTo = arrayMoveServerUrlTo.firstObject;
  404. [arrayMoveMetadata removeObjectAtIndex:0];
  405. [arrayMoveServerUrlTo removeObjectAtIndex:0];
  406. [[NCNetworking shared] moveMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  407. }
  408. if (errorCode != 0 && self.view.window != nil) {
  409. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  410. }
  411. [self reloadDatasource:self.serverUrl ocId:nil];
  412. }
  413. - (void)copyFile:(NSNotification *)notification
  414. {
  415. NSDictionary *userInfo = notification.userInfo;
  416. tableMetadata *metadata = userInfo[@"metadata"];
  417. // NSString *serverUrlTo = userInfo[@"serverUrlTo"];
  418. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  419. NSString *errorDescription = userInfo[@"errorDescription"];
  420. if (![metadata.serverUrl isEqualToString:self.serverUrl]) { return; }
  421. if (arrayCopyMetadata.count > 0) {
  422. tableMetadata *metadata = arrayCopyMetadata.firstObject;
  423. NSString *serverUrlTo = arrayCopyServerUrlTo.firstObject;
  424. [arrayCopyMetadata removeObjectAtIndex:0];
  425. [arrayCopyServerUrlTo removeObjectAtIndex:0];
  426. [[NCNetworking shared] copyMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  427. }
  428. if (errorCode != 0 && self.view.window != nil) {
  429. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  430. }
  431. }
  432. - (void)favoriteFile:(NSNotification *)notification
  433. {
  434. if (self.view.window == nil) { return; }
  435. NSDictionary *userInfo = notification.userInfo;
  436. tableMetadata *metadata = userInfo[@"metadata"];
  437. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  438. NSString *errorDescription = userInfo[@"errorDescription"];
  439. BOOL favorite = [userInfo[@"favorite"] boolValue];
  440. if (errorCode == 0) {
  441. if (self.searchController.isActive) {
  442. [self readFolder:self.serverUrl];
  443. }
  444. if (favorite) {
  445. if ([CCUtility getFavoriteOffline]) {
  446. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorDownloadAllFile];
  447. } else {
  448. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorReadFile];
  449. }
  450. }
  451. } else {
  452. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  453. }
  454. [self reloadDatasource:self.serverUrl ocId:nil];
  455. }
  456. #pragma --------------------------------------------------------------------------------------------
  457. #pragma mark ==== DZNEmptyDataSetSource ====
  458. #pragma --------------------------------------------------------------------------------------------
  459. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  460. {
  461. if (_loadingFolder)
  462. return NO;
  463. else
  464. return YES;
  465. }
  466. - (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
  467. {
  468. CGFloat height = self.tabBarController.tabBar.frame.size.height;
  469. return -height;
  470. }
  471. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  472. {
  473. return NCBrandColor.sharedInstance.backgroundView;
  474. }
  475. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  476. {
  477. if (self.searchController.isActive)
  478. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"search"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  479. else
  480. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] width:300 height:300 color:NCBrandColor.sharedInstance.brandElement];
  481. }
  482. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  483. {
  484. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  485. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  486. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  487. activityView.color = NCBrandColor.sharedInstance.brandElement;
  488. [activityView startAnimating];
  489. return activityView;
  490. }
  491. return nil;
  492. }
  493. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  494. {
  495. NSString *text;
  496. if (self.searchController.isActive) {
  497. text = _noFilesSearchTitle;
  498. } else {
  499. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  500. }
  501. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  502. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  503. }
  504. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  505. {
  506. NSString *text;
  507. if (self.searchController.isActive) {
  508. text = _noFilesSearchDescription;
  509. } else {
  510. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  511. }
  512. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  513. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  514. paragraph.alignment = NSTextAlignmentCenter;
  515. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  516. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  517. }
  518. #pragma --------------------------------------------------------------------------------------------
  519. #pragma mark ===== Text Field =====
  520. #pragma --------------------------------------------------------------------------------------------
  521. - (void)minCharTextFieldDidChange:(UITextField *)sender
  522. {
  523. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  524. if (alertController)
  525. {
  526. UITextField *fileName = alertController.textFields.firstObject;
  527. UIAlertAction *okAction = alertController.actions.lastObject;
  528. okAction.enabled = fileName.text.length > 0;
  529. }
  530. }
  531. - (void)textFieldDidBeginEditing:(UITextField *)textField
  532. {
  533. [CCUtility selectFileNameFrom:textField];
  534. }
  535. #pragma --------------------------------------------------------------------------------------------
  536. #pragma mark ===== Graphic Window =====
  537. #pragma --------------------------------------------------------------------------------------------
  538. - (void)createRefreshControl
  539. {
  540. refreshControl = [NCMainRefreshControl new];
  541. self.tableView.refreshControl = refreshControl;
  542. refreshControl.tintColor = UIColor.lightGrayColor;
  543. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  544. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  545. }
  546. - (void)deleteRefreshControl
  547. {
  548. [refreshControl endRefreshing];
  549. [refreshControl removeFromSuperview];
  550. refreshControl = nil;
  551. }
  552. - (void)refreshControlTarget
  553. {
  554. [self readFolder:_serverUrl];
  555. // Actuate `Peek` feedback (weak boom)
  556. AudioServicesPlaySystemSound(1519);
  557. }
  558. - (void)setTitle
  559. {
  560. if (_isSelectedMode) {
  561. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  562. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  563. self.navigationItem.titleView = nil;
  564. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  565. } else {
  566. if (_isRoot) {
  567. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  568. } else {
  569. self.navigationItem.title = _titleMain;
  570. }
  571. }
  572. NSString *titleButtonMenuSort = [[NCUtility shared] getTitleButtonForViewWithKey:k_layout_view_main];
  573. [self.sortButton setTitle:NSLocalizedString(titleButtonMenuSort, nil) forState:UIControlStateNormal];
  574. }
  575. - (void)setUINavigationBarDefault
  576. {
  577. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  578. self.navigationController.navigationBar.hidden = NO;
  579. self.navigationItem.rightBarButtonItem = buttonSelect;
  580. self.navigationItem.leftBarButtonItem = nil;
  581. }
  582. - (void)setUINavigationBarSelected
  583. {
  584. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationMore"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleSelectMenu)];
  585. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  586. self.navigationItem.leftBarButtonItem = leftButton;
  587. self.navigationItem.rightBarButtonItem = buttonMore; //[[NSArray alloc] initWithObjects:buttonMore, nil];
  588. }
  589. - (void)cancelSelect
  590. {
  591. [self tableViewSelect:false];
  592. }
  593. #pragma --------------------------------------------------------------------------------------------
  594. #pragma mark ===== Document Picker =====
  595. #pragma --------------------------------------------------------------------------------------------
  596. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  597. {
  598. }
  599. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  600. {
  601. }
  602. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  603. {
  604. documentPicker.delegate = self;
  605. [self presentViewController:documentPicker animated:YES completion:nil];
  606. }
  607. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  608. {
  609. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  610. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  611. __block NSError *error;
  612. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  613. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  614. NSString *fileName = [url lastPathComponent];
  615. NSString *ocId = [[NSUUID UUID] UUIDString];
  616. NSData *data = [NSData dataWithContentsOfURL:newURL];
  617. if (data && error == nil) {
  618. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  619. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:ocId serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:false];
  620. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground;
  621. metadataForUpload.sessionSelector = selectorUploadFile;
  622. metadataForUpload.size = data.length;
  623. metadataForUpload.status = k_metadataStatusWaitUpload;
  624. if ([[NCUtility shared] getMetadataConflictWithAccount:appDelegate.account serverUrl:serverUrl fileName:fileName] != nil) {
  625. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  626. conflict.serverUrl = self.serverUrl;
  627. conflict.metadatasUploadInConflict = @[metadataForUpload];
  628. [self presentViewController:conflict animated:YES completion:nil];
  629. } else {
  630. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  631. [[appDelegate networkingAutoUpload] startProcess];
  632. }
  633. } else {
  634. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  635. }
  636. } else {
  637. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  638. }
  639. }];
  640. }
  641. }
  642. - (void)openImportDocumentPicker
  643. {
  644. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  645. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  646. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  647. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  648. documentProviderMenu.delegate = self;
  649. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  650. }
  651. #pragma --------------------------------------------------------------------------------------------
  652. #pragma mark ===== Assets Picker =====
  653. #pragma --------------------------------------------------------------------------------------------
  654. -(void)dismissFormUploadAssets
  655. {
  656. }
  657. - (void)openAssetsPickerController
  658. {
  659. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  660. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets) {
  661. if (assets.count > 0) {
  662. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  663. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  664. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets cryptated:NO session:NCNetworking.shared.sessionIdentifierBackground delegate:self];
  665. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  666. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  667. [self presentViewController:navigationController animated:YES completion:nil];
  668. });
  669. }
  670. }];
  671. }
  672. #pragma --------------------------------------------------------------------------------------------
  673. #pragma mark ===== Save selected File =====
  674. #pragma --------------------------------------------------------------------------------------------
  675. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  676. {
  677. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  678. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  679. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  680. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  681. if (image)
  682. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  683. else
  684. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  685. }
  686. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  687. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  688. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  689. } else {
  690. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorFileNotSaved forced:false];
  691. }
  692. }
  693. if (status != PHAuthorizationStatusAuthorized) {
  694. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  695. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  696. [alertController addAction:okAction];
  697. [self presentViewController:alertController animated:YES completion:nil];
  698. }
  699. }
  700. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  701. {
  702. if (error) {
  703. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code forced:false];
  704. }
  705. }
  706. - (void)saveSelectedFiles
  707. {
  708. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  709. return;
  710. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  711. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  712. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  713. for (tableMetadata *metadata in metadatas) {
  714. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  715. [[NCOperationQueue shared] downloadWithMetadata:metadata selector:selectorSaveAlbum setFavorite:false];
  716. }
  717. }
  718. [_hud hideHud];
  719. });
  720. [self tableViewSelect:false];
  721. }
  722. #pragma mark -
  723. #pragma --------------------------------------------------------------------------------------------
  724. #pragma mark ===== Peek & Pop =====
  725. #pragma --------------------------------------------------------------------------------------------
  726. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  727. {
  728. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  729. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  730. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  731. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  732. if (cell) {
  733. previewingContext.sourceRect = cell.frame;
  734. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  735. viewController.metadata = metadata;
  736. viewController.imageFile = cell.file.image;
  737. viewController.showOpenIn = true;
  738. viewController.showShare = true;
  739. viewController.showOpenQuickLook = [[NCUtility shared] isQuickLookDisplayableWithMetadata:metadata];
  740. return viewController;
  741. }
  742. return nil;
  743. }
  744. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  745. {
  746. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  747. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  748. }
  749. #pragma --------------------------------------------------------------------------------------------
  750. #pragma mark ==== Download ====
  751. #pragma --------------------------------------------------------------------------------------------
  752. - (void)downloadSelectedFilesFolders
  753. {
  754. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  755. return;
  756. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  757. for (tableMetadata *metadata in selectedMetadatas) {
  758. [[NCOperationQueue shared] synchronizationMetadata:metadata selector:selectorDownloadFile];
  759. }
  760. [self tableViewSelect:false];
  761. }
  762. #pragma --------------------------------------------------------------------------------------------
  763. #pragma mark ===== Upload new Photos/Videos =====
  764. #pragma --------------------------------------------------------------------------------------------
  765. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  766. {
  767. // if request create the folder for Auto Upload & the subfolders
  768. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  769. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPathWithUrlBase:appDelegate.urlBase account:appDelegate.account];
  770. if ([autoUploadPath isEqualToString:serverUrl]) {
  771. if ([[NCNetworking shared] createFolderWithAssets:(PHFetchResult *)assets selector:selectorUploadFile useSubFolder:useSubFolder account:appDelegate.account urlBase:appDelegate.urlBase]) {
  772. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError forced:true];
  773. return;
  774. }
  775. }
  776. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  777. });
  778. }
  779. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  780. {
  781. NSMutableArray *metadatasNOConflict = [NSMutableArray new];
  782. NSMutableArray *metadatasMOV = [NSMutableArray new];
  783. NSMutableArray *metadatasUploadInConflict = [NSMutableArray new];
  784. for (PHAsset *asset in assets) {
  785. BOOL livePhoto = false;
  786. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  787. NSDate *assetDate = asset.creationDate;
  788. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  789. // Detect LivePhoto Upload
  790. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto) {
  791. livePhoto = true;
  792. }
  793. // Create serverUrl if use sub folder
  794. if (useSubFolder) {
  795. [formatter setDateFormat:@"yyyy"];
  796. NSString *yearString = [formatter stringFromDate:assetDate];
  797. [formatter setDateFormat:@"MM"];
  798. NSString *monthString = [formatter stringFromDate:assetDate];
  799. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  800. }
  801. // Check if is in upload
  802. 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];
  803. if ([isRecordInSessions count] > 0)
  804. continue;
  805. // Prepare record metadata
  806. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  807. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  808. metadataForUpload.session = session;
  809. metadataForUpload.sessionSelector = selectorUploadFile;
  810. metadataForUpload.size = [[NCUtilityFileSystem shared] getFileSizeWithAsset:asset];
  811. metadataForUpload.status = k_metadataStatusWaitUpload;
  812. // Add Medtadata MOV LIVE PHOTO for upload
  813. if (livePhoto) {
  814. NSString *fileNameMove = [NSString stringWithFormat:@"%@.mov", fileName.stringByDeletingPathExtension];
  815. NSString *ocId = [[NSUUID UUID] UUIDString];
  816. NSString *filePath = [CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameMove];
  817. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  818. [CCUtility extractLivePhotoAsset:asset filePath:filePath withCompletion:^(NSURL *url) {
  819. if (url != nil) {
  820. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  821. tableMetadata *metadataMOVForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileNameMove ocId:ocId serverUrl:serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:livePhoto];
  822. metadataForUpload.livePhoto = true;
  823. metadataMOVForUpload.livePhoto = true;
  824. metadataMOVForUpload.session = session;
  825. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  826. metadataMOVForUpload.size = fileSize;
  827. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  828. metadataMOVForUpload.typeFile = k_metadataTypeFile_video;
  829. [metadatasMOV addObject:metadataMOVForUpload];
  830. }
  831. dispatch_semaphore_signal(semaphore);
  832. }];
  833. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER))
  834. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:30]];
  835. }
  836. if ([[NCUtility shared] getMetadataConflictWithAccount:appDelegate.account serverUrl:serverUrl fileName:fileName] != nil) {
  837. [metadatasUploadInConflict addObject:metadataForUpload];
  838. } else {
  839. [metadatasNOConflict addObject:metadataForUpload];
  840. }
  841. }
  842. dispatch_async(dispatch_get_main_queue(), ^{
  843. // Verify if file(s) exists
  844. if (metadatasUploadInConflict.count > 0) {
  845. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  846. conflict.serverUrl = self.serverUrl;
  847. conflict.metadatasNOConflict = metadatasNOConflict;
  848. conflict.metadatasMOV = metadatasMOV;
  849. conflict.metadatasUploadInConflict = metadatasUploadInConflict;
  850. [self presentViewController:conflict animated:YES completion:nil];
  851. } else {
  852. [[NCManageDatabase sharedInstance] addMetadatas:metadatasNOConflict];
  853. [[NCManageDatabase sharedInstance] addMetadatas:metadatasMOV];
  854. [[appDelegate networkingAutoUpload] startProcess];
  855. }
  856. });
  857. }
  858. #pragma --------------------------------------------------------------------------------------------
  859. #pragma mark ==== Read Folder ====
  860. #pragma --------------------------------------------------------------------------------------------
  861. - (void)readFolder:(NSString *)serverUrl
  862. {
  863. // init control
  864. if (!serverUrl || !appDelegate.account || appDelegate.maintenanceMode) {
  865. [refreshControl endRefreshing];
  866. return;
  867. }
  868. // Search Mode
  869. if (self.searchController.isActive) {
  870. _searchFileName = @""; // forced reload searchg
  871. [self updateSearchResultsForSearchController:self.searchController];
  872. return;
  873. }
  874. _loadingFolder = YES;
  875. [refreshControl endRefreshing];
  876. [self tableViewReloadData];
  877. [[NCNetworking shared] readFolderWithServerUrl:serverUrl account:appDelegate.account completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSArray *metadatasUpdate, NSArray *metadatasLocalUpdate, NSInteger errorCode, NSString *errorDescription) {
  878. if (errorCode == 0 ) {
  879. _metadataFolder = metadataFolder;
  880. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.account urlBase:_metadataFolder.urlBase];
  881. [self setTitle];
  882. for (tableMetadata *metadata in metadatasLocalUpdate) {
  883. if (!metadata.directory) {
  884. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorDownloadFile setFavorite:false completion:^(NSInteger errorCode) { }];
  885. }
  886. }
  887. // E2EE Is encrypted folder get metadata
  888. if (isFolderEncrypted) {
  889. if ([CCUtility isEndToEndEnabled:account]) {
  890. [[NCCommunication shared] getE2EEMetadataWithFileId:metadataFolder.fileId e2eToken:nil customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *e2eMetadata, NSInteger errorCode, NSString *errorDescription) {
  891. if (errorCode == 0 && e2eMetadata != nil) {
  892. BOOL result = [[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eMetadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account urlBase:appDelegate.urlBase];
  893. if (result == false) {
  894. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorDecodeMetadata forced:true];
  895. }
  896. } else if (errorCode != 404) {
  897. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  898. }
  899. [self reloadDatasource:_serverUrl ocId:nil];
  900. }];
  901. } else {
  902. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotEnabled forced:true];
  903. }
  904. }
  905. } else {
  906. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  907. }
  908. _loadingFolder = NO;
  909. [self reloadDatasource:serverUrl ocId:nil];
  910. }];
  911. }
  912. - (void)readFileReloadFolder
  913. {
  914. if (!_serverUrl || !appDelegate.account || appDelegate.maintenanceMode)
  915. return;
  916. [[NCNetworking shared] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.account completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  917. if (errorCode == 0 && [account isEqualToString:appDelegate.account]) {
  918. // Rich Workspace
  919. [[NCManageDatabase sharedInstance] setDirectoryWithRichWorkspace:metadata.richWorkspace serverUrl:self.serverUrl account:appDelegate.account];
  920. if (![self.richWorkspaceText isEqualToString:metadata.richWorkspace]) {
  921. self.richWorkspaceText = metadata.richWorkspace;
  922. }
  923. [self setTableViewHeader];
  924. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  925. // Read folder: No record, Change etag or BLINK
  926. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  927. [self readFolder:self.serverUrl];
  928. }
  929. } else if (errorCode != 0) {
  930. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  931. }
  932. }];
  933. }
  934. #pragma mark -
  935. #pragma --------------------------------------------------------------------------------------------
  936. #pragma mark ===== Search =====
  937. #pragma --------------------------------------------------------------------------------------------
  938. - (void)searchStartTimer
  939. {
  940. if (self.searchController.isActive == false) {
  941. return;
  942. }
  943. [[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) {
  944. if (errorCode == 0 && [account isEqualToString:appDelegate.account] && files != nil) {
  945. [[NCManageDatabase sharedInstance] convertNCCommunicationFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  946. [[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  947. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  948. _metadataFolder = nil;
  949. [self reloadDatasource:_serverUrl ocId:nil];
  950. [self tableViewReloadData];
  951. [self setTitle];
  952. }];
  953. } else {
  954. if (errorCode != 0) {
  955. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:true];
  956. }
  957. _searchFileName = @"";
  958. [self cancelSearchBar];
  959. }
  960. }];
  961. _noFilesSearchTitle = @"";
  962. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  963. [self.tableView reloadEmptyDataSet];
  964. }
  965. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  966. {
  967. // Color text "Cancel"
  968. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brandElement];
  969. if (searchController.isActive) {
  970. [self deleteRefreshControl];
  971. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  972. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  973. _searchFileName = fileName;
  974. _metadataFolder = nil;
  975. // First : filter
  976. 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];
  977. [_searchResultMetadatas removeAllObjects];
  978. for (tableMetadata *record in records) {
  979. [_searchResultMetadatas addObject:record];
  980. }
  981. // Version >= 12
  982. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  983. if (serverVersionMajor >= 12) {
  984. [_timerWaitInput invalidate];
  985. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  986. }
  987. [self setTitle];
  988. }
  989. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  990. [self reloadDatasource:_serverUrl ocId:nil];
  991. }
  992. } else {
  993. [self createRefreshControl];
  994. [self reloadDatasource:_serverUrl ocId:nil];
  995. }
  996. }
  997. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  998. {
  999. [self cancelSearchBar];
  1000. }
  1001. - (void)cancelSearchBar
  1002. {
  1003. if (self.searchController.active) {
  1004. [self.searchController setActive:NO];
  1005. _searchFileName = @"";
  1006. _searchResultMetadatas = [NSMutableArray new];
  1007. [self reloadDatasource:_serverUrl ocId:nil];
  1008. }
  1009. }
  1010. #pragma mark -
  1011. #pragma --------------------------------------------------------------------------------------------
  1012. #pragma mark ===== Delete File or Folder =====
  1013. #pragma --------------------------------------------------------------------------------------------
  1014. - (void)deleteMetadatas
  1015. {
  1016. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1017. return;
  1018. if ([_selectedocIdsMetadatas count] > 0) {
  1019. [arrayDeleteMetadata addObjectsFromArray:[_selectedocIdsMetadatas allValues]];
  1020. } else {
  1021. [arrayDeleteMetadata addObject:self.metadata];
  1022. }
  1023. [[NCNetworking shared] deleteMetadata:arrayDeleteMetadata.firstObject account:appDelegate.account urlBase:appDelegate.urlBase onlyLocal:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1024. [arrayDeleteMetadata removeObjectAtIndex:0];
  1025. // End Select Table View
  1026. [self tableViewSelect:false];
  1027. }
  1028. #pragma --------------------------------------------------------------------------------------------
  1029. #pragma mark ===== Move / Copy =====
  1030. #pragma --------------------------------------------------------------------------------------------
  1031. - (void)moveCopyFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo move:(BOOL)move overwrite:(BOOL)overwrite
  1032. {
  1033. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1034. return;
  1035. NSMutableArray *arrayMetadata, *arrayServerUrlTo;
  1036. if (move) {
  1037. arrayMetadata = arrayMoveMetadata;
  1038. arrayServerUrlTo = arrayMoveServerUrlTo;
  1039. } else {
  1040. arrayMetadata = arrayCopyMetadata;
  1041. arrayServerUrlTo = arrayCopyServerUrlTo;
  1042. }
  1043. if ([_selectedocIdsMetadatas count] > 0) {
  1044. for (NSString *key in _selectedocIdsMetadatas) {
  1045. tableMetadata *metadata = [_selectedocIdsMetadatas objectForKey:key];
  1046. [arrayMetadata addObject:metadata];
  1047. [arrayServerUrlTo addObject:serverUrlTo];
  1048. }
  1049. } else {
  1050. [arrayMetadata addObject:metadata];
  1051. [arrayServerUrlTo addObject:serverUrlTo];
  1052. }
  1053. if (move) {
  1054. [[NCNetworking shared] moveMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1055. } else {
  1056. [[NCNetworking shared] copyMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1057. }
  1058. [arrayMetadata removeObjectAtIndex:0];
  1059. [arrayServerUrlTo removeObjectAtIndex:0];
  1060. // End Select Table View
  1061. [self tableViewSelect:false];
  1062. }
  1063. // DELEGATE : Select
  1064. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type array:(NSArray *)array buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  1065. {
  1066. if (serverUrl != nil) {
  1067. // E2EE DENIED
  1068. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase:appDelegate.urlBase]) {
  1069. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"_e2e_error_not_move_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorE2EENotMove forced:true];
  1070. return;
  1071. }
  1072. BOOL move = true;
  1073. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  1074. if ([_selectedocIdsMetadatas count] > 0) {
  1075. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1076. [self moveCopyFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl move:move overwrite:overwrite];
  1077. } else {
  1078. [self moveCopyFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl move:move overwrite:overwrite];
  1079. }
  1080. }
  1081. }
  1082. - (void)moveOpenWindow:(NSArray *)indexPaths
  1083. {
  1084. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1085. return;
  1086. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1087. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1088. viewController.delegate = self;
  1089. viewController.hideButtonCreateFolder = false;
  1090. viewController.selectFile = false;
  1091. viewController.includeDirectoryE2EEncryption = false;
  1092. viewController.includeImages = false;
  1093. viewController.type = @"";
  1094. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1095. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  1096. viewController.isButtonDone1Hide = false;
  1097. viewController.isOverwriteHide = false;
  1098. viewController.keyLayout = k_layout_view_move;
  1099. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1100. [self presentViewController:navigationController animated:YES completion:nil];
  1101. }
  1102. #pragma --------------------------------------------------------------------------------------------
  1103. #pragma mark ===== Create folder =====
  1104. #pragma --------------------------------------------------------------------------------------------
  1105. - (void)createFolder
  1106. {
  1107. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1108. NSString *message;
  1109. UIAlertController *alertController;
  1110. if ([serverUrl isEqualToString:[[NCUtility shared] getHomeServerWithUrlBase:appDelegate.urlBase account:appDelegate.account]]) {
  1111. message = @"/";
  1112. } else {
  1113. message = [serverUrl lastPathComponent];
  1114. }
  1115. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1116. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1117. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1118. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1119. }];
  1120. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }];
  1121. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1122. UITextField *fileName = alertController.textFields.firstObject;
  1123. [[NCNetworking shared] createFolderWithFileName:[fileName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] serverUrl:serverUrl account:appDelegate.account urlBase:appDelegate.urlBase overwrite:false completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1124. }];
  1125. okAction.enabled = NO;
  1126. [alertController addAction:cancelAction];
  1127. [alertController addAction:okAction];
  1128. [self presentViewController:alertController animated:YES completion:nil];
  1129. }
  1130. #pragma --------------------------------------------------------------------------------------------
  1131. #pragma mark ===== Progress & Task Button =====
  1132. #pragma --------------------------------------------------------------------------------------------
  1133. - (void)triggerProgressTask:(NSNotification *)notification
  1134. {
  1135. if (sectionDataSource.ocIdIndexPath != nil) {
  1136. [[NCMainCommon shared] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1137. }
  1138. }
  1139. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1140. {
  1141. UITouch *touch = [[event allTouches] anyObject];
  1142. CGPoint location = [touch locationInView:self.tableView];
  1143. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1144. if ([self indexPathIsValid:indexPath]) {
  1145. tableMetadata *metadataSection = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1146. if (metadataSection) {
  1147. [[NCMainCommon shared] cancelTransferMetadata:metadataSection uploadStatusForcedStart:false];
  1148. }
  1149. }
  1150. }
  1151. - (void)cancelAllTask:(id)sender
  1152. {
  1153. CGPoint location = [sender locationInView:self.tableView];
  1154. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1155. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1156. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1157. [NCUtility.shared startActivityIndicatorWithView:self.view bottom:0];
  1158. [[NCMainCommon shared] cancelAllTransfer];
  1159. [NCUtility.shared stopActivityIndicator];
  1160. }]];
  1161. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1162. alertController.popoverPresentationController.sourceView = self.tableView;
  1163. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1164. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1165. [alertController.view layoutIfNeeded];
  1166. [self presentViewController:alertController animated:YES completion:nil];
  1167. }
  1168. #pragma --------------------------------------------------------------------------------------------
  1169. #pragma mark ===== Tap =====
  1170. #pragma --------------------------------------------------------------------------------------------
  1171. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1172. {
  1173. CGPoint location = [tapGesture locationInView:self.tableView];
  1174. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1175. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1176. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase: appDelegate.urlBase]) {
  1177. [[NCMainCommon shared] openShareWithViewController:self metadata:metadata indexPage:1];
  1178. }
  1179. }
  1180. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1181. {
  1182. CGPoint location = [tapGesture locationInView:self.tableView];
  1183. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1184. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1185. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.account urlBase:appDelegate.urlBase]) {
  1186. [[NCMainCommon shared] openShareWithViewController:self metadata:metadata indexPage:2];
  1187. }
  1188. }
  1189. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1190. {
  1191. CGPoint location = [tapGesture locationInView:self.tableView];
  1192. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1193. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1194. if (metadata) {
  1195. }
  1196. }
  1197. #pragma --------------------------------------------------------------------------------------------
  1198. #pragma mark ===== Rich Workspace =====
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1201. {
  1202. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1203. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1204. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1205. viewerRichWorkspace.serverUrl = self.serverUrl;
  1206. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1207. [self presentViewController:navigationController animated:NO completion:NULL];
  1208. }
  1209. - (void)createRichWorkspace
  1210. {
  1211. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1212. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.account, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1213. if (metadata) {
  1214. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1215. } else {
  1216. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1217. }
  1218. }
  1219. - (void)toggleSortMenu
  1220. {
  1221. NCSortMenu *sortMenu = [NCSortMenu new];
  1222. [sortMenu toggleMenuWithViewController:self key:k_layout_view_main sortButton:self.sortButton serverUrl:self.serverUrl hideDirectoryOnTop:false];
  1223. }
  1224. - (void)toggleSelectMenu
  1225. {
  1226. [self toggleSelectMenuWithViewController:self.navigationController];
  1227. }
  1228. #pragma --------------------------------------------------------------------------------------------
  1229. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1230. #pragma --------------------------------------------------------------------------------------------
  1231. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1232. {
  1233. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1234. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1235. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1236. NSMutableArray *items = [NSMutableArray new];
  1237. if ([self indexPathIsValid:indexPath])
  1238. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1239. [self becomeFirstResponder];
  1240. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1241. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1242. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1243. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1244. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1245. }
  1246. if ([[NCUtility shared] isQuickLookDisplayableWithMetadata:self.metadata]) {
  1247. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_quicklook_", nil) action:@selector(openQuickLookTouch:)]];
  1248. }
  1249. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1250. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1251. [menuController setMenuItems:items];
  1252. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1253. [menuController setMenuVisible:YES animated:YES];
  1254. }
  1255. }
  1256. - (BOOL)canBecomeFirstResponder
  1257. {
  1258. return YES;
  1259. }
  1260. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1261. {
  1262. // For copy file, copy files, Open in ... :
  1263. //
  1264. // NO Directory
  1265. // NO Error Passcode
  1266. // NO In Session mode (download/upload)
  1267. // NO Template
  1268. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openQuickLookTouch:) == action) {
  1269. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1270. else return NO;
  1271. }
  1272. if (@selector(copyTouchFiles:) == action) {
  1273. if (_isSelectedMode) {
  1274. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1275. for (tableMetadata *metadata in selectedMetadatas) {
  1276. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1277. return YES;
  1278. }
  1279. }
  1280. return NO;
  1281. }
  1282. if (@selector(pasteTouchFile:) == action) {
  1283. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1284. NSArray *items = [pasteboard items];
  1285. if ([items count] == 1) {
  1286. // Value : (NSData) ocId
  1287. NSDictionary *dic = [items objectAtIndex:0];
  1288. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1289. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1290. if (ocId) {
  1291. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1292. if (metadata) {
  1293. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1294. } else {
  1295. return NO;
  1296. }
  1297. }
  1298. }
  1299. return NO;
  1300. }
  1301. if (@selector(pasteTouchFiles:) == action) {
  1302. BOOL isValid = NO;
  1303. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1304. NSArray *items = [pasteboard items];
  1305. if ([items count] <= 1) return NO;
  1306. for (NSDictionary *dic in items) {
  1307. // Value : (NSData) ocId
  1308. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1309. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1310. if (ocId) {
  1311. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  1312. if (metadata) {
  1313. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1314. isValid = YES;
  1315. } else {
  1316. isValid = NO;
  1317. break;
  1318. }
  1319. } else {
  1320. isValid = NO;
  1321. break;
  1322. }
  1323. } else {
  1324. isValid = NO;
  1325. break;
  1326. }
  1327. }
  1328. return isValid;
  1329. }
  1330. return NO;
  1331. }
  1332. /************************************ COPY ************************************/
  1333. - (void)copyTouchFile:(id)sender
  1334. {
  1335. // Remove all item
  1336. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1337. pasteboard.items = [[NSArray alloc] init];
  1338. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1339. [self copyFileToPasteboard:self.metadata];
  1340. } else {
  1341. [[NCNetworking shared] downloadWithMetadata:self.metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1342. }
  1343. }
  1344. - (void)copyTouchFiles:(id)sender
  1345. {
  1346. // Remove all item
  1347. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1348. pasteboard.items = [[NSArray alloc] init];
  1349. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1350. for (tableMetadata *metadata in selectedMetadatas) {
  1351. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1352. [self copyFileToPasteboard:metadata];
  1353. } else {
  1354. [[NCNetworking shared] downloadWithMetadata:metadata selector:selectorLoadCopy setFavorite:false completion:^(NSInteger errorCode) { }];
  1355. }
  1356. }
  1357. [self tableViewSelect:false];
  1358. }
  1359. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1360. {
  1361. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1362. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1363. // Value : (NSData) ocId
  1364. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1365. [items addObject:item];
  1366. [pasteboard setItems:items];
  1367. }
  1368. /************************************ OPEN IN ... ******************************/
  1369. - (void)openinTouchFile:(id)sender
  1370. {
  1371. [[NCMainCommon shared] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1372. }
  1373. /************************************ OPEN QUICK LOOK ******************************/
  1374. - (void)openQuickLookTouch:(id)sender
  1375. {
  1376. [[NCMainCommon shared] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileQuickLook];
  1377. }
  1378. /************************************ PASTE ************************************/
  1379. - (void)pasteTouchFile:(id)sender
  1380. {
  1381. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1382. [self uploadFilePasteArray:[pasteboard items]];
  1383. }
  1384. - (void)pasteTouchFiles:(id)sender
  1385. {
  1386. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1387. [self uploadFilePasteArray:[pasteboard items]];
  1388. }
  1389. - (void)uploadFilePasteArray:(NSArray *)items
  1390. {
  1391. for (NSDictionary *dic in items) {
  1392. // Value : (NSData) ocId
  1393. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1394. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1395. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromOcId:ocId];
  1396. if (metadata) {
  1397. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1398. NSString *fileName = [[NCUtility shared] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.account];
  1399. NSString *ocId = [[NSUUID UUID] UUIDString];
  1400. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1401. // Prepare record metadata
  1402. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.account fileName:fileName ocId:ocId serverUrl:self.serverUrl urlBase:appDelegate.urlBase url:@"" contentType:@"" livePhoto:false];
  1403. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground;
  1404. metadataForUpload.sessionSelector = selectorUploadFile;
  1405. metadataForUpload.size = metadata.size;
  1406. metadataForUpload.status = k_metadataStatusWaitUpload;
  1407. // Add Medtadata for upload
  1408. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1409. }
  1410. }
  1411. }
  1412. [[appDelegate networkingAutoUpload] startProcess];
  1413. }
  1414. #pragma mark -
  1415. #pragma --------------------------------------------------------------------------------------------
  1416. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1417. #pragma --------------------------------------------------------------------------------------------
  1418. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1419. {
  1420. if (metadata == nil)
  1421. return NO;
  1422. // E2EE
  1423. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.account] == NO)
  1424. return NO;
  1425. return YES;
  1426. }
  1427. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1428. {
  1429. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1430. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1431. return [self canOpenMenuAction:metadata];
  1432. }
  1433. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1434. {
  1435. }
  1436. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1437. {
  1438. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1439. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1440. if (direction == MGSwipeDirectionRightToLeft) {
  1441. [self actionDelete:indexPath];
  1442. }
  1443. if (direction == MGSwipeDirectionLeftToRight) {
  1444. [[NCNetworking shared] favoriteMetadata:self.metadata urlBase:appDelegate.urlBase completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1445. }
  1446. return YES;
  1447. }
  1448. - (void)actionDelete:(NSIndexPath *)indexPath
  1449. {
  1450. tableMetadata *metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1451. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1452. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1453. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1454. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1455. }]];
  1456. if (localFile) {
  1457. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1458. tableMetadata *metadataLivePhoto = [[NCManageDatabase sharedInstance] isLivePhotoWithMetadata:metadata];
  1459. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1460. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1461. if (metadataLivePhoto) {
  1462. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1463. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1464. }
  1465. [self reloadDatasource:metadata.serverUrl ocId:metadata.ocId];
  1466. }]];
  1467. }
  1468. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1469. }]];
  1470. alertController.popoverPresentationController.sourceView = self.tableView;
  1471. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1472. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1473. [alertController.view layoutIfNeeded];
  1474. [self presentViewController:alertController animated:YES completion:nil];
  1475. }
  1476. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1477. {
  1478. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1479. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1480. self.metadata = [[NCMainCommon shared] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1481. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1482. }
  1483. #pragma --------------------------------------------------------------------------------------------
  1484. #pragma mark - ==== Datasource ====
  1485. #pragma --------------------------------------------------------------------------------------------
  1486. - (void)reloadDatasource:(NSNotification *)notification
  1487. {
  1488. NSDictionary *userInfo = notification.userInfo;
  1489. NSString *ocId = userInfo[@"ocId"];
  1490. NSString *serverUrl = userInfo[@"serverUrl"];
  1491. [self reloadDatasource:serverUrl ocId:ocId];
  1492. }
  1493. - (void)reloadDatasourceTransfer:(NSNotification *)notification
  1494. {
  1495. NSDictionary *userInfo = notification.userInfo;
  1496. tableMetadata *metadata = userInfo[@"metadata"];
  1497. NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  1498. NSString *errorDescription = userInfo[@"errorDescription"];
  1499. if (errorCode != 0 && self.view.window != nil) {
  1500. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode forced:false];
  1501. }
  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