CCMain.m 117 KB

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