CCMain.m 235 KB

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