CCMain.m 114 KB

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