CCMain.m 206 KB

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