CCMain.m 225 KB

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