CCMain.m 157 KB

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