CCMain.m 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465
  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:@"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:[UIImage imageNamed:@"navigationSort"] 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]) {
  857. tableMetadata *metadataFolder = [tableMetadata new];
  858. (void)[[NCNetworking sharedInstance] convertFiles:files urlString:appDelegate.activeUrl serverUrl:self.serverUrl user:appDelegate.activeUser metadataFolder:&metadataFolder];
  859. // Rich Workspace
  860. [[NCManageDatabase sharedInstance] setDirectoryWithOcId:metadataFolder.ocId serverUrl:self.serverUrl richWorkspace:metadataFolder.richWorkspace account:account];
  861. self.richWorkspaceText = metadataFolder.richWorkspace;
  862. [self setTableViewHeader];
  863. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadataFolder.serverUrl]];
  864. // Read folder: No record, Change etag or BLINK
  865. if ([sectionDataSource.allRecordsDataSource count] == 0 || [metadataFolder.etag isEqualToString:directory.etag] == NO || self.blinkFileNamePath != nil) {
  866. [self readFolder:self.serverUrl];
  867. }
  868. } else if (errorCode != 0) {
  869. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorMessage delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  870. } else {
  871. NSLog(@"[LOG] It has been changed user during networking process, error.");
  872. }
  873. }];
  874. }
  875. #pragma --------------------------------------------------------------------------------------------
  876. #pragma mark ==== Read Folder ====
  877. #pragma --------------------------------------------------------------------------------------------
  878. - (void)insertMetadatasWithAccount:(NSString *)account serverUrl:(NSString *)serverUrl metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  879. {
  880. // stoprefresh
  881. [refreshControl endRefreshing];
  882. // save metadataFolder
  883. _metadataFolder = metadataFolder;
  884. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  885. if (tableAccount == nil) {
  886. return;
  887. }
  888. if (self.searchController.isActive == NO) {
  889. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:nil etag:metadataFolder.etag ocId:metadataFolder.ocId encrypted:metadataFolder.e2eEncrypted richWorkspace:nil account:account];
  890. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND (status == %d OR status == %d)", account, serverUrl, k_metadataStatusNormal, k_metadataStatusHide]];
  891. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithServerUrl:serverUrl account:account];
  892. }
  893. 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];
  894. // insert in Database
  895. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas];
  896. // insert in Database the /
  897. if (metadataFolder != nil) {
  898. _metadataFolder = [[NCManageDatabase sharedInstance] addMetadata:metadataFolder];
  899. }
  900. // reinsert metadatas in Download
  901. if (metadatasInDownload) {
  902. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload];
  903. }
  904. // File is changed ??
  905. if (!self.searchController.isActive && metadatasToInsertInDB) {
  906. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  907. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:serverUrl account:account withDownload:NO];
  908. });
  909. }
  910. // Search Mode
  911. if (self.searchController.isActive) {
  912. // Fix managed -> Unmanaged _searchResultMetadatas
  913. if (metadatasToInsertInDB)
  914. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  915. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  916. }
  917. // this is the same directory
  918. if ([serverUrl isEqualToString:_serverUrl] && !self.searchController.isActive) {
  919. // reload
  920. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  921. [self tableViewReloadData];
  922. }
  923. // E2EE Is encrypted folder get metadata
  924. if (_metadataFolder.e2eEncrypted) {
  925. NSString *metadataFolderocId = metadataFolder.ocId;
  926. // Read Metadata
  927. if ([CCUtility isEndToEndEnabled:account]) {
  928. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  929. NSString *metadata;
  930. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata ocId:metadataFolderocId user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  931. dispatch_async(dispatch_get_main_queue(), ^{
  932. if (error) {
  933. if (error.code != kOCErrorServerPathNotFound)
  934. [[NCContentPresenter shared] messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  935. } else {
  936. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:self.serverUrl account:account url:tableAccount.url] == false)
  937. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  938. else
  939. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl ocId:nil action:k_action_NULL];
  940. }
  941. });
  942. });
  943. } else {
  944. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  945. }
  946. }
  947. // rewrite title
  948. [self setTitle];
  949. }
  950. - (void)readFolder:(NSString *)serverUrl
  951. {
  952. // init control
  953. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  954. [refreshControl endRefreshing];
  955. return;
  956. }
  957. // Search Mode
  958. if (self.searchController.isActive) {
  959. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  960. _searchFileName = @""; // forced reload searchg
  961. [self updateSearchResultsForSearchController:self.searchController];
  962. return;
  963. }
  964. _loadingFolder = YES;
  965. [self tableViewReloadData];
  966. [[OCNetworking sharedManager] readFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl depth:@"1" completion:^(NSString *account, NSArray *metadatas, tableMetadata *metadataFolder, NSString *message, NSInteger errorCode) {
  967. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  968. [self insertMetadatasWithAccount:account serverUrl:serverUrl metadataFolder:metadataFolder metadatas:metadatas];
  969. } else if (errorCode != 0) {
  970. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  971. } else {
  972. NSLog(@"[LOG] It has been changed user during networking process, error.");
  973. }
  974. _loadingFolder = NO;
  975. }];
  976. }
  977. #pragma mark -
  978. #pragma --------------------------------------------------------------------------------------------
  979. #pragma mark ===== Search =====
  980. #pragma --------------------------------------------------------------------------------------------
  981. - (void)searchStartTimer
  982. {
  983. if (self.searchController.isActive == false) {
  984. return;
  985. }
  986. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  987. [[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) {
  988. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  989. #if TARGET_OS_SIMULATOR
  990. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:account];
  991. if (capabilities.isFulltextsearchEnabled) {
  992. [[OCNetworking sharedManager] fullTextSearchWithAccount:appDelegate.activeAccount text:_searchFileName page:1 completion:^(NSString *account, NSArray *items, NSString *message, NSInteger errorCode) {
  993. NSLog(@"x");
  994. }];
  995. }
  996. #endif
  997. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  998. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  999. } else {
  1000. if (errorCode != 0) {
  1001. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1002. } else {
  1003. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1004. }
  1005. _searchFileName = @"";
  1006. }
  1007. }];
  1008. _noFilesSearchTitle = @"";
  1009. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1010. [self.tableView reloadEmptyDataSet];
  1011. }
  1012. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1013. {
  1014. // Color text "Cancel"
  1015. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:NCBrandColor.sharedInstance.brandText];
  1016. if (searchController.isActive) {
  1017. [self deleteRefreshControl];
  1018. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1019. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1020. _searchFileName = fileName;
  1021. // First : filter
  1022. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView CONTAINS[cd] %@", appDelegate.activeAccount, _serverUrl, fileName] sorted:nil ascending:NO];
  1023. [_searchResultMetadatas removeAllObjects];
  1024. for (tableMetadata *record in records)
  1025. [_searchResultMetadatas addObject:record];
  1026. [self insertMetadatasWithAccount:appDelegate.activeAccount serverUrl:_serverUrl metadataFolder:nil metadatas:_searchResultMetadatas];
  1027. // Version >= 12
  1028. if ([[NCManageDatabase sharedInstance] getServerVersionWithAccount:appDelegate.activeAccount] >= 12) {
  1029. [_timerWaitInput invalidate];
  1030. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1031. }
  1032. }
  1033. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1034. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1035. }
  1036. } else {
  1037. [self createRefreshControl];
  1038. [self reloadDatasource:self.serverUrl ocId:nil action:k_action_NULL];
  1039. }
  1040. }
  1041. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1042. {
  1043. [self cancelSearchBar];
  1044. }
  1045. - (void)cancelSearchBar
  1046. {
  1047. if (self.searchController.active) {
  1048. [self.searchController setActive:NO];
  1049. _searchFileName = @"";
  1050. _dateReadDataSource = nil;
  1051. _searchResultMetadatas = [NSMutableArray new];
  1052. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1053. }
  1054. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1055. [self setTableViewHeader];
  1056. });
  1057. }
  1058. #pragma mark -
  1059. #pragma --------------------------------------------------------------------------------------------
  1060. #pragma mark ===== Delete File or Folder =====
  1061. #pragma --------------------------------------------------------------------------------------------
  1062. - (void)deleteFile
  1063. {
  1064. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1065. return;
  1066. NSArray *metadatas;
  1067. if ([_selectedocIdsMetadatas count] > 0) {
  1068. metadatas = [_selectedocIdsMetadatas allValues];
  1069. } else {
  1070. metadatas = [[NSArray alloc] initWithObjects:self.metadata, nil];
  1071. }
  1072. // remove optimization
  1073. _dateReadDataSource = nil;
  1074. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:_metadataFolder.e2eEncrypted serverUrl:self.serverUrl folderocId:_metadataFolder.ocId completion:^(NSInteger errorCode, NSString *message) {
  1075. // Reload
  1076. if (self.searchController.isActive)
  1077. [self readFolder:self.serverUrl];
  1078. else
  1079. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1080. }];
  1081. // End Select Table View
  1082. [self tableViewSelect:false];
  1083. }
  1084. #pragma --------------------------------------------------------------------------------------------
  1085. #pragma mark ===== Rename =====
  1086. #pragma --------------------------------------------------------------------------------------------
  1087. - (void)renameFile:(NSArray *)arguments
  1088. {
  1089. tableMetadata *metadata = [arguments objectAtIndex:0];
  1090. NSString *fileName = [arguments objectAtIndex:1];
  1091. // E2EE
  1092. if (_metadataFolder.e2eEncrypted) {
  1093. // verify if exists the new fileName
  1094. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1095. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1096. return;
  1097. }
  1098. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1099. 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];
  1100. if (error) {
  1101. [[NCContentPresenter shared] messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1102. } else {
  1103. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithServerUrl:metadata.serverUrl fileName:metadata.fileName newFileNameView:fileName account:appDelegate.activeAccount];
  1104. // Move file system
  1105. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], metadata.fileNameView];
  1106. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], fileName];
  1107. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1108. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:fileName] error:nil];
  1109. }
  1110. // Unlock
  1111. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1112. if (tableLock != nil) {
  1113. 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];
  1114. if (error) {
  1115. [[NCContentPresenter shared] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1116. }
  1117. }
  1118. dispatch_async(dispatch_get_main_queue(), ^{
  1119. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1120. });
  1121. });
  1122. } else {
  1123. // verify permission
  1124. BOOL permission = [[NCUtility sharedInstance] permissionsContainsString:metadata.permissions permissions:k_permission_can_rename];
  1125. if (![metadata.permissions isEqualToString:@""] && permission == false) {
  1126. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_no_permission_modify_file_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1127. return;
  1128. }
  1129. // Plain
  1130. NSString *fileNameNew = [CCUtility removeForbiddenCharactersServer:fileName];
  1131. if ([fileName length] == 0 || [fileName isEqualToString:metadata.fileNameView]) {
  1132. return;
  1133. }
  1134. // Verify if exists the fileName TO
  1135. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:metadata.serverUrl fileName:fileNameNew completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  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. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1146. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1147. // Rename metadata
  1148. (void) [[NCManageDatabase sharedInstance] renameMetadataWithFileNameTo:fileNameNew ocId:metadata.ocId];
  1149. if (metadata.directory) {
  1150. NSString *serverUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  1151. NSString *serverUrlTo = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:fileNameNew];
  1152. tableDirectory *directoryTable = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, metadata.serverUrl]];
  1153. if (directoryTable == nil) {
  1154. [[NCContentPresenter shared] messageNotification:@"_rename_" description:@"Internal error, ServerUrl not found" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1155. return;
  1156. }
  1157. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:serverUrlTo etag:@"" ocId:nil encrypted:directoryTable.e2eEncrypted richWorkspace:nil account:appDelegate.activeAccount];
  1158. } else {
  1159. [[NCManageDatabase sharedInstance] setLocalFileWithOcId:metadata.ocId date:nil exifDate:nil exifLatitude:nil exifLongitude:nil fileName:fileNameNew etag:nil];
  1160. // Move file system
  1161. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], metadata.fileName];
  1162. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageOcId:metadata.ocId], fileNameNew];
  1163. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1164. NSString *atPathIcon = [CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileName];
  1165. NSString *toPathIcon = [CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:fileNameNew];
  1166. [[NSFileManager defaultManager] moveItemAtPath:atPathIcon toPath:toPathIcon error:nil];
  1167. }
  1168. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1169. } else if (errorCode != 0) {
  1170. [[NCContentPresenter shared] messageNotification:@"_rename_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1171. } else {
  1172. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1173. }
  1174. }];
  1175. } else {
  1176. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1177. }
  1178. } else {
  1179. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1180. }
  1181. }];
  1182. }
  1183. }
  1184. #pragma --------------------------------------------------------------------------------------------
  1185. #pragma mark ===== Move =====
  1186. #pragma --------------------------------------------------------------------------------------------
  1187. - (void)moveFileOrFolderMetadata:(tableMetadata *)metadata serverUrlTo:(NSString *)serverUrlTo numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1188. {
  1189. // verify permission
  1190. BOOL permission = [[NCUtility sharedInstance] permissionsContainsString:metadata.permissions permissions:k_permission_can_move];
  1191. if (![metadata.permissions isEqualToString:@""] && permission == false) {
  1192. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_no_permission_modify_file_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1193. return;
  1194. }
  1195. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:serverUrlTo fileName:metadata.fileName completion:^(NSString *account, tableMetadata *metadataReadFile, NSString *message, NSInteger errorCode) {
  1196. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1197. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1198. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1199. }];
  1200. [alert addAction:ok];
  1201. [self presentViewController:alert animated:YES completion:nil];
  1202. // End Select Table View
  1203. [self tableViewSelect:false];
  1204. // reload Datasource
  1205. [self readFileReloadFolder];
  1206. } else if (errorCode != 0) {
  1207. if (errorCode == kOCErrorServerPathNotFound) {
  1208. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  1209. NSString *fileNameToPath = [NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName];
  1210. [[OCNetworking sharedManager] moveFileOrFolderWithAccount:appDelegate.activeAccount fileName:fileNamePath fileNameTo:fileNameToPath completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  1211. [_hud hideHud];
  1212. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1213. if (metadata.directory) {
  1214. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName] account:account];
  1215. }
  1216. [[NCManageDatabase sharedInstance] moveMetadataWithOcId:metadata.ocId serverUrlTo:serverUrlTo];
  1217. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:metadata.serverUrl account:account];
  1218. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrlTo account:account];
  1219. // next
  1220. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  1221. if ([_selectedocIdsMetadatas count] > 0) {
  1222. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1223. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrlTo numFile:[_selectedocIdsMetadatas count] ofFile:_numSelectedocIdsMetadatas];
  1224. } else {
  1225. // End Select Table View
  1226. [self tableViewSelect:false];
  1227. // reload Datasource
  1228. if (self.searchController.isActive)
  1229. [self readFolder:metadata.serverUrl];
  1230. else
  1231. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1232. }
  1233. } else if (errorCode != 0) {
  1234. [[NCContentPresenter shared] messageNotification:@"_move_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1235. // End Select Table View
  1236. [self tableViewSelect:false];
  1237. // reload Datasource
  1238. if (self.searchController.isActive)
  1239. [self readFolder:metadata.serverUrl];
  1240. else
  1241. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadata.serverUrl ocId:nil action:k_action_NULL];
  1242. } else {
  1243. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1244. }
  1245. }];
  1246. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1247. } else {
  1248. [[NCContentPresenter shared] messageNotification:@"_error_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1249. }
  1250. } else {
  1251. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1252. }
  1253. }];
  1254. }
  1255. // DELEGATE : Select
  1256. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  1257. {
  1258. if (serverUrl == nil) {
  1259. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1260. } else {
  1261. // E2EE DENIED
  1262. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) {
  1263. [[NCContentPresenter shared] messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  1264. return;
  1265. }
  1266. if ([_selectedocIdsMetadatas count] > 0) {
  1267. _numSelectedocIdsMetadatas = [_selectedocIdsMetadatas count];
  1268. NSArray *metadatas = [_selectedocIdsMetadatas allValues];
  1269. [self moveFileOrFolderMetadata:[metadatas objectAtIndex:0] serverUrlTo:serverUrl numFile:[_selectedocIdsMetadatas count] ofFile:_numSelectedocIdsMetadatas];
  1270. } else {
  1271. _numSelectedocIdsMetadatas = 1;
  1272. [self moveFileOrFolderMetadata:self.metadata serverUrlTo:serverUrl numFile:1 ofFile:_numSelectedocIdsMetadatas];
  1273. }
  1274. }
  1275. }
  1276. - (void)moveOpenWindow:(NSArray *)indexPaths
  1277. {
  1278. if (_isSelectedMode && [_selectedocIdsMetadatas count] == 0)
  1279. return;
  1280. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1281. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1282. viewController.delegate = self;
  1283. viewController.hideButtonCreateFolder = false;
  1284. viewController.selectFile = false;
  1285. viewController.includeDirectoryE2EEncryption = false;
  1286. viewController.includeImages = false;
  1287. viewController.type = @"";
  1288. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1289. viewController.layoutViewSelect = k_layout_view_move;
  1290. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  1291. [self presentViewController:navigationController animated:YES completion:nil];
  1292. }
  1293. #pragma --------------------------------------------------------------------------------------------
  1294. #pragma mark ===== Create folder =====
  1295. #pragma --------------------------------------------------------------------------------------------
  1296. - (void)createFolder
  1297. {
  1298. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1299. NSString *message;
  1300. UIAlertController *alertController;
  1301. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1302. message = @"/";
  1303. } else {
  1304. message = [serverUrl lastPathComponent];
  1305. }
  1306. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1307. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1308. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1309. textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  1310. }];
  1311. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1312. NSLog(@"[LOG] Cancel action");
  1313. }];
  1314. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1315. UITextField *fileName = alertController.textFields.firstObject;
  1316. [self createFolder:fileName.text serverUrl:serverUrl];
  1317. }];
  1318. okAction.enabled = NO;
  1319. [alertController addAction:cancelAction];
  1320. [alertController addAction:okAction];
  1321. [self presentViewController:alertController animated:YES completion:nil];
  1322. }
  1323. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1324. {
  1325. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1326. fileNameFolder = [[NCUtility sharedInstance] createFileName:fileNameFolder serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1327. if (![fileNameFolder length]) return;
  1328. NSString *ocIdTemp = [[NSUUID UUID] UUIDString];
  1329. // Create Directory (temp) on metadata
  1330. 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:@""];
  1331. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1332. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl account:appDelegate.activeAccount];
  1333. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1334. // Creeate folder Networking
  1335. [[OCNetworking sharedManager] createFolderWithAccount:appDelegate.activeAccount serverUrl:serverUrl fileName:fileNameFolder completion:^(NSString *account, NSString *ocId, NSDate *date, NSString *message, NSInteger errorCode) {
  1336. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  1337. // Delete Temp Dir
  1338. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocIdTemp]];
  1339. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1340. if (_metadataFolder.e2eEncrypted) {
  1341. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1342. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory ocId:ocId user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1343. dispatch_async(dispatch_get_main_queue(), ^{
  1344. if (error) {
  1345. [[NCContentPresenter shared] messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  1346. }
  1347. [self readFolder:self.serverUrl];
  1348. });
  1349. });
  1350. } else {
  1351. [self readFolder:self.serverUrl];
  1352. }
  1353. } else {
  1354. // Delete Temp Dir
  1355. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocIdTemp]];
  1356. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1357. if (errorCode != 0) {
  1358. [[NCContentPresenter shared] messageNotification:@"_create_folder_" description:message delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1359. } else {
  1360. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1361. }
  1362. }
  1363. }];
  1364. }
  1365. #pragma --------------------------------------------------------------------------------------------
  1366. #pragma mark ===== Progress & Task Button =====
  1367. #pragma --------------------------------------------------------------------------------------------
  1368. - (void)triggerProgressTask:(NSNotification *)notification
  1369. {
  1370. if (sectionDataSource.ocIdIndexPath != nil) {
  1371. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceocIdIndexPath:sectionDataSource.ocIdIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1372. }
  1373. }
  1374. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1375. {
  1376. UITouch *touch = [[event allTouches] anyObject];
  1377. CGPoint location = [touch locationInView:self.tableView];
  1378. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1379. if ([self indexPathIsValid:indexPath]) {
  1380. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1381. if (metadataSection) {
  1382. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataSection.ocId]];
  1383. if (metadata)
  1384. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true uploadStatusForcedStart:false];
  1385. }
  1386. }
  1387. }
  1388. - (void)cancelAllTask:(id)sender
  1389. {
  1390. CGPoint location = [sender locationInView:self.tableView];
  1391. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1392. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1393. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1394. [NCUtility.sharedInstance startActivityIndicatorWithView:self.view bottom:0];
  1395. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1396. [NCUtility.sharedInstance stopActivityIndicator];
  1397. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil ocId:nil action:k_action_NULL];
  1398. }]];
  1399. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1400. alertController.popoverPresentationController.sourceView = self.tableView;
  1401. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1402. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1403. [alertController.view layoutIfNeeded];
  1404. [self presentViewController:alertController animated:YES completion:nil];
  1405. }
  1406. #pragma --------------------------------------------------------------------------------------------
  1407. #pragma mark ===== Tap =====
  1408. #pragma --------------------------------------------------------------------------------------------
  1409. - (void)tapActionComment:(UITapGestureRecognizer *)tapGesture
  1410. {
  1411. CGPoint location = [tapGesture locationInView:self.tableView];
  1412. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1413. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1414. if (metadata) {
  1415. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:1];
  1416. }
  1417. }
  1418. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1419. {
  1420. CGPoint location = [tapGesture locationInView:self.tableView];
  1421. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1422. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1423. if (metadata) {
  1424. [[NCMainCommon sharedInstance] openShareWithViewController:self metadata:metadata indexPage:2];
  1425. }
  1426. }
  1427. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1428. {
  1429. CGPoint location = [tapGesture locationInView:self.tableView];
  1430. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1431. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1432. if (metadata) {
  1433. }
  1434. }
  1435. #pragma --------------------------------------------------------------------------------------------
  1436. #pragma mark ===== Rich Workspace =====
  1437. #pragma --------------------------------------------------------------------------------------------
  1438. - (void)viewRichWorkspaceTapAction:(UITapGestureRecognizer *)tapGesture
  1439. {
  1440. [UIView animateWithDuration:0.5 animations:^{
  1441. [self.tableView setContentOffset:CGPointMake(0, heightSearchBar)];
  1442. } completion:^(BOOL finished) {
  1443. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCViewerRichWorkspace" bundle:nil] instantiateInitialViewController];
  1444. NCViewerRichWorkspace *viewerRichWorkspace = (NCViewerRichWorkspace *)[navigationController topViewController];
  1445. viewerRichWorkspace.richWorkspaceText = self.richWorkspaceText;
  1446. viewerRichWorkspace.serverUrl = self.serverUrl;
  1447. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1448. [self presentViewController:navigationController animated:NO completion:NULL];
  1449. }];
  1450. }
  1451. - (void)createRichWorkspace
  1452. {
  1453. NCRichWorkspaceCommon *richWorkspaceCommon = [NCRichWorkspaceCommon new];
  1454. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", appDelegate.activeAccount, self.serverUrl, k_fileNameRichWorkspace.lowercaseString]];
  1455. if (metadata) {
  1456. [richWorkspaceCommon openViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1457. } else {
  1458. [richWorkspaceCommon createViewerNextcloudTextWithServerUrl:self.serverUrl viewController:self];
  1459. }
  1460. }
  1461. #pragma --------------------------------------------------------------------------------------------
  1462. #pragma mark ===== Favorite =====
  1463. #pragma --------------------------------------------------------------------------------------------
  1464. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1465. {
  1466. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1467. [[NCCommunication sharedInstance] setFavoriteWithUrlString:appDelegate.activeUrl fileName:fileNameServerUrl favorite:favorite account:appDelegate.activeAccount completionHandler:^(NSString *account, NSInteger errorCode, NSString *errorDecription) {
  1468. if (errorCode == 0 && [appDelegate.activeAccount isEqualToString:account]) {
  1469. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithOcId:metadata.ocId favorite:favorite];
  1470. _dateReadDataSource = nil;
  1471. if (self.searchController.isActive)
  1472. [self readFolder:self.serverUrl];
  1473. else
  1474. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1475. if (metadata.directory && favorite) {
  1476. NSString *selector;
  1477. if ([CCUtility getFavoriteOffline])
  1478. selector = selectorReadFolderWithDownload;
  1479. else
  1480. selector = selectorReadFolder;
  1481. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName] selector:selector account:appDelegate.activeAccount];
  1482. }
  1483. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1484. metadata.favorite = favorite;
  1485. metadata.session = k_download_session;
  1486. metadata.sessionError = @"";
  1487. metadata.sessionSelector = selectorDownloadSynchronize;
  1488. metadata.status = k_metadataStatusWaitDownload;
  1489. // Add Metadata for Download
  1490. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1491. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1492. [appDelegate startLoadAutoDownloadUpload];
  1493. }
  1494. } else if (errorCode != 0) {
  1495. [[NCContentPresenter shared] messageNotification:@"_error_" description:errorDecription delay:k_dismissAfterSecond type:messageTypeError errorCode:errorCode];
  1496. } else {
  1497. NSLog(@"[LOG] It has been changed user during networking process, error.");
  1498. }
  1499. }];
  1500. }
  1501. #pragma --------------------------------------------------------------------------------------------
  1502. #pragma mark ==== Menu LOGO ====
  1503. #pragma --------------------------------------------------------------------------------------------
  1504. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1505. {
  1506. // Brand
  1507. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1508. return;
  1509. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1510. NSMutableArray *menuArray = [NSMutableArray new];
  1511. for (NSString *account in listAccount) {
  1512. CCMenuItem *item = [[CCMenuItem alloc] init];
  1513. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1514. item.argument = account;
  1515. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1516. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-%@.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url], tableAccount.user];
  1517. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1518. if (avatar) {
  1519. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1520. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1521. CGSize imageSize = avatarImageView.bounds.size;
  1522. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1523. CGContextRef context = UIGraphicsGetCurrentContext();
  1524. [avatarImageView.layer renderInContext:context];
  1525. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1526. UIGraphicsEndImageContext();
  1527. } else {
  1528. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1529. }
  1530. item.image = avatar;
  1531. item.target = self;
  1532. if ([account isEqualToString:appDelegate.activeAccount]) {
  1533. item.action = nil;
  1534. [menuArray insertObject:item atIndex:0];
  1535. } else {
  1536. item.action = @selector(changeDefaultAccount:);
  1537. [menuArray addObject:item];
  1538. }
  1539. }
  1540. // Add + new account
  1541. CCMenuItem *item = [[CCMenuItem alloc] init];
  1542. item.title = NSLocalizedString(@"_add_account_", nil);
  1543. item.argument = @"";
  1544. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"add"] width:50 height:50 color:NCBrandColor.sharedInstance.textView];
  1545. item.target = self;
  1546. item.action = @selector(addNewAccount:);
  1547. [menuArray addObject:item];
  1548. OptionalConfiguration options;
  1549. Color backgroundColor;
  1550. const CGFloat *componentsBackgroundColor = CGColorGetComponents(NCBrandColor.sharedInstance.backgroundForm.CGColor);
  1551. backgroundColor.R = componentsBackgroundColor[0];
  1552. backgroundColor.G = componentsBackgroundColor[1];
  1553. backgroundColor.B = componentsBackgroundColor[2];
  1554. options.arrowSize = 9;
  1555. options.marginXSpacing = 7;
  1556. options.marginYSpacing = 10;
  1557. options.intervalSpacing = 20;
  1558. options.menuCornerRadius = 6.5;
  1559. options.maskToBackground = NO;
  1560. options.shadowOfMenu = YES;
  1561. options.hasSeperatorLine = YES;
  1562. options.seperatorLineHasInsets = YES;
  1563. options.textColor = NCBrandColor.sharedInstance.textView;
  1564. options.menuBackgroundColor = backgroundColor;
  1565. options.separatorColor = NCBrandColor.sharedInstance.separator;
  1566. CGRect rect = self.view.frame;
  1567. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1568. CGFloat safeAreaTop = 0;
  1569. CGFloat offsetY = 35;
  1570. if (@available(iOS 11, *)) {
  1571. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1572. }
  1573. rect.origin.y = locationY + safeAreaTop + offsetY;
  1574. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1575. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1576. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1577. }
  1578. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1579. {
  1580. // LOGOUT
  1581. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1582. if (tableAccount) {
  1583. // LOGIN
  1584. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  1585. // go to home sweet home
  1586. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1587. }
  1588. }
  1589. - (void)addNewAccount:(CCMenuItem *)sender
  1590. {
  1591. [appDelegate openLoginView:self selector:k_intro_login openLoginWeb:false];
  1592. }
  1593. - (void)toggleReMainMenu
  1594. {
  1595. [self toggleMenuWithViewController:self.navigationController];
  1596. }
  1597. - (void)toggleReSelectMenu
  1598. {
  1599. [self toggleSelectMenuWithViewController:self.navigationController];
  1600. }
  1601. #pragma --------------------------------------------------------------------------------------------
  1602. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  1603. #pragma --------------------------------------------------------------------------------------------
  1604. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  1605. {
  1606. if (recognizer.state == UIGestureRecognizerStateBegan) {
  1607. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  1608. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  1609. NSMutableArray *items = [NSMutableArray new];
  1610. if ([self indexPathIsValid:indexPath])
  1611. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1612. else
  1613. self.metadata = nil;
  1614. [self becomeFirstResponder];
  1615. UIMenuController *menuController = [UIMenuController sharedMenuController];
  1616. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)]];
  1617. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)]];
  1618. if ([NCBrandOptions sharedInstance].disable_openin_file == false) {
  1619. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)]];
  1620. }
  1621. if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document]) {
  1622. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_internal_view_", nil) action:@selector(openInternalViewer:)]];
  1623. }
  1624. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)]];
  1625. [items addObject:[[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)]];
  1626. [menuController setMenuItems:items];
  1627. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  1628. [menuController setMenuVisible:YES animated:YES];
  1629. }
  1630. }
  1631. - (BOOL)canBecomeFirstResponder
  1632. {
  1633. return YES;
  1634. }
  1635. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  1636. {
  1637. // For copy file, copy files, Open in ... :
  1638. //
  1639. // NO Directory
  1640. // NO Error Passcode
  1641. // NO In Session mode (download/upload)
  1642. // NO Template
  1643. if (@selector(copyFile:) == action || @selector(openinFile:) == action || @selector(openInternalViewer:) == action) {
  1644. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  1645. else return NO;
  1646. }
  1647. if (@selector(copyFiles:) == action) {
  1648. if (_isSelectedMode) {
  1649. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1650. for (tableMetadata *metadata in selectedMetadatas) {
  1651. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  1652. return YES;
  1653. }
  1654. }
  1655. return NO;
  1656. }
  1657. if (@selector(pasteFile:) == action) {
  1658. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1659. NSArray *items = [pasteboard items];
  1660. if ([items count] == 1) {
  1661. // Value : (NSData) ocId
  1662. NSDictionary *dic = [items objectAtIndex:0];
  1663. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1664. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1665. if (ocId) {
  1666. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1667. if (metadata) {
  1668. return [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView];
  1669. } else {
  1670. return NO;
  1671. }
  1672. }
  1673. }
  1674. return NO;
  1675. }
  1676. if (@selector(pasteFiles:) == action) {
  1677. BOOL isValid = NO;
  1678. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1679. NSArray *items = [pasteboard items];
  1680. if ([items count] <= 1) return NO;
  1681. for (NSDictionary *dic in items) {
  1682. // Value : (NSData) ocId
  1683. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1684. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1685. if (ocId) {
  1686. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1687. if (metadata) {
  1688. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1689. isValid = YES;
  1690. } else {
  1691. isValid = NO;
  1692. break;
  1693. }
  1694. } else {
  1695. isValid = NO;
  1696. break;
  1697. }
  1698. } else {
  1699. isValid = NO;
  1700. break;
  1701. }
  1702. }
  1703. return isValid;
  1704. }
  1705. return NO;
  1706. }
  1707. /************************************ COPY ************************************/
  1708. - (void)copyFile:(id)sender
  1709. {
  1710. // Remove all item
  1711. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1712. pasteboard.items = [[NSArray alloc] init];
  1713. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  1714. [self copyFileToPasteboard:self.metadata];
  1715. } else {
  1716. self.metadata.session = k_download_session;
  1717. self.metadata.sessionError = @"";
  1718. self.metadata.sessionSelector = selectorLoadCopy;
  1719. self.metadata.status = k_metadataStatusWaitDownload;
  1720. // Add Metadata for Download
  1721. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  1722. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  1723. [appDelegate startLoadAutoDownloadUpload];
  1724. }
  1725. }
  1726. - (void)copyFiles:(id)sender
  1727. {
  1728. // Remove all item
  1729. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1730. pasteboard.items = [[NSArray alloc] init];
  1731. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1732. for (tableMetadata *metadata in selectedMetadatas) {
  1733. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1734. [self copyFileToPasteboard:metadata];
  1735. } else {
  1736. metadata.session = k_download_session;
  1737. metadata.sessionError = @"";
  1738. metadata.sessionSelector = selectorLoadCopy;
  1739. metadata.status = k_metadataStatusWaitDownload;
  1740. // Add Metadata for Download
  1741. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1742. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:metadata.ocId action:k_action_MOD];
  1743. [appDelegate startLoadAutoDownloadUpload];
  1744. }
  1745. }
  1746. [self tableViewSelect:false];
  1747. }
  1748. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  1749. {
  1750. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1751. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  1752. // Value : (NSData) ocId
  1753. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.ocId], k_metadataKeyedUnarchiver,nil];
  1754. [items addObject:item];
  1755. [pasteboard setItems:items];
  1756. }
  1757. /************************************ OPEN IN ... ******************************/
  1758. - (void)openinFile:(id)sender
  1759. {
  1760. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorOpenIn];
  1761. }
  1762. /************************************ OPEN INTERNAL VIEWER ... ******************************/
  1763. - (void)openInternalViewer:(id)sender
  1764. {
  1765. [[NCMainCommon sharedInstance] downloadOpenWithMetadata:self.metadata selector:selectorLoadFileInternalView];
  1766. }
  1767. /************************************ PASTE ************************************/
  1768. - (void)pasteFile:(id)sender
  1769. {
  1770. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1771. [self uploadFilePasteArray:[pasteboard items]];
  1772. }
  1773. - (void)pasteFiles:(id)sender
  1774. {
  1775. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1776. [self uploadFilePasteArray:[pasteboard items]];
  1777. }
  1778. - (void)uploadFilePasteArray:(NSArray *)items
  1779. {
  1780. for (NSDictionary *dic in items) {
  1781. // Value : (NSData) ocId
  1782. NSData *dataocId = [dic objectForKey: k_metadataKeyedUnarchiver];
  1783. NSString *ocId = [NSKeyedUnarchiver unarchiveObjectWithData:dataocId];
  1784. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  1785. if (metadata) {
  1786. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1787. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView serverUrl:self.serverUrl account:appDelegate.activeAccount];
  1788. NSString *ocId = [CCUtility createMetadataIDFromAccount:appDelegate.activeAccount serverUrl:self.serverUrl fileNameView:fileName directory:false];
  1789. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName]];
  1790. tableMetadata *metadataForUpload = [tableMetadata new];
  1791. metadataForUpload.account = appDelegate.activeAccount;
  1792. metadataForUpload.date = [NSDate new];
  1793. metadataForUpload.ocId = ocId;
  1794. metadataForUpload.fileName = fileName;
  1795. metadataForUpload.fileNameView = fileName;
  1796. metadataForUpload.serverUrl = self.serverUrl;
  1797. metadataForUpload.session = k_upload_session;
  1798. metadataForUpload.sessionSelector = selectorUploadFile;
  1799. metadataForUpload.size = metadata.size;
  1800. metadataForUpload.status = k_metadataStatusWaitUpload;
  1801. // Add Medtadata for upload
  1802. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1803. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1804. }
  1805. }
  1806. }
  1807. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1808. [appDelegate startLoadAutoDownloadUpload];
  1809. }
  1810. #pragma --------------------------------------------------------------------------------------------
  1811. #pragma mark ===== Lock Passcode =====
  1812. #pragma --------------------------------------------------------------------------------------------
  1813. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  1814. {
  1815. return _failedAttempts;
  1816. }
  1817. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  1818. {
  1819. return _lockUntilDate;
  1820. }
  1821. - (void)passcodeViewCloseButtonPressed:(id)sender
  1822. {
  1823. [self dismissViewControllerAnimated:YES completion:nil];
  1824. }
  1825. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  1826. {
  1827. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  1828. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  1829. _lockUntilDate = nil;
  1830. _failedAttempts = 0;
  1831. aResultHandler(YES);
  1832. } else aResultHandler(NO);
  1833. } else aResultHandler(YES);
  1834. }
  1835. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  1836. {
  1837. [aViewController dismissViewControllerAnimated:YES completion:nil];
  1838. switch (aViewController.type) {
  1839. case BKPasscodeViewControllerCheckPasscodeType: {
  1840. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  1841. // possiamo procedere alla prossima directory
  1842. [self performSegueDirectoryWithControlPasscode:false metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  1843. // avviamo la sessione Passcode Lock con now
  1844. appDelegate.sessionePasscodeLock = [NSDate date];
  1845. }
  1846. // disattivazione lock cartella
  1847. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  1848. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  1849. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO account:appDelegate.activeAccount]) {
  1850. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1851. }
  1852. [self tableViewReloadData];
  1853. }
  1854. }
  1855. break;
  1856. default:
  1857. break;
  1858. }
  1859. }
  1860. - (void)comandoLockPassword
  1861. {
  1862. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:self.metadata.fileName];
  1863. // se non è abilitato il Lock Passcode esci
  1864. if ([[CCUtility getBlockCode] length] == 0) {
  1865. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1866. UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_go_to_app_settings_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1867. [self.tabBarController setSelectedIndex:4];
  1868. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1869. NSIndexPath *selectedIndex = [NSIndexPath indexPathForRow:0 inSection:1];
  1870. [appDelegate.activeMore.tableView selectRowAtIndexPath:selectedIndex animated:true scrollPosition: UITableViewScrollPositionNone];
  1871. [appDelegate.activeMore tableView:appDelegate.activeMore.tableView didSelectRowAtIndexPath:selectedIndex];
  1872. });
  1873. }];
  1874. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1875. [alertController addAction:goToSettingsAction];
  1876. [alertController addAction:okAction];
  1877. [self presentViewController:alertController animated:YES completion:nil];
  1878. return;
  1879. }
  1880. // se è richiesta la disattivazione si chiede la password
  1881. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  1882. if (directory.lock) {
  1883. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  1884. viewController.delegate = self;
  1885. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  1886. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  1887. viewController.inputViewTitlePassword = YES;
  1888. if ([CCUtility getSimplyBlockCode]) {
  1889. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  1890. viewController.passcodeInputView.maximumLength = 6;
  1891. } else {
  1892. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  1893. viewController.passcodeInputView.maximumLength = 64;
  1894. }
  1895. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  1896. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  1897. viewController.touchIDManager = touchIDManager;
  1898. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  1899. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  1900. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  1901. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  1902. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  1903. [self presentViewController:navigationController animated:YES completion:nil];
  1904. return;
  1905. }
  1906. // ---------------- ACTIVATE PASSWORD
  1907. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES account:appDelegate.activeAccount]) {
  1908. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:self.metadata.ocId];
  1909. if ([self indexPathIsValid:indexPath])
  1910. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  1911. } else {
  1912. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_error_operation_canc_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1913. }
  1914. }
  1915. #pragma mark -
  1916. #pragma --------------------------------------------------------------------------------------------
  1917. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  1918. #pragma --------------------------------------------------------------------------------------------
  1919. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  1920. {
  1921. if (metadata == nil || _metadataFolder == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || metadata.status != k_metadataStatusNormal || [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])
  1922. return NO;
  1923. // E2EE
  1924. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  1925. return NO;
  1926. return YES;
  1927. }
  1928. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  1929. {
  1930. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1931. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1932. return [self canOpenMenuAction:metadata];
  1933. }
  1934. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  1935. {
  1936. }
  1937. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  1938. {
  1939. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  1940. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1941. if (direction == MGSwipeDirectionRightToLeft) {
  1942. [self actionDelete:indexPath];
  1943. }
  1944. if (direction == MGSwipeDirectionLeftToRight) {
  1945. if (self.metadata.favorite)
  1946. [self settingFavorite:self.metadata favorite:NO];
  1947. else
  1948. [self settingFavorite:self.metadata favorite:YES];
  1949. }
  1950. return YES;
  1951. }
  1952. - (void)actionDelete:(NSIndexPath *)indexPath
  1953. {
  1954. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1955. // Directory locked ?
  1956. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:self.metadata.serverUrl addFileName:metadata.fileName];
  1957. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  1958. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1959. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  1960. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_folder_blocked_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1961. return;
  1962. }
  1963. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1964. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1965. [self performSelector:@selector(deleteFile) withObject:nil];
  1966. }]];
  1967. if (localFile) {
  1968. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1969. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  1970. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  1971. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1972. }]];
  1973. }
  1974. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1975. }]];
  1976. alertController.popoverPresentationController.sourceView = self.tableView;
  1977. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1978. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1979. [alertController.view layoutIfNeeded];
  1980. [self presentViewController:alertController animated:YES completion:nil];
  1981. }
  1982. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  1983. {
  1984. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  1985. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  1986. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1987. [self toggleMoreMenuWithViewController:self.tabBarController indexPath:indexPath metadata:self.metadata metadataFolder:_metadataFolder];
  1988. }
  1989. #pragma --------------------------------------------------------------------------------------------
  1990. #pragma mark - ==== Datasource ====
  1991. #pragma --------------------------------------------------------------------------------------------
  1992. - (void)clearDateReadDataSource:(NSNotification *)notification
  1993. {
  1994. _dateReadDataSource = Nil;
  1995. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:nil action:k_action_NULL];
  1996. }
  1997. - (void)reloadDatasource:(NSString *)serverUrl ocId:(NSString *)ocId action:(NSInteger)action
  1998. {
  1999. // test
  2000. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2001. return;
  2002. // Search Mode
  2003. if (self.searchController.isActive) {
  2004. // Create metadatas
  2005. NSMutableArray *metadatas = [NSMutableArray new];
  2006. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  2007. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", resultMetadata.ocId]];
  2008. if (metadata) {
  2009. [metadatas addObject:metadata];
  2010. }
  2011. }
  2012. // [CCUtility getGroupBySettings]
  2013. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:nil filterocId:appDelegate.filterocId filterTypeFileImage:NO filterTypeFileVideo:NO sorted:@"fileName" ascending:NO activeAccount:appDelegate.activeAccount];
  2014. [self tableViewReloadData];
  2015. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2016. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2017. _noFilesSearchDescription = @"";
  2018. }
  2019. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2020. _noFilesSearchTitle = @"";
  2021. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2022. }
  2023. [self.tableView reloadEmptyDataSet];
  2024. return;
  2025. }
  2026. // Se non siamo nella dir appropriata esci
  2027. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  2028. return;
  2029. }
  2030. // Controllo data lettura Data Source
  2031. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2032. if (tableDirectory == nil) {
  2033. return;
  2034. }
  2035. // Get MetadataFolder
  2036. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2037. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, k_serverUrl_root]];
  2038. else
  2039. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tableDirectory.ocId]];
  2040. // Remove optimization for encrypted directory
  2041. if (_metadataFolder.e2eEncrypted)
  2042. _dateReadDataSource = nil;
  2043. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2044. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2045. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2046. _dateReadDataSource = [NSDate date];
  2047. // Data Source
  2048. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2049. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  2050. dispatch_async(dispatch_get_main_queue(), ^{
  2051. sectionDataSource = sectionDataSourceTemp;
  2052. [self tableViewReloadData];
  2053. });
  2054. });
  2055. } else {
  2056. [self tableViewReloadData];
  2057. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2058. }
  2059. // BLINK
  2060. if (self.blinkFileNamePath != nil) {
  2061. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2062. for (NSString *key in sectionDataSource.allRecordsDataSource) {
  2063. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:key];
  2064. NSString *metadataFileNamePath = [NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName];
  2065. if ([metadataFileNamePath isEqualToString:self.blinkFileNamePath]) {
  2066. for (NSString *key in sectionDataSource.ocIdIndexPath) {
  2067. if ([key isEqualToString:metadata.ocId]) {
  2068. NSIndexPath *indexPath = [sectionDataSource.ocIdIndexPath objectForKey:key];
  2069. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
  2070. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  2071. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  2072. if (cell) {
  2073. self.blinkFileNamePath = nil;
  2074. [[NCUtility sharedInstance] blinkWithCell:cell];
  2075. }
  2076. });
  2077. }
  2078. }
  2079. }
  2080. }
  2081. });
  2082. }
  2083. }
  2084. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  2085. {
  2086. // test
  2087. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  2088. return nil;
  2089. }
  2090. // get auto upload folder
  2091. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2092. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2093. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2094. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND status != %i", appDelegate.activeAccount, serverUrl, k_metadataStatusHide] sorted:nil ascending:NO];
  2095. // [CCUtility getGroupBySettings]
  2096. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:nil filterocId:appDelegate.filterocId filterTypeFileImage:NO filterTypeFileVideo:NO sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings] activeAccount:appDelegate.activeAccount];
  2097. if (withReloadData) {
  2098. sectionDataSource = sectionDataSourceTemp;
  2099. [self tableViewReloadData];
  2100. }
  2101. return sectionDataSourceTemp;
  2102. }
  2103. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2104. {
  2105. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2106. if (selectedRows.count > 0) {
  2107. for (NSIndexPath *selectionIndex in selectedRows) {
  2108. NSString *ocId = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2109. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2110. [metadatas addObject:metadata];
  2111. }
  2112. }
  2113. return metadatas;
  2114. }
  2115. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2116. {
  2117. NSInteger totSections =[sectionDataSource.sections count] ;
  2118. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2119. return nil;
  2120. }
  2121. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2122. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2123. }
  2124. #pragma --------------------------------------------------------------------------------------------
  2125. #pragma mark - ==== Table ====
  2126. #pragma --------------------------------------------------------------------------------------------
  2127. - (void)tableViewToggle
  2128. {
  2129. [self tableViewSelect:!_isSelectedMode];
  2130. }
  2131. - (void)tableViewSelect:(BOOL)toggle
  2132. {
  2133. _isSelectedMode = toggle;
  2134. // chiudiamo eventuali swipe aperti
  2135. if (_isSelectedMode)
  2136. [self.tableView setEditing:NO animated:NO];
  2137. [self.tableView setAllowsMultipleSelectionDuringEditing:_isSelectedMode];
  2138. [self.tableView setEditing:_isSelectedMode animated:YES];
  2139. if (_isSelectedMode)
  2140. [self setUINavigationBarSelected];
  2141. else
  2142. [self setUINavigationBarDefault];
  2143. [_selectedocIdsMetadatas removeAllObjects];
  2144. [self setTitle];
  2145. }
  2146. - (void)tableViewReloadData
  2147. {
  2148. // store selected cells before relod
  2149. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2150. // reload table view
  2151. [self.tableView reloadData];
  2152. // selected cells stored
  2153. for (NSIndexPath *path in indexPaths)
  2154. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2155. [self setTableViewHeader];
  2156. [self setTableViewFooter];
  2157. if (self.tableView.editing)
  2158. [self setTitle];
  2159. [self.tableView reloadEmptyDataSet];
  2160. }
  2161. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2162. {
  2163. if (tableView.editing == 1) {
  2164. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2165. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2166. return NO;
  2167. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2168. return NO;
  2169. else
  2170. return YES;
  2171. } else {
  2172. [_selectedocIdsMetadatas removeAllObjects];
  2173. }
  2174. return YES;
  2175. }
  2176. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2177. {
  2178. return 60;
  2179. }
  2180. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2181. {
  2182. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2183. }
  2184. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2185. {
  2186. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2187. }
  2188. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2189. {
  2190. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2191. NSString *sectionTitle = [sections objectAtIndex:section];
  2192. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2193. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2194. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2195. return 20.f;
  2196. }
  2197. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2198. {
  2199. float shift;
  2200. UIVisualEffectView *visualEffectView;
  2201. NSString *titleSection;
  2202. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2203. return nil;
  2204. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2205. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2206. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2207. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2208. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2209. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2210. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2211. else titleSection = NSLocalizedString(titleSection,nil);
  2212. // Format title
  2213. UIVisualEffect *blurEffect;
  2214. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2215. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2216. visualEffectView.backgroundColor = [NCBrandColor.sharedInstance.brand colorWithAlphaComponent:0.2];
  2217. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  2218. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2219. shift = - 35;
  2220. else
  2221. shift = - 20;
  2222. } else shift = - 10;
  2223. // Title
  2224. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2225. titleLabel.backgroundColor = [UIColor clearColor];
  2226. titleLabel.textColor = NCBrandColor.sharedInstance.textView;
  2227. titleLabel.font = [UIFont systemFontOfSize:12];
  2228. titleLabel.textAlignment = NSTextAlignmentLeft;
  2229. titleLabel.text = titleSection;
  2230. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2231. [visualEffectView.contentView addSubview:titleLabel];
  2232. // Elements
  2233. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2234. elementLabel.backgroundColor = [UIColor clearColor];
  2235. elementLabel.textColor = NCBrandColor.sharedInstance.textView;
  2236. elementLabel.font = [UIFont systemFontOfSize:12];
  2237. elementLabel.textAlignment = NSTextAlignmentRight;
  2238. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2239. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2240. NSUInteger rowsCount = [metadatas count];
  2241. if (rowsCount == 0) return nil;
  2242. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2243. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2244. [visualEffectView.contentView addSubview:elementLabel];
  2245. return visualEffectView;
  2246. }
  2247. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2248. {
  2249. return [sectionDataSource.sections indexOfObject:title];
  2250. }
  2251. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2252. {
  2253. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  2254. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2255. else
  2256. return nil;
  2257. }
  2258. /*
  2259. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2260. {
  2261. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  2262. }
  2263. }
  2264. */
  2265. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2266. {
  2267. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2268. tableShare *shareCell;
  2269. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata] || (_metadataFolder != nil && [[NCManageDatabase sharedInstance] isTableInvalidated:_metadataFolder])) {
  2270. return [CCCellMain new];
  2271. }
  2272. for (tableShare *share in appDelegate.shares) {
  2273. if ([share.serverUrl isEqualToString:metadata.serverUrl] && [share.fileName isEqualToString:metadata.fileName]) {
  2274. shareCell = share;
  2275. break;
  2276. }
  2277. }
  2278. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory tableShare:shareCell];
  2279. // NORMAL - > MAIN
  2280. if ([cell isKindOfClass:[CCCellMain class]]) {
  2281. // Comment tap
  2282. if (metadata.commentsUnread) {
  2283. UITapGestureRecognizer *tapComment = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionComment:)];
  2284. [tapComment setNumberOfTapsRequired:1];
  2285. ((CCCellMain *)cell).comment.userInteractionEnabled = YES;
  2286. [((CCCellMain *)cell).comment addGestureRecognizer:tapComment];
  2287. }
  2288. // Share add Tap
  2289. UITapGestureRecognizer *tapShare = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  2290. [tapShare setNumberOfTapsRequired:1];
  2291. ((CCCellMain *)cell).viewShared.userInteractionEnabled = YES;
  2292. [((CCCellMain *)cell).viewShared addGestureRecognizer:tapShare];
  2293. // More
  2294. if ([self canOpenMenuAction:metadata]) {
  2295. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  2296. [tapMore setNumberOfTapsRequired:1];
  2297. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  2298. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  2299. }
  2300. // MGSwipeButton
  2301. ((CCCellMain *)cell).delegate = self;
  2302. // LEFT
  2303. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellFavouriteImage backgroundColor:NCBrandColor.sharedInstance.yellowFavorite padding:25]];
  2304. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  2305. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  2306. //centerIconOverText
  2307. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  2308. [favoriteButton centerIconOverText];
  2309. // RIGHT
  2310. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:self.cellTrashImage backgroundColor:[UIColor redColor] padding:25]];
  2311. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  2312. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  2313. //centerIconOverText
  2314. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  2315. [deleteButton centerIconOverText];
  2316. }
  2317. // TRANSFER
  2318. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  2319. // gesture Transfer
  2320. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  2321. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  2322. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  2323. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  2324. }
  2325. return cell;
  2326. }
  2327. - (void)setTableViewHeader
  2328. {
  2329. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:appDelegate.activeAccount];
  2330. if (capabilities.versionMajor < k_nextcloud_version_18_0 || self.richWorkspaceText.length == 0 || self.searchController.isActive) {
  2331. [self.tableView.tableHeaderView setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightSearchBar)];
  2332. } else {
  2333. [self.viewRichWorkspace setFrame:CGRectMake(self.tableView.tableHeaderView.frame.origin.x, self.tableView.tableHeaderView.frame.origin.y, self.tableView.frame.size.width, heightRichWorkspace)];
  2334. }
  2335. [self.viewRichWorkspace loadWithRichWorkspaceText:self.richWorkspaceText];
  2336. self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.tableView.frame.size.width, heightSearchBar);
  2337. [self.tableView reloadData];
  2338. }
  2339. - (void)setTableViewFooter
  2340. {
  2341. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2342. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2343. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  2344. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  2345. UIFont *appFont = [UIFont systemFontOfSize:12];
  2346. footerLabel.font = appFont;
  2347. footerLabel.textColor = [UIColor grayColor];
  2348. footerLabel.backgroundColor = [UIColor clearColor];
  2349. footerLabel.textAlignment = NSTextAlignmentCenter;
  2350. NSString *folders;
  2351. NSString *files;
  2352. NSString *footerText;
  2353. if (sectionDataSource.directories > 1) {
  2354. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  2355. } else if (sectionDataSource.directories == 1){
  2356. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  2357. } else {
  2358. folders = @"";
  2359. }
  2360. if (sectionDataSource.files > 1) {
  2361. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2362. } else if (sectionDataSource.files == 1){
  2363. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  2364. } else {
  2365. files = @"";
  2366. }
  2367. if ([folders isEqualToString:@""]) {
  2368. footerText = files;
  2369. } else if ([files isEqualToString:@""]) {
  2370. footerText = folders;
  2371. } else {
  2372. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  2373. }
  2374. footerLabel.text = footerText;
  2375. [footerView addSubview:footerLabel];
  2376. [self.tableView setTableFooterView:footerView];
  2377. }
  2378. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  2379. {
  2380. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  2381. // settiamo il record file.
  2382. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2383. if (!self.metadata)
  2384. return;
  2385. // se non può essere selezionata deseleziona
  2386. if ([cell isEditing] == NO)
  2387. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  2388. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  2389. if (self.tableView.editing) {
  2390. [_selectedocIdsMetadatas setObject:self.metadata forKey:self.metadata.ocId];
  2391. [self setTitle];
  2392. return;
  2393. }
  2394. // se è in corso una sessione
  2395. if (self.metadata.status != k_metadataStatusNormal)
  2396. return;
  2397. // file
  2398. if (self.metadata.directory == NO) {
  2399. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  2400. if ([CCUtility fileProviderStorageExists:self.metadata.ocId fileNameView:self.metadata.fileNameView]) {
  2401. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName ocId:self.metadata.ocId serverUrl:self.metadata.serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  2402. } else {
  2403. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2404. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2405. } else {
  2406. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) && _metadataFolder.e2eEncrypted == NO) {
  2407. [self shouldPerformSegue:self.metadata selector:@""];
  2408. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isDirectEditing:self.metadata] != nil) {
  2409. if (appDelegate.reachability.isReachable) {
  2410. [self shouldPerformSegue:self.metadata selector:@""];
  2411. } else {
  2412. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2413. }
  2414. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCUtility sharedInstance] isRichDocument:self.metadata]) {
  2415. if (appDelegate.reachability.isReachable) {
  2416. [self shouldPerformSegue:self.metadata selector:@""];
  2417. } else {
  2418. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_go_online_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2419. }
  2420. } else {
  2421. self.metadata.session = k_download_session;
  2422. self.metadata.sessionError = @"";
  2423. self.metadata.sessionSelector = selectorLoadFileView;
  2424. self.metadata.status = k_metadataStatusWaitDownload;
  2425. // Add Metadata for Download
  2426. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2427. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl ocId:self.metadata.ocId action:k_action_MOD];
  2428. [appDelegate startLoadAutoDownloadUpload];
  2429. }
  2430. }
  2431. }
  2432. }
  2433. if (self.metadata.directory) {
  2434. [self performSegueDirectoryWithControlPasscode:true metadata:self.metadata blinkFileNamePath:self.blinkFileNamePath];
  2435. }
  2436. }
  2437. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  2438. {
  2439. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2440. [_selectedocIdsMetadatas removeObjectForKey:metadata.ocId];
  2441. [self setTitle];
  2442. }
  2443. - (void)didSelectAll
  2444. {
  2445. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  2446. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  2447. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  2448. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2449. [_selectedocIdsMetadatas setObject:metadata forKey:metadata.ocId];
  2450. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  2451. }
  2452. }
  2453. [self setTitle];
  2454. }
  2455. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  2456. {
  2457. if (!indexPath)
  2458. return NO;
  2459. NSInteger section = indexPath.section;
  2460. NSInteger row = indexPath.row;
  2461. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  2462. if (section > lastSectionIndex || lastSectionIndex < 0)
  2463. return NO;
  2464. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  2465. if (rowCount < 0)
  2466. return NO;
  2467. return row <= rowCount;
  2468. }
  2469. #pragma --------------------------------------------------------------------------------------------
  2470. #pragma mark ===== Navigation ====
  2471. #pragma --------------------------------------------------------------------------------------------
  2472. - (void)shouldPerformSegue:(tableMetadata *)metadata selector:(NSString *)selector
  2473. {
  2474. // if background return
  2475. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  2476. if (self.view.window == NO)
  2477. return;
  2478. // Collapsed ma siamo già in detail esci
  2479. if (self.splitViewController.isCollapsed) {
  2480. if (appDelegate.activeDetail.isViewLoaded && appDelegate.activeDetail.view.window) return;
  2481. }
  2482. // Metadata for push detail
  2483. self.metadataForPushDetail = metadata;
  2484. self.selectorForPushDetail = selector;
  2485. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  2486. }
  2487. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  2488. {
  2489. tableMetadata *metadata;
  2490. NSMutableArray *photoDataSource = [NSMutableArray new];
  2491. UINavigationController *navigationController = segue.destinationViewController;
  2492. NCDetailViewController *detailViewController = (NCDetailViewController *)navigationController.topViewController;
  2493. if ([sender isKindOfClass:[tableMetadata class]]) {
  2494. metadata = sender;
  2495. [photoDataSource addObject:sender];
  2496. } else {
  2497. metadata = self.metadataForPushDetail;
  2498. for (NSString *ocId in sectionDataSource.allOcId) {
  2499. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:ocId];
  2500. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  2501. [photoDataSource addObject:metadata];
  2502. }
  2503. }
  2504. detailViewController.metadata = metadata;
  2505. detailViewController.selector = self.selectorForPushDetail;
  2506. [detailViewController setTitle:metadata.fileNameView];
  2507. }
  2508. // can i go to next viewcontroller
  2509. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode metadata:(tableMetadata *)metadata blinkFileNamePath:(NSString *)blinkFileNamePath
  2510. {
  2511. NSString *nomeDir;
  2512. if (self.tableView.editing == NO) {
  2513. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:metadata.fileName];
  2514. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadata.account, lockServerUrl]];
  2515. // 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
  2516. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  2517. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2518. viewController.delegate = self;
  2519. viewController.fromType = CCBKPasscodeFromLockDirectory;
  2520. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2521. viewController.inputViewTitlePassword = YES;
  2522. if ([CCUtility getSimplyBlockCode]) {
  2523. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2524. viewController.passcodeInputView.maximumLength = 6;
  2525. } else {
  2526. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2527. viewController.passcodeInputView.maximumLength = 64;
  2528. }
  2529. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2530. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2531. viewController.touchIDManager = touchIDManager;
  2532. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  2533. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2534. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2535. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2536. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  2537. [self presentViewController:navigationController animated:YES completion:nil];
  2538. return;
  2539. }
  2540. // E2EE Check enable
  2541. if (metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  2542. [[NCContentPresenter shared] messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  2543. return;
  2544. }
  2545. nomeDir = metadata.fileName;
  2546. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:metadata.serverUrl addFileName:nomeDir];
  2547. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  2548. if (!viewController) {
  2549. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  2550. viewController.serverUrl = serverUrlPush;
  2551. viewController.titleMain = metadata.fileName;
  2552. viewController.blinkFileNamePath = blinkFileNamePath;
  2553. // save self
  2554. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  2555. [self.navigationController pushViewController:viewController animated:YES];
  2556. } else {
  2557. if (viewController.isViewLoaded) {
  2558. viewController.titleMain = metadata.fileName;
  2559. viewController.blinkFileNamePath = blinkFileNamePath;
  2560. // Fix : Application tried to present modally an active controller
  2561. if ([self.navigationController isBeingPresented]) {
  2562. // being presented
  2563. } else if ([self.navigationController isMovingToParentViewController]) {
  2564. // being pushed
  2565. } else {
  2566. [self.navigationController pushViewController:viewController animated:YES];
  2567. }
  2568. }
  2569. }
  2570. }
  2571. }
  2572. @end