CCMain.m 208 KB

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