CCMain.m 149 KB

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