CCMain.m 114 KB

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