CCMain.m 126 KB

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