CCMain.m 148 KB

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