CCMain.m 148 KB

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