CCMain.m 116 KB

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