CCMain.m 117 KB

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