CCMain.m 160 KB

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