CCMain.m 117 KB

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