CCMain.m 210 KB

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