CCMain.m 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935
  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. for (UIView *subview in [_tableView subviews]) {
  560. if (subview == refreshControl)
  561. [subview removeFromSuperview];
  562. }
  563. refreshControl = nil;
  564. }
  565. - (void)refreshControlTarget
  566. {
  567. [self readFolder:_serverUrl];
  568. // Actuate `Peek` feedback (weak boom)
  569. AudioServicesPlaySystemSound(1519);
  570. }
  571. - (void)setTitle
  572. {
  573. if (_isSelectedMode) {
  574. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  575. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  576. self.navigationItem.titleView = nil;
  577. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  578. } else {
  579. if (_isRoot) {
  580. self.navigationItem.title = NCBrandOptions.sharedInstance.brand;
  581. } else {
  582. self.navigationItem.title = _titleMain;
  583. }
  584. }
  585. [self SetSortButtonText];
  586. }
  587. - (void)setUINavigationBarDefault
  588. {
  589. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_select_", @"") style:UIBarButtonItemStylePlain target:self action:@selector(tableViewToggle)];
  590. self.navigationController.navigationBar.hidden = NO;
  591. self.navigationItem.rightBarButtonItem = buttonSelect;
  592. self.navigationItem.leftBarButtonItem = nil;
  593. }
  594. - (void)setUINavigationBarSelected
  595. {
  596. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationMore"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  597. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  598. self.navigationItem.leftBarButtonItem = leftButton;
  599. self.navigationItem.rightBarButtonItem = buttonMore; //[[NSArray alloc] initWithObjects:buttonMore, nil];
  600. }
  601. - (void)cancelSelect
  602. {
  603. [self tableViewSelect:false];
  604. }
  605. #pragma --------------------------------------------------------------------------------------------
  606. #pragma mark ===== Document Picker =====
  607. #pragma --------------------------------------------------------------------------------------------
  608. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  609. {
  610. NSLog(@"[LOG] Cancelled");
  611. }
  612. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  613. {
  614. NSLog(@"[LOG] Cancelled");
  615. }
  616. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  617. {
  618. documentPicker.delegate = self;
  619. [self presentViewController:documentPicker animated:YES completion:nil];
  620. }
  621. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  622. {
  623. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  624. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  625. __block NSError *error;
  626. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  627. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  628. NSString *fileName = [url lastPathComponent];
  629. NSString *ocId = [[NSUUID UUID] UUIDString];
  630. NSData *data = [NSData dataWithContentsOfURL:newURL];
  631. if (data && error == nil) {
  632. if ([data writeToFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  633. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:ocId serverUrl:serverUrl url:@"" contentType:@""];
  634. metadataForUpload.session = k_upload_session;
  635. metadataForUpload.sessionSelector = selectorUploadFile;
  636. metadataForUpload.size = data.length;
  637. metadataForUpload.status = k_metadataStatusWaitUpload;
  638. if ([[NCUtility sharedInstance] getMetadataConflictWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileName] != nil) {
  639. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  640. conflict.serverUrl = self.serverUrl;
  641. conflict.metadatasUploadInConflict = @[metadataForUpload];
  642. [self presentViewController:conflict animated:YES completion:nil];
  643. } else {
  644. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  645. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  646. [appDelegate startLoadAutoDownloadUpload];
  647. }
  648. } else {
  649. [[NCContentPresenter shared] messageNotification:@"_error_" description:error.description delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  650. }
  651. } else {
  652. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_read_file_error_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  653. }
  654. }];
  655. }
  656. }
  657. - (void)openImportDocumentPicker
  658. {
  659. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  660. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  661. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  662. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  663. documentProviderMenu.delegate = self;
  664. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  665. }
  666. #pragma --------------------------------------------------------------------------------------------
  667. #pragma mark ===== Assets Picker =====
  668. #pragma --------------------------------------------------------------------------------------------
  669. -(void)dismissFormUploadAssets
  670. {
  671. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  672. }
  673. - (void)openAssetsPickerController
  674. {
  675. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self maxSelectedAssets:100 singleSelectedMode:false];
  676. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nullable assets, NSArray<NSURL *> * urls) {
  677. if (assets.count > 0) {
  678. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  679. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  680. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets urls:(NSMutableArray *)urls cryptated:NO session:k_upload_session delegate:self];
  681. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  682. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  683. [self presentViewController:navigationController animated:YES completion:nil];
  684. });
  685. }
  686. }];
  687. }
  688. #pragma --------------------------------------------------------------------------------------------
  689. #pragma mark ===== Save selected File =====
  690. #pragma --------------------------------------------------------------------------------------------
  691. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  692. {
  693. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView];
  694. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  695. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  696. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  697. if (image)
  698. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  699. else
  700. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  701. }
  702. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  703. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  704. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  705. } else {
  706. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  707. }
  708. }
  709. if (status != PHAuthorizationStatusAuthorized) {
  710. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  711. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  712. [alertController addAction:okAction];
  713. [self presentViewController:alertController animated:YES completion:nil];
  714. }
  715. }
  716. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  717. {
  718. if (error) {
  719. [[NCContentPresenter shared] messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  720. }
  721. }
  722. - (void)saveSelectedFiles
  723. {
  724. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  725. return;
  726. NSLog(@"[LOG] Start download selected files ...");
  727. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  728. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  729. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  730. for (tableMetadata *metadata in metadatas) {
  731. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  732. metadata.session = k_download_session;
  733. metadata.sessionError = @"";
  734. metadata.sessionSelector = selectorSave;
  735. metadata.status = k_metadataStatusWaitDownload;
  736. // Add Metadata for Download
  737. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  738. [appDelegate startLoadAutoDownloadUpload];
  739. }
  740. }
  741. [_hud hideHud];
  742. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  743. });
  744. [self tableViewSelect:false];
  745. }
  746. #pragma mark -
  747. #pragma --------------------------------------------------------------------------------------------
  748. #pragma mark ===== Peek & Pop =====
  749. #pragma --------------------------------------------------------------------------------------------
  750. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  751. {
  752. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  753. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  754. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  755. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  756. if (cell) {
  757. previewingContext.sourceRect = cell.frame;
  758. CCPeekPop *viewController = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  759. viewController.metadata = metadata;
  760. viewController.imageFile = cell.file.image;
  761. viewController.showOpenIn = true;
  762. viewController.showShare = true;
  763. viewController.showOpenQuickLook = [[NCUtility sharedInstance] isQuickLookDisplayableWithMetadata:metadata];
  764. return viewController;
  765. }
  766. return nil;
  767. }
  768. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  769. {
  770. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  771. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  772. }
  773. #pragma --------------------------------------------------------------------------------------------
  774. #pragma mark ==== Download ====
  775. #pragma --------------------------------------------------------------------------------------------
  776. - (void)downloadSelectedFilesFolders
  777. {
  778. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  779. return;
  780. NSLog(@"[LOG] Start download selected ...");
  781. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  782. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  783. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  784. for (tableMetadata *metadata in selectedMetadatas) {
  785. if (metadata.directory) {
  786. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] selector:selectorReadFolderWithDownload account:appDelegate.activeAccount];
  787. } else {
  788. [[CCSynchronize sharedSynchronize] readFile:metadata.ocId fileName:metadata.fileName serverUrl:metadata.serverUrl selector:selectorReadFileWithDownload account:appDelegate.activeAccount];
  789. }
  790. }
  791. [_hud hideHud];
  792. });
  793. [self tableViewSelect:false];
  794. }
  795. #pragma --------------------------------------------------------------------------------------------
  796. #pragma mark ===== Upload new Photos/Videos =====
  797. #pragma --------------------------------------------------------------------------------------------
  798. //
  799. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  800. //
  801. - (void)uploadFileAsset:(NSMutableArray *)assets urls:(NSMutableArray *)urls serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  802. {
  803. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  804. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  805. // if request create the folder for Auto Upload & the subfolders
  806. if ([autoUploadPath isEqualToString:serverUrl])
  807. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  808. return;
  809. dispatch_async(dispatch_get_main_queue(), ^{
  810. [self uploadFileAsset:assets urls:urls serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  811. });
  812. });
  813. }
  814. - (void)uploadFileAsset:(NSArray *)assets urls:(NSArray *)urls serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  815. {
  816. NSMutableArray *metadatasNOConflict = [NSMutableArray new];
  817. NSMutableArray *metadatasMOV = [NSMutableArray new];
  818. NSMutableArray *metadatasUploadInConflict = [NSMutableArray new];
  819. for (PHAsset *asset in assets) {
  820. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  821. NSDate *assetDate = asset.creationDate;
  822. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  823. // Create serverUrl if use sub folder
  824. if (useSubFolder) {
  825. [formatter setDateFormat:@"yyyy"];
  826. NSString *yearString = [formatter stringFromDate:assetDate];
  827. [formatter setDateFormat:@"MM"];
  828. NSString *monthString = [formatter stringFromDate:assetDate];
  829. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  830. }
  831. // Check if is in upload
  832. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", appDelegate.activeAccount, serverUrl, fileName] sorted:nil ascending:NO];
  833. if ([isRecordInSessions count] > 0)
  834. continue;
  835. // Prepare record metadata
  836. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  837. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  838. metadataForUpload.session = session;
  839. metadataForUpload.sessionSelector = selectorUploadFile;
  840. metadataForUpload.size = [[NCUtility sharedInstance] getFileSizeWithAsset:asset];
  841. metadataForUpload.status = k_metadataStatusWaitUpload;
  842. if ([[NCUtility sharedInstance] getMetadataConflictWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileName] != nil) {
  843. [metadatasUploadInConflict addObject:metadataForUpload];
  844. } else {
  845. [metadatasNOConflict addObject:metadataForUpload];
  846. }
  847. // Add Medtadata MOV LIVE PHOTO for upload
  848. if ((asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive || asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive+PHAssetMediaSubtypePhotoHDR) && CCUtility.getLivePhoto && urls.count == assets.count) {
  849. NSUInteger index = [assets indexOfObject:asset];
  850. NSURL *url = [urls objectAtIndex:index];
  851. NSString *fileNameNoExt = [fileName stringByDeletingPathExtension];
  852. NSString *fileName = [NSString stringWithFormat:@"%@.mov", fileNameNoExt];
  853. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
  854. tableMetadata *metadataMOVForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  855. metadataMOVForUpload.session = session;
  856. metadataMOVForUpload.sessionSelector = selectorUploadFile;
  857. metadataMOVForUpload.size = fileSize;
  858. metadataMOVForUpload.status = k_metadataStatusWaitUpload;
  859. // Prepare file and directory
  860. [CCUtility moveFileAtPath:url.path toPath:[CCUtility getDirectoryProviderStorageOcId:metadataMOVForUpload.ocId fileNameView:fileName]];
  861. [metadatasMOV addObject:metadataMOVForUpload];
  862. }
  863. }
  864. // Verify if file(s) exists
  865. if (metadatasUploadInConflict.count > 0) {
  866. NCCreateFormUploadConflict *conflict = [[UIStoryboard storyboardWithName:@"NCCreateFormUploadConflict" bundle:nil] instantiateInitialViewController];
  867. conflict.serverUrl = self.serverUrl;
  868. conflict.metadatasNOConflict = metadatasNOConflict;
  869. conflict.metadatasMOV = metadatasMOV;
  870. conflict.metadatasUploadInConflict = metadatasUploadInConflict;
  871. [self presentViewController:conflict animated:YES completion:nil];
  872. } else {
  873. [[NCManageDatabase sharedInstance] addMetadatas:metadatasNOConflict];
  874. [[NCManageDatabase sharedInstance] addMetadatas:metadatasMOV];
  875. [appDelegate startLoadAutoDownloadUpload];
  876. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  877. }
  878. }
  879. #pragma --------------------------------------------------------------------------------------------
  880. #pragma mark ==== Read Folder ====
  881. #pragma --------------------------------------------------------------------------------------------
  882. - (void)readFolder:(NSString *)serverUrl
  883. {
  884. // init control
  885. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  886. [refreshControl endRefreshing];
  887. return;
  888. }
  889. // Search Mode
  890. if (self.searchController.isActive) {
  891. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  892. _searchFileName = @""; // forced reload searchg
  893. [self updateSearchResultsForSearchController:self.searchController];
  894. return;
  895. }
  896. _loadingFolder = YES;
  897. [self tableViewReloadData];
  898. [[NCNetworking sharedInstance] readFolderWithServerUrl:serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadataFolder, NSArray *metadatas, NSInteger errorCode, NSString *errorDescription) {
  899. [refreshControl endRefreshing];
  900. if (errorCode == 0 ) {
  901. _metadataFolder = metadataFolder;
  902. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:serverUrl e2eEncrypted:_metadataFolder.e2eEncrypted account:appDelegate.activeAccount];
  903. [self setTitle];
  904. // File is changed ??
  905. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  906. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:serverUrl account:account withDownload:NO];
  907. });
  908. // E2EE Is encrypted folder get metadata
  909. if (isFolderEncrypted) {
  910. NSString *metadataFolderFileId = metadataFolder.fileId;
  911. // Read Metadata
  912. if ([CCUtility isEndToEndEnabled:account]) {
  913. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  914. NSString *metadata;
  915. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileId:metadataFolderFileId user:appDelegate.activeUser userID:appDelegate.activeUserID password:[CCUtility getPassword:appDelegate.activeAccount] url:appDelegate.activeUrl];
  916. dispatch_async(dispatch_get_main_queue(), ^{
  917. if (error) {
  918. if (error.code != kOCErrorServerPathNotFound)
  919. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  920. } else {
  921. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:appDelegate.activeUrl] == false)
  922. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  923. else
  924. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  925. }
  926. });
  927. });
  928. } else {
  929. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  930. }
  931. }
  932. if ([serverUrl isEqualToString:_serverUrl]) {
  933. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  934. [self tableViewReloadData];
  935. }
  936. } else {
  937. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  938. }
  939. _loadingFolder = NO;
  940. }];
  941. }
  942. - (void)readFileReloadFolder
  943. {
  944. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  945. return;
  946. // RichWorkspace
  947. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, self.serverUrl]];
  948. self.richWorkspaceText = directory.richWorkspace;
  949. [self setTableViewHeader];
  950. // Load Datasource
  951. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  952. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  953. });
  954. [[NCNetworking sharedInstance] readFileWithServerUrlFileName:self.serverUrl account:appDelegate.activeAccount completion:^(NSString *account, tableMetadata *metadata, NSInteger errorCode, NSString *errorDescription) {
  955. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  956. // Rich Workspace
  957. [[NCManageDatabase sharedInstance] setDirectoryWithOcId:metadata.ocId serverUrl:self.serverUrl richWorkspace:metadata.richWorkspace account:account];
  958. self.richWorkspaceText = metadata.richWorkspace;
  959. [self setTableViewHeader];
  960. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, self.serverUrl]];
  961. // Read folder: No record, Change etag or BLINK
  962. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadata.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  963. [self readFolder:self.serverUrl];
  964. }
  965. } else if (errorCode != 0) {
  966. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  967. }
  968. }];
  969. }
  970. #pragma mark -
  971. #pragma --------------------------------------------------------------------------------------------
  972. #pragma mark ===== Search =====
  973. #pragma --------------------------------------------------------------------------------------------
  974. - (void)searchStartTimer
  975. {
  976. if (self.searchController.isActive == false) {
  977. return;
  978. }
  979. [[NCCommunication shared] searchLiteralWithServerUrl:appDelegate.activeUrl depth:@"infinity" literal:_searchFileName showHiddenFiles:[CCUtility getShowHiddenFiles] customUserAgent:nil addCustomHeaders:nil user:appDelegate.activeUser account:appDelegate.activeAccount completionHandler:^(NSString *account, NSArray *files, NSInteger errorCode, NSString *errorDescription) {
  980. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount] && files != nil) {
  981. [[NCManageDatabase sharedInstance] convertNCFilesToMetadatas:files useMetadataFolder:false account:account completion:^(tableMetadata *metadataFolder, NSArray<tableMetadata *> *metadatasFolder, NSArray<tableMetadata *> *metadatas) {
  982. NSMutableArray *metadatasDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  983. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasDB];
  984. _metadataFolder = nil;
  985. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl ocId:nil action:k_action_NULL];
  986. [self tableViewReloadData];
  987. [self setTitle];
  988. }];
  989. } else {
  990. if (errorCode != 0) {
  991. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  992. }
  993. _searchFileName = @"";
  994. }
  995. }];
  996. _noFilesSearchTitle = @"";
  997. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  998. [self.tableView reloadEmptyDataSet];
  999. }
  1000. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1001. {
  1002. // Color text "Cancel"
  1003. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brand];
  1004. if (searchController.isActive) {
  1005. [self deleteRefreshControl];
  1006. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1007. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1008. _searchFileName = fileName;
  1009. _metadataFolder = nil;
  1010. // First : filter
  1011. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1012. [_searchResultMetadatas removeAllObjects];
  1013. for (tableMetadata *record in records) {
  1014. [_searchResultMetadatas addObject:record];
  1015. }
  1016. // Version >= 12
  1017. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.activeAccount elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  1018. if (serverVersionMajor >= 12) {
  1019. [_timerWaitInput invalidate];
  1020. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1021. }
  1022. [self setTitle];
  1023. }
  1024. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1025. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1026. }
  1027. } else {
  1028. [self createRefreshControl];
  1029. [self reloadDatasource:self.serverUrl ocId:nil action:k_action_NULL];
  1030. }
  1031. }
  1032. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1033. {
  1034. [self cancelSearchBar];
  1035. }
  1036. - (void)cancelSearchBar
  1037. {
  1038. if (self.searchController.active) {
  1039. [self.searchController setActive:NO];
  1040. _searchFileName = @"";
  1041. _dateReadDataSource = nil;
  1042. _searchResultMetadatas = [NSMutableArray new];
  1043. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1044. }
  1045. }
  1046. #pragma mark -
  1047. #pragma --------------------------------------------------------------------------------------------
  1048. #pragma mark ===== Delete File or Folder =====
  1049. #pragma --------------------------------------------------------------------------------------------
  1050. - (void)deleteMetadatas
  1051. {
  1052. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1053. return;
  1054. if ([_selectedocIdsMetadatas count] > 0) {
  1055. [appDelegate.arrayDeleteMetadata addObjectsFromArray:[_selectedocIdsMetadatas allValues]];
  1056. } else {
  1057. [appDelegate.arrayDeleteMetadata addObject:self.metadata];
  1058. }
  1059. [[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) { }];
  1060. [appDelegate.arrayDeleteMetadata removeObjectAtIndex:0];
  1061. // End Select Table View
  1062. [self tableViewSelect:false];
  1063. }
  1064. #pragma --------------------------------------------------------------------------------------------
  1065. #pragma mark ===== Move / Copy =====
  1066. #pragma --------------------------------------------------------------------------------------------
  1067. - (void)moveCopyFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo move:(BOOL)move overwrite:(BOOL)overwrite
  1068. {
  1069. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1070. return;
  1071. NSMutableArray *arrayMetadata, *arrayServerUrlTo;
  1072. if (move) {
  1073. arrayMetadata = appDelegate.arrayMoveMetadata;
  1074. arrayServerUrlTo = appDelegate.arrayMoveServerUrlTo;
  1075. } else {
  1076. arrayMetadata = appDelegate.arrayCopyMetadata;
  1077. arrayServerUrlTo = appDelegate.arrayCopyServerUrlTo;
  1078. }
  1079. if ([_selectedocIdsMetadatas count] > 0) {
  1080. for (NSString *key in _selectedocIdsMetadatas) {
  1081. tableMetadata *metadata = [_selectedocIdsMetadatas objectForKey:key];
  1082. [arrayMetadata addObject:metadata];
  1083. [arrayServerUrlTo addObject:serverUrlTo];
  1084. }
  1085. } else {
  1086. [arrayMetadata addObject:metadata];
  1087. [arrayServerUrlTo addObject:serverUrlTo];
  1088. }
  1089. if (move) {
  1090. [[NCNetworking sharedInstance] moveMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1091. } else {
  1092. [[NCNetworking sharedInstance] copyMetadata:arrayMetadata.firstObject serverUrlTo:arrayServerUrlTo.firstObject overwrite:overwrite completion:^(NSInteger errorCode, NSString * errorDesctiption) { }];
  1093. }
  1094. [arrayMetadata removeObjectAtIndex:0];
  1095. [arrayServerUrlTo removeObjectAtIndex:0];
  1096. // End Select Table View
  1097. [self tableViewSelect:false];
  1098. }
  1099. // DELEGATE : Select
  1100. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type buttonType:(NSString *)buttonType overwrite:(BOOL)overwrite
  1101. {
  1102. if (serverUrl == nil) {
  1103. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1104. } else {
  1105. // E2EE DENIED
  1106. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1107. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1108. return;
  1109. }
  1110. BOOL move = true;
  1111. if ([buttonType isEqualToString:@"done1"]) { move = false; }
  1112. if ([_selectedocIdsMetadatas count] > 0) {
  1113. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1114. [self moveCopyFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl move:move overwrite:overwrite];
  1115. } else {
  1116. [self moveCopyFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl move:move overwrite:overwrite];
  1117. }
  1118. }
  1119. }
  1120. - (void)moveOpenWindow:(NSArray *)indexPaths
  1121. {
  1122. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1123. return;
  1124. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1125. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1126. viewController.delegate = self;
  1127. viewController.hideButtonCreateFolder = false;
  1128. viewController.selectFile = false;
  1129. viewController.includeDirectoryE2EEncryption = false;
  1130. viewController.includeImages = false;
  1131. viewController.type = @"";
  1132. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1133. viewController.titleButtonDone1 = NSLocalizedString(@"_copy_", nil);
  1134. viewController.isButtonDone1Hide = false;
  1135. viewController.isOverwriteHide = false;
  1136. viewController.layoutViewSelect = k_layout_view_move;
  1137. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1138. [self presentViewController:navigationController animated:YES completion:nil];
  1139. }
  1140. #pragma --------------------------------------------------------------------------------------------
  1141. #pragma mark ===== Create folder =====
  1142. #pragma --------------------------------------------------------------------------------------------
  1143. - (void)createFolder
  1144. {
  1145. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1146. NSString *message;
  1147. UIAlertController *alertController;
  1148. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1149. message = @"/";
  1150. } else {
  1151. message = [serverUrl lastPathComponent];
  1152. }
  1153. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1154. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1155. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1156. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1157. }];
  1158. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1159. NSLog(@"[LOG] Cancel action");
  1160. }];
  1161. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1162. UITextField *fileName = alertController.textFields.firstObject;
  1163. [[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) { }];
  1164. }];
  1165. okAction.enabled = NO;
  1166. [alertController addAction:cancelAction];
  1167. [alertController addAction:okAction];
  1168. [self presentViewController:alertController animated:YES completion:nil];
  1169. }
  1170. #pragma --------------------------------------------------------------------------------------------
  1171. #pragma mark ===== Progress & Task Button =====
  1172. #pragma --------------------------------------------------------------------------------------------
  1173. - (void)triggerProgressTask:(NSNotification *)notification
  1174. {
  1175. if (sectionDataSource.ocIdIndexPath != nil) {
  1176. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1177. }
  1178. }
  1179. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1180. {
  1181. UITouch *touch = [[event allTouches] anyObject];
  1182. CGPoint location = [touch locationInView:self.tableView];
  1183. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1184. if ([self indexPathIsValid:indexPath]) {
  1185. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1186. if (metadataSection) {
  1187. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataSection.ocId]];
  1188. if (metadata)
  1189. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1190. }
  1191. }
  1192. }
  1193. - (void)cancelAllTask:(id)sender
  1194. {
  1195. CGPoint location = [sender locationInView:self.tableView];
  1196. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1197. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1198. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1199. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1200. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1201. [NCUtility.sharedInstance stopActivityIndicator];
  1202. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil ocId:nil action:k_action_NULL];
  1203. }]];
  1204. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1205. alertController.popoverPresentationController.sourceView = self.tableView;
  1206. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1207. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1208. [alertController.view layoutIfNeeded];
  1209. [self presentViewController:alertController animated:YES completion:nil];
  1210. }
  1211. #pragma --------------------------------------------------------------------------------------------
  1212. #pragma mark ===== Tap =====
  1213. #pragma --------------------------------------------------------------------------------------------
  1214. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1215. {
  1216. CGPoint location = [tapGesture locationInView:self.tableView];
  1217. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1218. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1219. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1220. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1221. }
  1222. }
  1223. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1224. {
  1225. CGPoint location = [tapGesture locationInView:self.tableView];
  1226. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1227. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1228. if (metadata && ![CCUtility isFolderEncrypted:self.serverUrl e2eEncrypted:metadata.e2eEncrypted account:appDelegate.activeAccount]) {
  1229. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1230. }
  1231. }
  1232. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1233. {
  1234. CGPoint location = [tapGesture locationInView:self.tableView];
  1235. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1236. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1237. if (metadata) {
  1238. }
  1239. }
  1240. #pragma --------------------------------------------------------------------------------------------
  1241. #pragma mark ===== Rich Workspace =====
  1242. #pragma --------------------------------------------------------------------------------------------
  1243. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1244. {
  1245. [UIView animateWithDuration:0.5 animations:^{
  1246. [self.tableView setContentOffset:CGPointMake(0, heightSearchBar)];
  1247. } completion:^(BOOL finished) {
  1248. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1249. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1250. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1251. viewerRichWorkspace.serverUrl = self.serverUrl;
  1252. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1253. [self presentViewController:navigationController animated:NO completion:NULL];
  1254. }];
  1255. }
  1256. - (void)createRichWorkspace
  1257. {
  1258. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1259. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1260. if (metadata) {
  1261. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1262. } else {
  1263. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1264. }
  1265. }
  1266. #pragma --------------------------------------------------------------------------------------------
  1267. #pragma mark ==== Menu LOGO ====
  1268. #pragma --------------------------------------------------------------------------------------------
  1269. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1270. {
  1271. // Brand
  1272. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1273. return;
  1274. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1275. NSMutableArray *menuArray = [NSMutableArray new];
  1276. for (NSString *account in listAccount) {
  1277. CCMenuItem *item = [[CCMenuItem alloc] init];
  1278. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1279. item.argument = account;
  1280. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1281. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1282. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1283. if (avatar) {
  1284. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1285. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1286. CGSize imageSize = avatarImageView.bounds.size;
  1287. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1288. CGContextRef context = UIGraphicsGetCurrentContext();
  1289. [avatarImageView.layer renderInContext:context];
  1290. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1291. UIGraphicsEndImageContext();
  1292. } else {
  1293. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1294. }
  1295. item.image = avatar;
  1296. item.target = self;
  1297. if ([account isEqualToString:appDelegate.activeAccount]) {
  1298. item.action = nil;
  1299. [menuArray insertObject:item atIndex:0];
  1300. } else {
  1301. item.action = @selector(changeDefaultAccount:);
  1302. [menuArray addObject:item];
  1303. }
  1304. }
  1305. // Add + new account
  1306. CCMenuItem *item = [[CCMenuItem alloc] init];
  1307. item.title = NSLocalizedString(@"_add_account_", nil);
  1308. item.argument = @"";
  1309. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"add"] width:50 height:50 color:NCBrandColor.sharedInstance.textView];
  1310. item.target = self;
  1311. item.action = @selector(addNewAccount:);
  1312. [menuArray addObject:item];
  1313. OptionalConfiguration options;
  1314. Color backgroundColor;
  1315. const CGFloat *componentsBackgroundColor = CGColorGetComponents(NCBrandColor.sharedInstance.backgroundForm.CGColor);
  1316. backgroundColor.R = componentsBackgroundColor[0];
  1317. backgroundColor.G = componentsBackgroundColor[1];
  1318. backgroundColor.B = componentsBackgroundColor[2];
  1319. options.arrowSize = 9;
  1320. options.marginXSpacing = 7;
  1321. options.marginYSpacing = 10;
  1322. options.intervalSpacing = 20;
  1323. options.menuCornerRadius = 6.5;
  1324. options.maskToBackground = NO;
  1325. options.shadowOfMenu = YES;
  1326. options.hasSeperatorLine = YES;
  1327. options.seperatorLineHasInsets = YES;
  1328. options.textColor = NCBrandColor.sharedInstance.textView;
  1329. options.menuBackgroundColor = backgroundColor;
  1330. options.separatorColor = NCBrandColor.sharedInstance.separator;
  1331. CGRect rect = self.view.frame;
  1332. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1333. CGFloat safeAreaTop = 0;
  1334. CGFloat offsetY = 35;
  1335. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1336. rect.origin.y = locationY + safeAreaTop + offsetY;
  1337. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1338. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1339. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1340. }
  1341. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1342. {
  1343. // LOGOUT
  1344. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1345. if (tableAccount) {
  1346. // LOGIN
  1347. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1348. // go to home sweet home
  1349. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1350. }
  1351. }
  1352. - (void)addNewAccount:(CCMenuItem *)sender
  1353. {
  1354. [appDelegate openLoginView:self selector:k_intro_login openLoginWeb:false];
  1355. }
  1356. - (void)toggleReMainMenu
  1357. {
  1358. [self toggleMenuWithViewController:self.navigationController];
  1359. }
  1360. - (void)toggleReSelectMenu
  1361. {
  1362. [self toggleSelectMenuWithViewController:self.navigationController];
  1363. }
  1364. #pragma --------------------------------------------------------------------------------------------
  1365. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1366. #pragma --------------------------------------------------------------------------------------------
  1367. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1368. {
  1369. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1370. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1371. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1372. NSMutableArray *items = [NSMutableArray new];
  1373. if ([self indexPathIsValid:indexPath])
  1374. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1375. [self becomeFirstResponder];
  1376. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1377. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyTouchFile:)]];
  1378. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyTouchFiles:)]];
  1379. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1380. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinTouchFile:)]];
  1381. }
  1382. if ([[NCUtility sharedInstance] isQuickLookDisplayableWithMetadata:self.metadata]) {
  1383. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_quicklook_", nil) action:@selector(openQuickLookTouch:)]];
  1384. }
  1385. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteTouchFile:)]];
  1386. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteTouchFiles:)]];
  1387. [menuController setMenuItems:items];
  1388. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1389. [menuController setMenuVisible:YES animated:YES];
  1390. }
  1391. }
  1392. - (BOOL)canBecomeFirstResponder
  1393. {
  1394. return YES;
  1395. }
  1396. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1397. {
  1398. // For copy file, copy files, Open in ... :
  1399. //
  1400. // NO Directory
  1401. // NO Error Passcode
  1402. // NO In Session mode (download/upload)
  1403. // NO Template
  1404. if (@selector(copyTouchFile:) == action || @selector(openinTouchFile:) == action || @selector(openQuickLookTouch:) == action) {
  1405. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1406. else return NO;
  1407. }
  1408. if (@selector(copyTouchFiles:) == action) {
  1409. if (_isSelectedMode) {
  1410. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1411. for (tableMetadata *metadata in selectedMetadatas) {
  1412. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1413. return YES;
  1414. }
  1415. }
  1416. return NO;
  1417. }
  1418. if (@selector(pasteTouchFile:) == action) {
  1419. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1420. NSArray *items = [pasteboard items];
  1421. if ([items count] == 1) {
  1422. // Value : (NSData) ocId
  1423. NSDictionary *dic = [items objectAtIndex:0];
  1424. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1425. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1426. if (ocId) {
  1427. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1428. if (metadata) {
  1429. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1430. } else {
  1431. return NO;
  1432. }
  1433. }
  1434. }
  1435. return NO;
  1436. }
  1437. if (@selector(pasteTouchFiles:) == action) {
  1438. BOOL isValid = NO;
  1439. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1440. NSArray *items = [pasteboard items];
  1441. if ([items count] <= 1) return NO;
  1442. for (NSDictionary *dic in items) {
  1443. // Value : (NSData) ocId
  1444. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1445. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1446. if (ocId) {
  1447. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1448. if (metadata) {
  1449. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1450. isValid = YES;
  1451. } else {
  1452. isValid = NO;
  1453. break;
  1454. }
  1455. } else {
  1456. isValid = NO;
  1457. break;
  1458. }
  1459. } else {
  1460. isValid = NO;
  1461. break;
  1462. }
  1463. }
  1464. return isValid;
  1465. }
  1466. return NO;
  1467. }
  1468. /************************************ COPY ************************************/
  1469. - (void)copyTouchFile:(id)sender
  1470. {
  1471. // Remove all item
  1472. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1473. pasteboard.items = [[NSArray alloc] init];
  1474. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1475. [self copyFileToPasteboard:self.metadata];
  1476. } else {
  1477. self.metadata.session = k_download_session;
  1478. self.metadata.sessionError = @"";
  1479. self.metadata.sessionSelector = selectorLoadCopy;
  1480. self.metadata.status = k_metadataStatusWaitDownload;
  1481. // Add Metadata for Download
  1482. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  1483. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  1484. [appDelegate startLoadAutoDownloadUpload];
  1485. }
  1486. }
  1487. - (void)copyTouchFiles:(id)sender
  1488. {
  1489. // Remove all item
  1490. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1491. pasteboard.items = [[NSArray alloc] init];
  1492. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1493. for (tableMetadata *metadata in selectedMetadatas) {
  1494. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1495. [self copyFileToPasteboard:metadata];
  1496. } else {
  1497. metadata.session = k_download_session;
  1498. metadata.sessionError = @"";
  1499. metadata.sessionSelector = selectorLoadCopy;
  1500. metadata.status = k_metadataStatusWaitDownload;
  1501. // Add Metadata for Download
  1502. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1503. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1504. [appDelegate startLoadAutoDownloadUpload];
  1505. }
  1506. }
  1507. [self tableViewSelect:false];
  1508. }
  1509. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1510. {
  1511. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1512. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1513. // Value : (NSData) ocId
  1514. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1515. [items addObject:item];
  1516. [pasteboard setItems:items];
  1517. }
  1518. /************************************ OPEN IN ... ******************************/
  1519. - (void)openinTouchFile:(id)sender
  1520. {
  1521. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1522. }
  1523. /************************************ OPEN QUICK LOOK ******************************/
  1524. - (void)openQuickLookTouch:(id)sender
  1525. {
  1526. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileQuickLook];
  1527. }
  1528. /************************************ PASTE ************************************/
  1529. - (void)pasteTouchFile:(id)sender
  1530. {
  1531. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1532. [self uploadFilePasteArray:[pasteboard items]];
  1533. }
  1534. - (void)pasteTouchFiles:(id)sender
  1535. {
  1536. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1537. [self uploadFilePasteArray:[pasteboard items]];
  1538. }
  1539. - (void)uploadFilePasteArray:(NSArray *)items
  1540. {
  1541. for (NSDictionary *dic in items) {
  1542. // Value : (NSData) ocId
  1543. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1544. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1545. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1546. if (metadata) {
  1547. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1548. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1549. NSString *ocId = [[NSUUID UUID] UUIDString];
  1550. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1551. // Prepare record metadata
  1552. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] createMetadataWithAccount:appDelegate.activeAccount fileName:fileName ocId:ocId serverUrl:self.serverUrl url:@"" contentType:@""];
  1553. metadataForUpload.session = k_upload_session;
  1554. metadataForUpload.sessionSelector = selectorUploadFile;
  1555. metadataForUpload.size = metadata.size;
  1556. metadataForUpload.status = k_metadataStatusWaitUpload;
  1557. // Add Medtadata for upload
  1558. [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1559. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1560. }
  1561. }
  1562. }
  1563. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1564. [appDelegate startLoadAutoDownloadUpload];
  1565. }
  1566. #pragma mark -
  1567. #pragma --------------------------------------------------------------------------------------------
  1568. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1569. #pragma --------------------------------------------------------------------------------------------
  1570. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1571. {
  1572. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  1573. return NO;
  1574. // E2EE
  1575. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  1576. return NO;
  1577. return YES;
  1578. }
  1579. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1580. {
  1581. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1582. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1583. return [self canOpenMenuAction:metadata];
  1584. }
  1585. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1586. {
  1587. }
  1588. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1589. {
  1590. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1591. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1592. if (direction == MGSwipeDirectionRightToLeft) {
  1593. [self actionDelete:indexPath];
  1594. }
  1595. if (direction == MGSwipeDirectionLeftToRight) {
  1596. [[NCNetworking sharedInstance] favoriteMetadata:self.metadata url:appDelegate.activeUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  1597. }
  1598. return YES;
  1599. }
  1600. - (void)actionDelete:(NSIndexPath *)indexPath
  1601. {
  1602. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1603. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1604. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1605. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1606. [self performSelector:@selector(deleteMetadatas) withObject:nil];
  1607. }]];
  1608. if (localFile) {
  1609. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1610. tableMetadata *metadataLivePhoto = [[NCUtility sharedInstance] isLivePhotoWithMetadata:metadata];
  1611. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1612. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1613. if (metadataLivePhoto) {
  1614. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataLivePhoto.ocId]];
  1615. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadataLivePhoto.ocId] error:nil];
  1616. }
  1617. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1618. }]];
  1619. }
  1620. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1621. }]];
  1622. alertController.popoverPresentationController.sourceView = self.tableView;
  1623. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1624. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1625. [alertController.view layoutIfNeeded];
  1626. [self presentViewController:alertController animated:YES completion:nil];
  1627. }
  1628. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1629. {
  1630. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1631. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1632. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1633. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1634. }
  1635. #pragma --------------------------------------------------------------------------------------------
  1636. #pragma mark - ==== Datasource ====
  1637. #pragma --------------------------------------------------------------------------------------------
  1638. - (void)clearDateReadDataSource:(NSNotification *)notification
  1639. {
  1640. _dateReadDataSource = Nil;
  1641. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1642. }
  1643. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId action:(NSInteger)action
  1644. {
  1645. // test
  1646. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  1647. return;
  1648. // Search Mode
  1649. if (self.searchController.isActive) {
  1650. // Create metadatas
  1651. NSMutableArray *metadatas = [NSMutableArray new];
  1652. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  1653. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  1654. if (metadata) {
  1655. [metadatas addObject:metadata];
  1656. }
  1657. }
  1658. // [CCUtility getGroupBySettings]
  1659. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  1660. [self tableViewReloadData];
  1661. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  1662. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  1663. _noFilesSearchDescription = @"";
  1664. }
  1665. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  1666. _noFilesSearchTitle = @"";
  1667. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  1668. }
  1669. [self.tableView reloadEmptyDataSet];
  1670. return;
  1671. }
  1672. // Se non siamo nella dir appropriata esci
  1673. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  1674. return;
  1675. }
  1676. // Controllo data lettura Data Source
  1677. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1678. if (tableDirectory == nil) {
  1679. return;
  1680. }
  1681. // Get MetadataFolder
  1682. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  1683. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  1684. else
  1685. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tableDirectory.ocId]];
  1686. // Remove optimization for encrypted directory
  1687. if (_metadataFolder.e2eEncrypted)
  1688. _dateReadDataSource = nil;
  1689. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  1690. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  1691. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  1692. _dateReadDataSource = [NSDate date];
  1693. // Data Source
  1694. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1695. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  1696. dispatch_async(dispatch_get_main_queue(), ^{
  1697. sectionDataSource = sectionDataSourceTemp;
  1698. [self tableViewReloadData];
  1699. });
  1700. });
  1701. } else {
  1702. [self tableViewReloadData];
  1703. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  1704. }
  1705. // BLINK
  1706. if (self.blinkFileNamePath != nil) {
  1707. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1708. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  1709. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  1710. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1711. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  1712. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  1713. if ([key isEqualToString:metadata.ocId]) {
  1714. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  1715. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  1716. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1717. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1718. if (cell) {
  1719. self.blinkFileNamePath = nil;
  1720. [[NCUtility sharedInstance] blinkWithCell:cell];
  1721. }
  1722. });
  1723. }
  1724. }
  1725. }
  1726. }
  1727. });
  1728. }
  1729. }
  1730. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  1731. {
  1732. // test
  1733. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  1734. return nil;
  1735. }
  1736. // get auto upload folder
  1737. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1738. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  1739. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  1740. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl] sorted:nil ascending:NO];
  1741. // [CCUtility getGroupBySettings]
  1742. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  1743. if (withReloadData) {
  1744. sectionDataSource = sectionDataSourceTemp;
  1745. [self tableViewReloadData];
  1746. }
  1747. return sectionDataSourceTemp;
  1748. }
  1749. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  1750. {
  1751. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1752. if (selectedRows.count > 0) {
  1753. for (NSIndexPath *selectionIndex in selectedRows) {
  1754. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  1755. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  1756. [metadatas addObject:metadata];
  1757. }
  1758. }
  1759. return metadatas;
  1760. }
  1761. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  1762. {
  1763. NSInteger totSections =[sectionDataSource.sections count] ;
  1764. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  1765. return nil;
  1766. }
  1767. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  1768. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  1769. }
  1770. #pragma --------------------------------------------------------------------------------------------
  1771. #pragma mark - ==== Table ====
  1772. #pragma --------------------------------------------------------------------------------------------
  1773. - (void)tableViewToggle
  1774. {
  1775. [self tableViewSelect:!_isSelectedMode];
  1776. }
  1777. - (void)tableViewSelect:(BOOL)toggle
  1778. {
  1779. _isSelectedMode = toggle;
  1780. // chiudiamo eventuali swipe aperti
  1781. if (_isSelectedMode)
  1782. [self.tableView setEditing:NO animated:NO];
  1783. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  1784. [self.tableView setEditing:_isSelectedMode animated:YES];
  1785. if (_isSelectedMode)
  1786. [self setUINavigationBarSelected];
  1787. else
  1788. [self setUINavigationBarDefault];
  1789. [_selectedocIdsMetadatas removeAllObjects];
  1790. [self setTitle];
  1791. }
  1792. - (void)tableViewReloadData
  1793. {
  1794. // store selected cells before relod
  1795. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  1796. // reload table view
  1797. [self.tableView reloadData];
  1798. // selected cells stored
  1799. for (NSIndexPath *path in indexPaths)
  1800. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  1801. [self setTableViewHeader];
  1802. [self setTableViewFooter];
  1803. if (self.tableView.editing)
  1804. [self setTitle];
  1805. [self.tableView reloadEmptyDataSet];
  1806. }
  1807. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  1808. {
  1809. if (tableView.editing == 1) {
  1810. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1811. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  1812. return NO;
  1813. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  1814. return NO;
  1815. else
  1816. return YES;
  1817. } else {
  1818. [_selectedocIdsMetadatas removeAllObjects];
  1819. }
  1820. return YES;
  1821. }
  1822. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  1823. {
  1824. return 60;
  1825. }
  1826. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  1827. {
  1828. return [[sectionDataSource.sectionArrayRow allKeys] count];
  1829. }
  1830. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1831. {
  1832. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  1833. }
  1834. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  1835. {
  1836. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  1837. NSString *sectionTitle = [sections objectAtIndex:section];
  1838. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  1839. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  1840. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  1841. return 20.f;
  1842. }
  1843. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  1844. {
  1845. float shift;
  1846. UIVisualEffectView *visualEffectView;
  1847. NSString *titleSection;
  1848. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  1849. return nil;
  1850. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  1851. titleSection = [sectionDataSource.sections objectAtIndex:section];
  1852. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  1853. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  1854. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  1855. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  1856. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  1857. else titleSection = NSLocalizedString(titleSection,nil);
  1858. // Format title
  1859. UIVisualEffect *blurEffect;
  1860. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  1861. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  1862. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brand colorWithAlphaComponent:0.2];
  1863. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  1864. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1865. shift = - 35;
  1866. else
  1867. shift = - 20;
  1868. } else shift = - 10;
  1869. // Title
  1870. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  1871. titleLabel.backgroundColor = [UIColor clearColor];
  1872. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  1873. titleLabel.font = [UIFont systemFontOfSize:12];
  1874. titleLabel.textAlignment = NSTextAlignmentLeft;
  1875. titleLabel.text = titleSection;
  1876. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1877. [visualEffectView.contentView addSubview:titleLabel];
  1878. // Elements
  1879. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  1880. elementLabel.backgroundColor = [UIColor clearColor];
  1881. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  1882. elementLabel.font = [UIFont systemFontOfSize:12];
  1883. elementLabel.textAlignment = NSTextAlignmentRight;
  1884. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  1885. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  1886. NSUInteger rowsCount = [metadatas count];
  1887. if (rowsCount == 0) return nil;
  1888. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  1889. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  1890. [visualEffectView.contentView addSubview:elementLabel];
  1891. return visualEffectView;
  1892. }
  1893. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  1894. {
  1895. return [sectionDataSource.sections indexOfObject:title];
  1896. }
  1897. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  1898. {
  1899. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  1900. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  1901. else
  1902. return nil;
  1903. }
  1904. /*
  1905. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  1906. {
  1907. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  1908. }
  1909. }
  1910. */
  1911. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1912. {
  1913. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1914. tableShare *shareCell;
  1915. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  1916. return [CCCellMain new];
  1917. }
  1918. for (tableShare *share in appDelegate.shares) {
  1919. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  1920. shareCell = share;
  1921. break;
  1922. }
  1923. }
  1924. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  1925. // NORMAL - > MAIN
  1926. if ([cell isKindOfClass:[CCCellMain class]]) {
  1927. // Comment tap
  1928. if (metadata.commentsUnread) {
  1929. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  1930. [tapComment setNumberOfTapsRequired:1];
  1931. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  1932. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  1933. }
  1934. // Share add Tap
  1935. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  1936. [tapShare setNumberOfTapsRequired:1];
  1937. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  1938. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  1939. // More
  1940. if ([self canOpenMenuAction:metadata]) {
  1941. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  1942. [tapMore setNumberOfTapsRequired:1];
  1943. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  1944. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  1945. }
  1946. // MGSwipeButton
  1947. ((CCCellMain *)cell).delegate = self;
  1948. // LEFT
  1949. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  1950. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  1951. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  1952. //centerIconOverText
  1953. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  1954. [favoriteButton centerIconOverText];
  1955. // RIGHT
  1956. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  1957. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  1958. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  1959. //centerIconOverText
  1960. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  1961. [deleteButton centerIconOverText];
  1962. }
  1963. // TRANSFER
  1964. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  1965. // gesture Transfer
  1966. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  1967. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  1968. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  1969. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  1970. }
  1971. return cell;
  1972. }
  1973. - (void)setTableViewHeader
  1974. {
  1975. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:appDelegate.activeAccount elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  1976. NSString *trimmedRichWorkspaceText = [self.richWorkspaceText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  1977. if (serverVersionMajor < k_nextcloud_version_18_0 || trimmedRichWorkspaceText.length == 0 ) {
  1978. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  1979. } else {
  1980. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  1981. }
  1982. if (self.searchController.isActive == true) {
  1983. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, 0)];
  1984. }
  1985. [self.viewRichWorkspace setNeedsLayout];
  1986. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  1987. }
  1988. - (void)setTableViewFooter
  1989. {
  1990. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1991. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1992. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  1993. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  1994. UIFont *appFont = [UIFont systemFontOfSize:12];
  1995. footerLabel.font = appFont;
  1996. footerLabel.textColor = [UIColor grayColor];
  1997. footerLabel.backgroundColor = [UIColor clearColor];
  1998. footerLabel.textAlignment = NSTextAlignmentCenter;
  1999. NSString *folders;
  2000. NSString *files;
  2001. NSString *footerText;
  2002. if (sectionDataSource.directories > 1) {
  2003. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2004. } else if (sectionDataSource.directories == 1){
  2005. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2006. } else {
  2007. folders = @"";
  2008. }
  2009. if (sectionDataSource.files > 1) {
  2010. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2011. } else if (sectionDataSource.files == 1){
  2012. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2013. } else {
  2014. files = @"";
  2015. }
  2016. if ([folders isEqualToString:@""]) {
  2017. footerText = files;
  2018. } else if ([files isEqualToString:@""]) {
  2019. footerText = folders;
  2020. } else {
  2021. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2022. }
  2023. footerLabel.text = footerText;
  2024. [footerView addSubview:footerLabel];
  2025. [self.tableView setTableFooterView:footerView];
  2026. }
  2027. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2028. {
  2029. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2030. // settiamo il record file.
  2031. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2032. if (!self.metadata)
  2033. return;
  2034. // se non può essere selezionata deseleziona
  2035. if ([cell isEditing] == NO)
  2036. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2037. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2038. if (self.tableView.editing) {
  2039. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  2040. [self setTitle];
  2041. return;
  2042. }
  2043. // se è in corso una sessione
  2044. if (self.metadata.status != k_metadataStatusNormal)
  2045. return;
  2046. // file
  2047. if (self.metadata.directory == NO) {
  2048. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  2049. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2050. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": self.metadata, @"selector": selectorLoadFileView, @"errorCode": @(0), @"errorDescription": @""}];
  2051. } else {
  2052. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2053. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2054. } else {
  2055. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) && _metadataFolder.e2eEncrypted == NO) {
  2056. [self shouldPerformSegue:self.metadata selector:@""];
  2057. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditing:self.metadata] != nil) {
  2058. if (appDelegate.reachability.isReachable) {
  2059. [self shouldPerformSegue:self.metadata selector:@""];
  2060. } else {
  2061. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2062. }
  2063. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  2064. if (appDelegate.reachability.isReachable) {
  2065. [self shouldPerformSegue:self.metadata selector:@""];
  2066. } else {
  2067. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2068. }
  2069. } else {
  2070. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  2071. [self shouldPerformSegue:self.metadata selector:selectorLoadFileView];
  2072. }
  2073. self.metadata.session = k_download_session;
  2074. self.metadata.sessionError = @"";
  2075. self.metadata.sessionSelector = selectorLoadFileView;
  2076. self.metadata.status = k_metadataStatusWaitDownload;
  2077. // Add Metadata for Download
  2078. [[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2079. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2080. [appDelegate startLoadAutoDownloadUpload];
  2081. }
  2082. }
  2083. }
  2084. }
  2085. if (self.metadata.directory) {
  2086. [self performSegueDirectoryWithMetadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2087. }
  2088. }
  2089. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  2090. {
  2091. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2092. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  2093. [self setTitle];
  2094. }
  2095. - (void)didSelectAll
  2096. {
  2097. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  2098. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  2099. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  2100. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2101. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  2102. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  2103. }
  2104. }
  2105. [self setTitle];
  2106. }
  2107. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  2108. {
  2109. if (!indexPath)
  2110. return NO;
  2111. NSInteger section = indexPath.section;
  2112. NSInteger row = indexPath.row;
  2113. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  2114. if (section > lastSectionIndex || lastSectionIndex < 0)
  2115. return NO;
  2116. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  2117. if (rowCount < 0)
  2118. return NO;
  2119. return row <= rowCount;
  2120. }
  2121. #pragma --------------------------------------------------------------------------------------------
  2122. #pragma mark ===== Navigation ====
  2123. #pragma --------------------------------------------------------------------------------------------
  2124. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  2125. {
  2126. // if background return
  2127. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  2128. if (self.view.window == NO)
  2129. return;
  2130. // Collapsed ma siamo già in detail esci
  2131. if (self.splitViewController.isCollapsed) {
  2132. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  2133. }
  2134. // Metadata for push detail
  2135. self.metadataForPushDetail = metadata;
  2136. self.selectorForPushDetail = selector;
  2137. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  2138. }
  2139. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  2140. {
  2141. tableMetadata *metadata;
  2142. NSMutableArray *photoDataSource = [NSMutableArray new];
  2143. UINavigationController *navigationController = segue.destinationViewController;
  2144. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  2145. if ([sender isKindOfClass:[tableMetadata class]]) {
  2146. metadata = sender;
  2147. [photoDataSource addObject:sender];
  2148. } else {
  2149. metadata = self.metadataForPushDetail;
  2150. for (NSString *ocId in sectionDataSource.allOcId) {
  2151. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2152. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  2153. [photoDataSource addObject:metadata];
  2154. }
  2155. }
  2156. detailViewController.metadata = metadata;
  2157. detailViewController.selector = self.selectorForPushDetail;
  2158. [detailViewController setTitle:metadata.fileNameView];
  2159. }
  2160. // can i go to next viewcontroller
  2161. - (void)performSegueDirectoryWithMetadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  2162. {
  2163. NSString *nomeDir;
  2164. if (self.tableView.editing == NO) {
  2165. // E2EE Check enable
  2166. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  2167. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2168. return;
  2169. }
  2170. nomeDir = metadata.fileName;
  2171. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  2172. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  2173. if (!viewController) {
  2174. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  2175. viewController.serverUrl = serverUrlPush;
  2176. viewController.titleMain = metadata.fileNameView;
  2177. viewController.blinkFileNamePath = blinkFileNamePath;
  2178. // save self
  2179. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  2180. [self.navigationController pushViewController:viewController animated:YES];
  2181. } else {
  2182. if (viewController.isViewLoaded) {
  2183. viewController.titleMain = metadata.fileNameView;
  2184. viewController.blinkFileNamePath = blinkFileNamePath;
  2185. // Fix : Application tried to present modally an active controller
  2186. if ([self.navigationController isBeingPresented]) {
  2187. // being presented
  2188. } else if ([self.navigationController isMovingToParentViewController]) {
  2189. // being pushed
  2190. } else {
  2191. [self.navigationController pushViewController:viewController animated:YES];
  2192. }
  2193. }
  2194. }
  2195. }
  2196. }
  2197. @end