CCMain.m 114 KB

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