CCMain.m 148 KB

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