CCMain.m 160 KB

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