CCMain.m 206 KB

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