CCMain.m 159 KB

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