CCMain.m 115 KB

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