CCMain.m 210 KB

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