CCMain.m 109 KB

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