CCMain.m 157 KB

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