CCMain.m 257 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 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 "CCPhotosCameraUpload.h"
  26. #import "CCOfflineFileFolder.h"
  27. #import <OCCommunicationLib/OCNotifications.h>
  28. #import <OCCommunicationLib/OCNotificationsAction.h>
  29. #import <OCCommunicationLib/OCFrameworkConstants.h>
  30. #import "Nextcloud-Swift.h"
  31. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  32. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  33. #define alertCreateFolder 1
  34. #define alertCreateFolderCrypto 2
  35. #define alertRename 3
  36. #define alertOfflineFolder 4
  37. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate>
  38. {
  39. CCMetadata *_metadataSegue;
  40. CCMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isOfflineServerUrl;
  44. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  45. BOOL _isSelectedMode;
  46. NSMutableArray *_selectedMetadatas;
  47. NSMutableArray *_queueSelector;
  48. NSUInteger _numSelectedMetadatas;
  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. CCSectionDataSource *_sectionDataSource;
  63. NSDate *_dateReadDataSource;
  64. // Search
  65. BOOL _isSearchMode;
  66. BOOL _reloadForcedFoderWhenSearchModeOff;
  67. NSString *_searchFileName;
  68. NSArray *_searchResultMetadatas;
  69. }
  70. @end
  71. @implementation CCMain
  72. #pragma --------------------------------------------------------------------------------------------
  73. #pragma mark ===== Init =====
  74. #pragma --------------------------------------------------------------------------------------------
  75. - (id)initWithCoder:(NSCoder *)aDecoder
  76. {
  77. if (self = [super initWithCoder:aDecoder]) {
  78. _directoryOrder = [CCUtility getOrderSettings];
  79. _directoryGroupBy = [CCUtility getGroupBySettings];
  80. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitleNOAnimation) name:@"setTitleCCMainNOAnimation" object:nil];
  83. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitleYESAnimation) name:@"setTitleCCMainYESAnimation" object:nil];
  84. }
  85. return self;
  86. }
  87. #pragma --------------------------------------------------------------------------------------------
  88. #pragma mark ===== View =====
  89. #pragma --------------------------------------------------------------------------------------------
  90. - (void)viewDidLoad
  91. {
  92. [super viewDidLoad];
  93. // init object
  94. _metadata = [CCMetadata new];
  95. _metadataSegue = [CCMetadata new];
  96. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  97. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  98. _selectedMetadatas = [NSMutableArray new];
  99. _queueSelector = [NSMutableArray new];
  100. _isViewDidLoad = YES;
  101. _fatherPermission = @"";
  102. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  103. _searchResultMetadatas = [NSArray new];
  104. _searchFileName = @"";
  105. // delegate
  106. self.tableView.delegate = self;
  107. self.tableView.tableFooterView = [UIView new];
  108. self.tableView.separatorColor = COLOR_SEPARATOR_TABLE;
  109. self.searchController.delegate = self;
  110. self.searchController.searchBar.delegate = self;
  111. [[CCNetworking sharedNetworking] settingDelegate:self];
  112. // Custom Cell
  113. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  114. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  115. // long press recognizer TableView
  116. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  117. [self.tableView addGestureRecognizer:longPressRecognizer];
  118. // Pull-to-Refresh
  119. [self createRefreshControl];
  120. // Register for 3D Touch Previewing if available
  121. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  122. {
  123. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  124. }
  125. // Back Button
  126. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  127. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController] style:UIBarButtonItemStylePlain target:nil action:nil];
  128. // reMenu Background
  129. _reMenuBackgroundView = [[UIView alloc] init];
  130. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  131. // if this is not Main (the Main uses inizializeMain)
  132. if (_isRoot == NO && app.activeAccount) {
  133. // Settings this folder & delegate & Loading datasource
  134. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  135. // Load Datasource
  136. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  137. // Read Folder
  138. [self readFolderWithForced:NO];
  139. }
  140. // Title
  141. [self setTitleNOAnimation];
  142. // List Transfers
  143. app.controlCenter = (CCControlCenter *)self.navigationController;
  144. // Search
  145. self.definesPresentationContext = YES;
  146. self.searchController.searchResultsUpdater = self;
  147. self.searchController.dimsBackgroundDuringPresentation = NO;
  148. self.tableView.tableHeaderView = self.searchController.searchBar;
  149. self.searchController.searchBar.barTintColor = COLOR_SEPARATOR_TABLE;
  150. [self.searchController.searchBar sizeToFit];
  151. if (_isRoot) self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  152. else self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  153. //self.searchController.searchBar.scopeButtonTitles = @[NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil)];
  154. }
  155. // Apparirà
  156. - (void)viewWillAppear:(BOOL)animated
  157. {
  158. [super viewWillAppear:animated];
  159. // Settings this folder & delegate & Loading datasource
  160. if (app.activeAccount) {
  161. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  162. }
  163. [[CCNetworking sharedNetworking] settingDelegate:self];
  164. // Color
  165. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  166. [CCAspect aspectTabBar:self.tabBarController.tabBar hidden:NO];
  167. // Menu e Bar
  168. [self createReMainMenu];
  169. [self createReSelectMenu];
  170. if (_isSelectedMode)
  171. [self setUINavigationBarSelected];
  172. else [self setUINavigationBarDefault];
  173. // Plus Button
  174. [app plusButtonVisibile:true];
  175. }
  176. // E' arrivato
  177. - (void)viewDidAppear:(BOOL)animated
  178. {
  179. [super viewDidAppear:animated];
  180. // Active Main
  181. app.activeMain = self;
  182. // Test viewDidLoad
  183. if (_isViewDidLoad) {
  184. _isViewDidLoad = NO;
  185. } else {
  186. if (app.activeAccount) {
  187. // Load Datasource
  188. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  189. // Read Folder
  190. [self readFolderWithForced:NO];
  191. }
  192. }
  193. // Title
  194. [self setTitle];
  195. // cancell Progress
  196. [self.navigationController cancelCCProgress];
  197. }
  198. - (void)viewWillDisappear:(BOOL)animated
  199. {
  200. [super viewWillDisappear:animated];
  201. // Close MainMenu & SelectMenu
  202. if (app.reMainMenu.isOpen || app.reSelectMenu.isOpen) {
  203. [app.reMainMenu close];
  204. [app.reSelectMenu close];
  205. }
  206. // Close Menu change user
  207. [CCMenu dismissMenu];
  208. }
  209. - (void)didReceiveMemoryWarning
  210. {
  211. [super didReceiveMemoryWarning];
  212. // Dispose of any resources that can be recreated.
  213. }
  214. - (BOOL)prefersStatusBarHidden
  215. {
  216. return NO;
  217. }
  218. // detect scroll for remove keyboard in search mode
  219. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  220. {
  221. if (_isSearchMode && scrollView == self.tableView) {
  222. [self.searchController.searchBar endEditing:YES];
  223. }
  224. }
  225. #pragma --------------------------------------------------------------------------------------------
  226. #pragma mark ===== Initizlize Mail =====
  227. #pragma --------------------------------------------------------------------------------------------
  228. - (void)initializeMain:(NSNotification *)notification
  229. {
  230. _directoryGroupBy = nil;
  231. _directoryOrder = nil;
  232. _dateReadDataSource = nil;
  233. // test
  234. if ([app.activeAccount length] == 0 || [app.activeUrl length] == 0)
  235. return;
  236. if ([app.listMainVC count] == 0 || _isRoot) {
  237. // This is Root
  238. _isRoot = YES;
  239. // Crypto Mode
  240. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  241. app.isCryptoCloudMode = NO;
  242. } else {
  243. app.isCryptoCloudMode = YES;
  244. }
  245. // go Home
  246. [self.navigationController popToRootViewControllerAnimated:NO];
  247. // Remove search mode
  248. [self cancelSearchBar];
  249. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  250. _isFolderEncrypted = NO;
  251. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  252. // add list
  253. [app.listMainVC setObject:self forKey:_serverUrl];
  254. // setting Networking
  255. [[CCNetworking sharedNetworking] settingDelegate:self];
  256. [[CCNetworking sharedNetworking] settingAccount];
  257. // populate shared Link & User variable
  258. [CCCoreData populateSharesVariableFromDBActiveAccount:app.activeAccount sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup];
  259. // Load Datasource
  260. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  261. // Load Folder
  262. [self readFolderWithForced:NO];
  263. // Load photo datasorce
  264. if (app.activeAccount && app.activeUrl && app.activePhotosCameraUpload)
  265. [app.activePhotosCameraUpload reloadDatasourceForced];
  266. // remove all of detail
  267. if (app.activeDetail)
  268. [app.activeDetail removeAllView];
  269. // remove all Notification Messages
  270. [app.listOfNotifications removeAllObjects];
  271. // home main
  272. app.homeMain = self;
  273. // Initializations
  274. [app applicationInitialized];
  275. } else {
  276. // reload datasource
  277. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  278. }
  279. }
  280. #pragma --------------------------------------------------------------------------------------------
  281. #pragma mark ===== AlertView =====
  282. #pragma --------------------------------------------------------------------------------------------
  283. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  284. {
  285. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  286. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  287. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  288. if (alertView.tag == alertRename && buttonIndex == 1) {
  289. if ([_metadata.model isEqualToString:@"note"]) {
  290. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  291. } else {
  292. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  293. }
  294. }
  295. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  296. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  297. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  298. [[CCOfflineFileFolder sharedOfflineFileFolder] addOfflineFolder:dir];
  299. [self performSelector:@selector(reloadDatasource) withObject:nil];
  300. }
  301. }
  302. // accept only number char > 0
  303. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  304. {
  305. /* Retrieve a text field at an index -
  306. raises NSRangeException when textFieldIndex is out-of-bounds.
  307. The field at index 0 will be the first text field
  308. (the single field or the login field),
  309. The field at index 1 will be the password field. */
  310. /*
  311. 1> Get the Text Field in alertview
  312. 2> Get the text of that Text Field
  313. 3> Verify that text length
  314. 4> return YES or NO Based on the length
  315. */
  316. if (alertView.tag == alertOfflineFolder) return YES;
  317. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  318. }
  319. #pragma --------------------------------------------------------------------------------------------
  320. #pragma mark ===== Graphic Window =====
  321. #pragma --------------------------------------------------------------------------------------------
  322. - (void)createRefreshControl
  323. {
  324. _refreshControl = [UIRefreshControl new];
  325. _refreshControl.tintColor = COLOR_BRAND;
  326. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  327. [self setRefreshControl:_refreshControl];
  328. }
  329. - (void)deleteRefreshControl
  330. {
  331. [_refreshControl endRefreshing];
  332. self.refreshControl = nil;
  333. }
  334. - (void)refreshControlTarget
  335. {
  336. [self readFolderWithForced:YES];
  337. // Actuate `Peek` feedback (weak boom)
  338. AudioServicesPlaySystemSound(1519);
  339. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  340. }
  341. - (void)setTitleNOAnimation
  342. {
  343. app.isTitleBrandAnimated = NO;
  344. [self setTitle];
  345. }
  346. - (void)setTitleYESAnimation
  347. {
  348. app.isTitleBrandAnimated = YES;
  349. [self setTitle];
  350. }
  351. - (void)setTitle
  352. {
  353. // PopGesture in progress [swipe gesture to switch between views]
  354. if (app.controlCenter.isPopGesture)
  355. return;
  356. // Color text self.navigationItem.title
  357. if ([app.reachability isReachable] == NO)
  358. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : COLOR_NO_CONNECTION}];
  359. else if (_isFolderEncrypted)
  360. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : COLOR_ENCRYPTED}];
  361. else
  362. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : COLOR_GRAY}];
  363. if (_isSelectedMode) {
  364. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  365. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  366. self.navigationItem.titleView = nil;
  367. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  368. } else {
  369. // we are in home : LOGO BRAND
  370. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  371. self.navigationItem.title = nil;
  372. if (app.isTitleBrandAnimated) {
  373. NSArray *animationArray = [NSArray arrayWithObjects:[UIImage imageNamed:image_brandNavigationController1],[UIImage imageNamed:image_brandNavigationController2],[UIImage imageNamed:image_brandNavigationController3],[UIImage imageNamed:image_brandNavigationController2],nil];
  374. _ImageTitleHomeCryptoCloud.animationImages = animationArray;
  375. _ImageTitleHomeCryptoCloud.animationDuration = 0.9;
  376. _ImageTitleHomeCryptoCloud.animationRepeatCount = -1;
  377. [_ImageTitleHomeCryptoCloud startAnimating];
  378. } else {
  379. if ([app.reachability isReachable] == NO) _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationControllerOffline]];
  380. else _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController]];
  381. }
  382. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  383. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuChangeUser)];
  384. [singleTap setNumberOfTapsRequired:1];
  385. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  386. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  387. } else {
  388. BOOL isOfflineDirectory = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  389. if (isOfflineDirectory) {
  390. self.navigationItem.titleView = [CCGraphics navigationBarTitle:_titleMain image:[UIImage imageNamed:image_offlineTitle] frame:self.navigationController.navigationBar.frame];
  391. } else
  392. self.navigationItem.title = _titleMain;
  393. }
  394. }
  395. }
  396. - (void)setTitleBackgroundTableView
  397. {
  398. if ([_sectionDataSource.allRecordsDataSource count] == 0) {
  399. [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_", nil)];
  400. } else {
  401. [self setTitleBackgroundTableView:nil];
  402. }
  403. }
  404. - (void)setTitleBackgroundTableView:(NSString *)title
  405. {
  406. if (title) {
  407. // message if table is empty
  408. UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
  409. if ([app.reachability isReachable] == NO) {
  410. messageLabel.text = NSLocalizedString(@"_comm_erro_pull_down_", nil);
  411. messageLabel.textColor = COLOR_NO_CONNECTION;
  412. messageLabel.font = [UIFont systemFontOfSize:14];
  413. } else {
  414. messageLabel.text = NSLocalizedString(title ,nil);
  415. messageLabel.textColor = [UIColor blackColor];
  416. messageLabel.font = [UIFont systemFontOfSize:14];
  417. }
  418. messageLabel.numberOfLines = 0;
  419. messageLabel.textAlignment = NSTextAlignmentCenter;
  420. [messageLabel sizeToFit];
  421. [self.tableView reloadData];
  422. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  423. self.tableView.backgroundView = messageLabel;
  424. } else {
  425. [self.tableView setBackgroundView:nil];
  426. self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
  427. }
  428. }
  429. - (void)setUINavigationBarDefault
  430. {
  431. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  432. UIBarButtonItem *buttonMore, *buttonNotification;
  433. // =
  434. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_more] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  435. buttonMore.enabled = true;
  436. // <
  437. self.navigationController.navigationBar.hidden = NO;
  438. // Notification
  439. if ([app.listOfNotifications count] > 0) {
  440. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_notification] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  441. buttonNotification.tintColor = COLOR_BRAND;
  442. buttonNotification.enabled = true;
  443. }
  444. if (buttonNotification)
  445. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  446. else
  447. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  448. self.navigationItem.leftBarButtonItem = nil;
  449. // close Menu
  450. [app.reSelectMenu close];
  451. }
  452. - (void)setUINavigationBarSelected
  453. {
  454. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  455. UIImage *icon = [UIImage imageNamed:image_more];
  456. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  457. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  458. self.navigationItem.leftBarButtonItem = leftButton;
  459. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  460. }
  461. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  462. {
  463. // close the menus
  464. if (app.reMainMenu.isOpen)
  465. [app.reMainMenu close];
  466. if (app.reSelectMenu.isOpen)
  467. [app.reSelectMenu close];
  468. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  469. }];
  470. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  471. }
  472. - (void)cancelSelect
  473. {
  474. [self tableViewSelect:NO];
  475. }
  476. #pragma --------------------------------------------------------------------------------------------
  477. #pragma mark ===== Document Picker =====
  478. #pragma --------------------------------------------------------------------------------------------
  479. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  480. {
  481. NSLog(@"Cancelled");
  482. }
  483. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  484. {
  485. NSLog(@"Cancelled");
  486. }
  487. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  488. {
  489. documentPicker.delegate = self;
  490. [self presentViewController:documentPicker animated:YES completion:nil];
  491. }
  492. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  493. {
  494. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  495. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  496. __block NSError *error;
  497. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  498. NSString *fileName = [url lastPathComponent];
  499. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  500. NSData *data = [NSData dataWithContentsOfURL:newURL];
  501. if (data && error == nil) {
  502. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  503. // Upload File
  504. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  505. } else {
  506. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  507. }
  508. } else {
  509. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  510. }
  511. }];
  512. }
  513. }
  514. - (void)openImportDocumentPicker
  515. {
  516. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  517. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  518. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  519. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  520. documentProviderMenu.delegate = self;
  521. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  522. }
  523. #pragma --------------------------------------------------------------------------------------------
  524. #pragma mark ===== Assets Picker =====
  525. #pragma --------------------------------------------------------------------------------------------
  526. - (void)openAssetsPickerController
  527. {
  528. CTAssetSelectionLabel *assetSelectionLabel = [CTAssetSelectionLabel appearance];
  529. assetSelectionLabel.borderWidth = 1.0;
  530. assetSelectionLabel.borderColor = COLOR_BRAND;
  531. [assetSelectionLabel setMargin:2.0];
  532. [assetSelectionLabel setTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12.0], NSForegroundColorAttributeName : [UIColor whiteColor], NSBackgroundColorAttributeName : COLOR_BRAND}];
  533. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  534. dispatch_async(dispatch_get_main_queue(), ^{
  535. // init picker
  536. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  537. // set delegate
  538. picker.delegate = self;
  539. // to show selection order
  540. //picker.showsSelectionIndex = YES;
  541. // to present picker as a form sheet in iPad
  542. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  543. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  544. // present picker
  545. [self presentViewController:picker animated:YES completion:nil];
  546. });
  547. }];
  548. }
  549. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  550. {
  551. [picker dismissViewControllerAnimated:YES completion:^{
  552. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  553. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  554. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  555. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  556. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  557. [self presentViewController:navigationController animated:YES completion:nil];
  558. }];
  559. }
  560. #pragma --------------------------------------------------------------------------------------------
  561. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  562. #pragma --------------------------------------------------------------------------------------------
  563. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  564. {
  565. // evitiamo il rimando della eventuale photo e/o video
  566. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  567. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  568. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  569. }
  570. }
  571. #pragma --------------------------------------------------------------------------------------------
  572. #pragma mark ===== UnZipFile =====
  573. #pragma --------------------------------------------------------------------------------------------
  574. - (void)unZipFile:(NSString *)fileID
  575. {
  576. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  577. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  578. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  579. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  580. dispatch_async(dispatch_get_main_queue(), ^{
  581. float progress = (float) entryNumber / (float)total;
  582. [_hudDeterminate progress:progress];
  583. });
  584. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  585. dispatch_async(dispatch_get_main_queue(), ^{
  586. [_hudDeterminate hideHud];
  587. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  588. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  589. });
  590. }];
  591. });
  592. }
  593. #pragma --------------------------------------------------------------------------------------------
  594. #pragma mark ===== Create New (OpenModel) =====
  595. #pragma --------------------------------------------------------------------------------------------
  596. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  597. {
  598. UIViewController *viewController;
  599. NSString *fileName, *uuid, *fileID, *serverUrl;
  600. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  601. [self.tableView deselectRowAtIndexPath:index animated:NO];
  602. if (isnew) {
  603. fileName = nil;
  604. uuid = [CCUtility getUUID];
  605. fileID = nil;
  606. serverUrl = _serverUrl;
  607. } else {
  608. fileName = _metadata.fileName;
  609. uuid = _metadata.uuid;
  610. fileID = _metadata.fileID;
  611. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  612. }
  613. if ([tipo isEqualToString:@"cartadicredito"])
  614. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  615. if ([tipo isEqualToString:@"bancomat"])
  616. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  617. if ([tipo isEqualToString:@"contocorrente"])
  618. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  619. if ([tipo isEqualToString:@"accountweb"])
  620. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  621. if ([tipo isEqualToString:@"patenteguida"])
  622. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  623. if ([tipo isEqualToString:@"cartaidentita"])
  624. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  625. if ([tipo isEqualToString:@"passaporto"])
  626. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  627. if ([tipo isEqualToString:@"note"]) {
  628. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  629. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  630. [self presentViewController:navigationController animated:YES completion:nil];
  631. } else {
  632. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  633. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  634. [self presentViewController:navigationController animated:YES completion:nil];
  635. }
  636. }
  637. // New folder or new photo or video
  638. - (void)returnCreate:(NSInteger)type
  639. {
  640. switch (type) {
  641. /* PLAIN */
  642. case k_returnCreateFolderPlain: {
  643. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  644. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  645. alertView.tag = alertCreateFolder;
  646. [alertView show];
  647. }
  648. break;
  649. case k_returnCreateFotoVideoPlain: {
  650. _isPickerCriptate = false;
  651. [self openAssetsPickerController];
  652. }
  653. break;
  654. case k_returnCreateFilePlain: {
  655. _isPickerCriptate = false;
  656. [self openImportDocumentPicker];
  657. }
  658. break;
  659. /* ENCRYPTED */
  660. case k_returnCreateFolderEncrypted: {
  661. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  662. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  663. alertView.tag = alertCreateFolderCrypto;
  664. [alertView show];
  665. }
  666. break;
  667. case k_returnCreateFotoVideoEncrypted: {
  668. _isPickerCriptate = true;
  669. [self openAssetsPickerController];
  670. }
  671. break;
  672. case k_returnCreateFileEncrypted: {
  673. _isPickerCriptate = true;
  674. [self openImportDocumentPicker];
  675. }
  676. break;
  677. /* UTILITY */
  678. case k_returnNote:
  679. [self openModel:@"note" isNew:true];
  680. break;
  681. case k_returnAccountWeb:
  682. [self openModel:@"accountweb" isNew:true];
  683. break;
  684. /* BANK */
  685. case k_returnCartaDiCredito:
  686. [self openModel:@"cartadicredito" isNew:true];
  687. break;
  688. case k_returnBancomat:
  689. [self openModel:@"bancomat" isNew:true];
  690. break;
  691. case k_returnContoCorrente:
  692. [self openModel:@"contocorrente" isNew:true];
  693. break;
  694. /* DOCUMENT */
  695. case k_returnPatenteGuida:
  696. [self openModel:@"patenteguida" isNew:true];
  697. break;
  698. case k_returnCartaIdentita:
  699. [self openModel:@"cartaidentita" isNew:true];
  700. break;
  701. case k_returnPassaporto:
  702. [self openModel:@"passaporto" isNew:true];
  703. break;
  704. }
  705. }
  706. #pragma --------------------------------------------------------------------------------------------
  707. #pragma mark ===== Save selected File =====
  708. #pragma --------------------------------------------------------------------------------------------
  709. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  710. {
  711. if (error)
  712. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  713. else
  714. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  715. }
  716. - (void)saveSelectedFiles
  717. {
  718. NSLog(@"[LOG] Start download selected files ...");
  719. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  720. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  721. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  722. for (CCMetadata *metadata in metadatas) {
  723. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  724. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  725. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  726. }
  727. }
  728. [_hud hideHud];
  729. });
  730. [self tableViewSelect:NO];
  731. }
  732. #pragma --------------------------------------------------------------------------------------------
  733. #pragma mark ===== Change Password =====
  734. #pragma --------------------------------------------------------------------------------------------
  735. - (void) loginSuccess:(NSInteger)loginType
  736. {
  737. [self readFolderWithForced:YES];
  738. }
  739. - (void)changePasswordAccount
  740. {
  741. CCLogin *loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  742. loginVC.delegate = self;
  743. loginVC.loginType = loginModifyPasswordUser;
  744. [self presentViewController:loginVC animated:YES completion:nil];
  745. }
  746. #pragma mark -
  747. #pragma --------------------------------------------------------------------------------------------
  748. #pragma mark ===== Peek & Pop =====
  749. #pragma --------------------------------------------------------------------------------------------
  750. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  751. {
  752. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  753. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  754. if (metadata.thumbnailExists && !metadata.cryptated) {
  755. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  756. if (cell) {
  757. previewingContext.sourceRect = cell.frame;
  758. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  759. vc.delegate = self;
  760. vc.metadata = metadata;
  761. return vc;
  762. }
  763. }
  764. return nil;
  765. }
  766. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  767. {
  768. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  769. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  770. }
  771. #pragma mark -
  772. #pragma --------------------------------------------------------------------------------------------
  773. #pragma mark ==== Notification ====
  774. #pragma --------------------------------------------------------------------------------------------
  775. - (void)getNotificationsOfServerSuccess:(NSArray *)listOfNotifications
  776. {
  777. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  778. NSString *old = @"", *new = @"";
  779. // Order by date
  780. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  781. OCNotifications *notification1 = obj1, *notification2 = obj2;
  782. return [notification2.date compare: notification1.date];
  783. }];
  784. // verify if listOfNotifications is changed
  785. for (OCNotifications *notification in listOfNotifications)
  786. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  787. for (OCNotifications *notification in appDelegate.listOfNotifications)
  788. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  789. if (![new isEqualToString:old]) {
  790. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  791. // reload Notification view
  792. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  793. }
  794. // Update NavigationBar
  795. if (!_isSelectedMode)
  796. [self setUINavigationBarDefault];
  797. }
  798. - (void)getNotificationsOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  799. {
  800. // Update NavigationBar
  801. if (!_isSelectedMode)
  802. [self setUINavigationBarDefault];
  803. }
  804. - (void)viewNotification
  805. {
  806. if ([app.listOfNotifications count] > 0) {
  807. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  808. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  809. [self presentViewController:notificationVC animated:YES completion:nil];
  810. }
  811. }
  812. #pragma --------------------------------------------------------------------------------------------
  813. #pragma mark ==== Request Server ====
  814. #pragma --------------------------------------------------------------------------------------------
  815. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  816. {
  817. app.capabilities = capabilities;
  818. }
  819. - (void)getFeaturesSupportedByServerSuccess:(BOOL)hasCapabilitiesSupport hasForbiddenCharactersSupport:(BOOL)hasForbiddenCharactersSupport hasShareSupport:(BOOL)hasShareSupport hasShareeSupport:(BOOL)hasShareeSupport
  820. {
  821. app.hasServerCapabilitiesSupport = hasCapabilitiesSupport;
  822. app.hasServerForbiddenCharactersSupport = hasForbiddenCharactersSupport;
  823. app.hasServerShareSupport = hasShareSupport;
  824. app.hasServerShareeSupport = hasShareeSupport;
  825. if (hasShareSupport || hasShareeSupport)
  826. [self requestSharedByServer];
  827. }
  828. - (void)getInfoServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  829. {
  830. if (errorCode == 401)
  831. [self changePasswordAccount];
  832. }
  833. - (void)requestServerInformation
  834. {
  835. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  836. [app.sharesID removeAllObjects];
  837. app.hasServerForbiddenCharactersSupport = YES;
  838. app.hasServerShareSupport = YES;
  839. metadataNet.action = actionGetFeaturesSuppServer;
  840. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  841. metadataNet.action = actionGetCapabilities;
  842. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  843. metadataNet.action = actionGetNotificationsOfServer;
  844. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  845. metadataNet.action = actionReadFile;
  846. metadataNet.selector = selectorReadFileQuota;
  847. metadataNet.serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  848. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  849. }
  850. #pragma --------------------------------------------------------------------------------------------
  851. #pragma mark ==== Download Thumbnail ====
  852. #pragma --------------------------------------------------------------------------------------------
  853. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  854. {
  855. __block CCCellMain *cell;
  856. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  857. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  858. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  859. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  860. if (cell.fileImageView.image == nil) {
  861. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  862. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  863. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  864. });
  865. }
  866. }
  867. }
  868. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  869. {
  870. NSLog(@"[LOG] Thumbnail Error %@ %@ (error %ld)", metadataNet.fileName , message, (long)errorCode);
  871. }
  872. - (void)downloadThumbnail:(CCMetadata *)metadata
  873. {
  874. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  875. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  876. metadataNet.action = actionDownloadThumbnail;
  877. metadataNet.fileID = metadata.fileID;
  878. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  879. metadataNet.fileNameLocal = metadata.fileID;
  880. metadataNet.fileNamePrint = metadata.fileNamePrint;
  881. metadataNet.options = @"m";
  882. metadataNet.priority = NSOperationQueuePriorityLow;
  883. metadataNet.selector = selectorDownloadThumbnail;
  884. metadataNet.serverUrl = serverUrl;
  885. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  886. }
  887. #pragma --------------------------------------------------------------------------------------------
  888. #pragma mark ==== Download ====
  889. #pragma --------------------------------------------------------------------------------------------
  890. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  891. {
  892. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  893. // File do not exists on server, remove in local
  894. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  895. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  896. }
  897. if ([selector isEqualToString:selectorLoadViewImage]) {
  898. dispatch_async(dispatch_get_main_queue(), ^{
  899. // Updating Detail
  900. if (app.activeDetail)
  901. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  902. // Updating Photos
  903. if (app.activePhotosCameraUpload)
  904. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  905. });
  906. } else {
  907. if (errorCode != kCFURLErrorCancelled)
  908. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  909. }
  910. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  911. }
  912. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  913. {
  914. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  915. if (metadata == nil) return;
  916. // reload
  917. if ([selector isEqualToString:selectorReload]) {
  918. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  919. }
  920. // Offline Directory
  921. if ([selector isEqualToString:selectorDownloadOffline]) {
  922. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  923. }
  924. // add Offline
  925. if ([selector isEqualToString:selectorAddOffline]) {
  926. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  927. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  928. }
  929. // encrypted file
  930. if ([selector isEqualToString:selectorEncryptFile]) {
  931. [self encryptedFile:metadata];
  932. }
  933. // decrypted file
  934. if ([selector isEqualToString:selectorDecryptFile]) {
  935. [self decryptedFile:metadata];
  936. }
  937. // open View File
  938. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  939. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  940. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  941. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  942. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  943. selector = selectorOpenIn;
  944. } else {
  945. _metadataSegue = metadata;
  946. _metadataSegue.sessionSelector = selector;
  947. if ([self shouldPerformSegue:serverUrl])
  948. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  949. }
  950. }
  951. // addLocal
  952. if ([selector isEqualToString:selectorAddLocal]) {
  953. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  954. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  955. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  956. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  957. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  958. }
  959. // Open with...
  960. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  961. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  962. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  963. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  964. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  965. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  966. _docController.delegate = self;
  967. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  968. }
  969. // Save to Photo Album
  970. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  971. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  972. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  973. // evitiamo il rimando photo
  974. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  975. UIImage *image = [UIImage imageWithContentsOfFile:file];
  976. if (image)
  977. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  978. else
  979. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  980. }
  981. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  982. // we avoid the cross-reference video
  983. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  984. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  985. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  986. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  987. } else {
  988. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  989. }
  990. }
  991. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  992. }
  993. // Copy File
  994. if ([selector isEqualToString:selectorLoadCopy]) {
  995. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  996. [self copyFileToPasteboard:metadata];
  997. }
  998. // download and view a template
  999. if ([selector isEqualToString:selectorLoadModelView]) {
  1000. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1001. [self openModel:metadata.model isNew:false];
  1002. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1003. }
  1004. //download file plist
  1005. if ([selector isEqualToString:selectorLoadPlist]) {
  1006. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1007. long countSelectorLoadPlist = 0;
  1008. for (NSOperation *operation in [app.netQueue operations]) {
  1009. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1010. countSelectorLoadPlist++;
  1011. }
  1012. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1013. dispatch_async(dispatch_get_main_queue(), ^{
  1014. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1015. });
  1016. }
  1017. }
  1018. //selectorLoadViewImage
  1019. if ([selector isEqualToString:selectorLoadViewImage]) {
  1020. dispatch_async(dispatch_get_main_queue(), ^{
  1021. // Detail
  1022. if (app.activeDetail)
  1023. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1024. // Photos
  1025. if (app.activePhotosCameraUpload)
  1026. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1027. });
  1028. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1029. }
  1030. // if exists postselector call self with selectorPost
  1031. if ([selectorPost length] > 0)
  1032. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1033. }
  1034. - (void)downloadSelectedFiles
  1035. {
  1036. NSLog(@"[LOG] Start download selected files ...");
  1037. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1038. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1039. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1040. for (CCMetadata *metadata in selectedMetadatas) {
  1041. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1042. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1043. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1044. }
  1045. }
  1046. [_hud hideHud];
  1047. });
  1048. [self tableViewSelect:NO];
  1049. }
  1050. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1051. {
  1052. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1053. for (TableMetadata *recordMetadata in records) {
  1054. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1055. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1056. metadataNet.action = actionDownloadFile;
  1057. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1058. metadataNet.downloadData = NO;
  1059. metadataNet.downloadPlist = YES;
  1060. metadataNet.selector = selectorLoadPlist;
  1061. metadataNet.serverUrl = serverUrl;
  1062. metadataNet.session = k_download_session_foreground;
  1063. metadataNet.taskStatus = k_taskStatusResume;
  1064. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1065. }
  1066. }
  1067. }
  1068. #pragma --------------------------------------------------------------------------------------------
  1069. #pragma mark ===== Upload new Photos/Videos =====
  1070. #pragma --------------------------------------------------------------------------------------------
  1071. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1072. {
  1073. // Automatic upload
  1074. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1075. [app loadTableAutomaticUploadForSelector:selector];
  1076. // Read File test do not exists
  1077. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1078. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1079. // reUpload
  1080. if (metadata)
  1081. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1082. }
  1083. // Print error
  1084. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1085. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1086. }
  1087. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1088. }
  1089. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1090. {
  1091. // Automatic upload
  1092. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1093. [app loadTableAutomaticUploadForSelector:selector];
  1094. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1095. [self readFolderWithForced:YES];
  1096. } else {
  1097. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1098. }
  1099. }
  1100. //
  1101. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1102. //
  1103. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1104. {
  1105. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  1106. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1107. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1108. });
  1109. }
  1110. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1111. {
  1112. NSArray *assets = [arguments objectAtIndex:0];
  1113. NSString *serverUrl = [arguments objectAtIndex:1];
  1114. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1115. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1116. NSString * session = [arguments objectAtIndex:4];
  1117. // remove title (graphics)
  1118. [self setTitleBackgroundTableView:nil];
  1119. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1120. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1121. // Create if request the folder for Photos
  1122. if ((useSubFolder || [serverUrl isEqualToString:folderPhotos]) && [_serverUrl isEqualToString:serverUrl] == NO){
  1123. if(![app.activePhotosCameraUpload createFolder:folderPhotos]) {
  1124. [_hud hideHud];
  1125. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1126. return;
  1127. }
  1128. }
  1129. // Create if request the subfolders
  1130. if (useSubFolder) {
  1131. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  1132. if(![app.activePhotosCameraUpload createFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  1133. [_hud hideHud];
  1134. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1135. return;
  1136. }
  1137. }
  1138. }
  1139. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1140. for (PHAsset *asset in assets) {
  1141. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1142. NSDate *assetDate = asset.creationDate;
  1143. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1144. // Create serverUrl if use sub folder
  1145. if (useSubFolder) {
  1146. [formatter setDateFormat:@"yyyy"];
  1147. NSString *yearString = [formatter stringFromDate:assetDate];
  1148. [formatter setDateFormat:@"MM"];
  1149. NSString *monthString = [formatter stringFromDate:assetDate];
  1150. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1151. }
  1152. // Check if is in upload
  1153. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1154. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1155. if ([isRecordInSessions count] > 0) {
  1156. // next upload
  1157. continue;
  1158. } else {
  1159. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1160. metadataNet.action = actionReadFile;
  1161. metadataNet.identifier = asset.localIdentifier;
  1162. metadataNet.cryptated = cryptated;
  1163. metadataNet.fileName = fileName;
  1164. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1165. metadataNet.session = session;
  1166. metadataNet.selector = selectorReadFileUploadFile;
  1167. metadataNet.serverUrl = serverUrl;
  1168. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1169. }
  1170. }
  1171. [_hud hideHud];
  1172. }
  1173. #pragma --------------------------------------------------------------------------------------------
  1174. #pragma mark ==== Read File ====
  1175. #pragma --------------------------------------------------------------------------------------------
  1176. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1177. {
  1178. // UploadFile
  1179. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1180. // File not exists
  1181. if (errorCode == 404) {
  1182. metadataNet.action = actionUploadAsset;
  1183. metadataNet.errorCode = 0;
  1184. metadataNet.selector = selectorUploadFile;
  1185. metadataNet.selectorPost = nil;
  1186. metadataNet.taskStatus = k_taskStatusResume;
  1187. if ([metadataNet.session containsString:@"wwan"])
  1188. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1189. else
  1190. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1191. } else {
  1192. // error ho many retry befor notification and go to on next asses
  1193. if (metadataNet.errorRetry < 3) {
  1194. // Retry read file
  1195. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1196. } else {
  1197. // STOP check file, view message error
  1198. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1199. }
  1200. }
  1201. }
  1202. }
  1203. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1204. {
  1205. // ReadFile Folder for change rev
  1206. if ([metadataNet.selector isEqualToString:selectorReadFileFolder]) {
  1207. NSString *rev = [CCCoreData getDirectoryRevFromServerUrl:metadataNet.serverUrl activeAccount:app.activeAccount];
  1208. if (![metadata.rev isEqualToString:rev]) {
  1209. NSLog(@"Change etag, force reload folder %@", metadataNet.serverUrl);
  1210. [CCCoreData setDirectoryRev:metadata.rev serverUrl:metadataNet.serverUrl activeAccount:app.activeAccount];
  1211. [CCCoreData clearDateReadDirectory:metadataNet.serverUrl activeAccount:app.activeAccount];
  1212. CCMain *viewController = [app.listMainVC objectForKey:metadataNet.serverUrl];
  1213. if (viewController)
  1214. [viewController clearDateReadDataSource:nil];
  1215. }
  1216. }
  1217. // UploadFile
  1218. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1219. metadataNet.action = actionUploadAsset;
  1220. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1221. metadataNet.selector = selectorUploadFile;
  1222. metadataNet.selectorPost = nil;
  1223. metadataNet.taskStatus = k_taskStatusResume;
  1224. if ([metadataNet.session containsString:@"wwan"])
  1225. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1226. else
  1227. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1228. }
  1229. // Quota
  1230. if ([metadataNet.selector isEqualToString:selectorReadFileQuota]) {
  1231. if (app.activeSettings)
  1232. [app.activeSettings reloadForm];
  1233. }
  1234. }
  1235. #pragma --------------------------------------------------------------------------------------------
  1236. #pragma mark ==== Read Folder ====
  1237. #pragma --------------------------------------------------------------------------------------------
  1238. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1239. {
  1240. // verify active user
  1241. TableAccount *record = [CCCoreData getActiveAccount];
  1242. [_hud hideHud];
  1243. [_refreshControl endRefreshing];
  1244. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1245. if (message && [record.account isEqualToString:metadataNet.account])
  1246. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1247. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1248. if (errorCode == 401)
  1249. [self changePasswordAccount];
  1250. }
  1251. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions rev:(NSString *)rev metadatas:(NSArray *)metadatas
  1252. {
  1253. // verify active user
  1254. TableAccount *record = [CCCoreData getActiveAccount];
  1255. if (![record.account isEqualToString:metadataNet.account])
  1256. return;
  1257. // save father e update permission
  1258. _fatherPermission = permissions;
  1259. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, metadataNet.directoryID]];
  1260. NSArray *recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, metadataNet.directoryID] context:nil];
  1261. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1262. for (CCMetadata *metadata in metadatas) {
  1263. // type of file
  1264. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1265. // if crypto do not insert
  1266. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1267. // verify if the record encrypted has plist + crypto
  1268. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1269. BOOL isCryptoComplete = NO;
  1270. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1271. for (CCMetadata *completeMetadata in metadatas) {
  1272. if (completeMetadata.cryptated == NO) continue;
  1273. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1274. isCryptoComplete = YES;
  1275. break;
  1276. }
  1277. }
  1278. if (isCryptoComplete == NO) continue;
  1279. }
  1280. // verify if the record is in download/upload progress
  1281. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1282. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1283. // Upload
  1284. if (metadataDB.session && [metadataDB.session rangeOfString:@"upload"].location != NSNotFound) {
  1285. NSString *sessionID = metadataDB.sessionID;
  1286. // rename SessionID -> fileID
  1287. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1288. metadataDB.session = @"";
  1289. metadataDB.date = metadata.date;
  1290. metadataDB.fileID = metadata.fileID;
  1291. metadataDB.rev = metadata.fileID;
  1292. metadataDB.sessionError = @"";
  1293. metadataDB.sessionID = @"";
  1294. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1295. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1296. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1297. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1298. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1299. continue;
  1300. }
  1301. // download in progress
  1302. if (metadataDB.session && [metadataDB.session rangeOfString:@"download"].location != NSNotFound) continue;
  1303. }
  1304. // end test, insert in CoreData
  1305. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1306. }
  1307. // read plist
  1308. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1309. // File is changed ??
  1310. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1311. [[CCOfflineFileFolder sharedOfflineFileFolder] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount offline:NO];
  1312. });
  1313. // this is the same directory
  1314. if ([metadataNet.serverUrl isEqualToString:_serverUrl]) {
  1315. // reload
  1316. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1317. // stoprefresh
  1318. [_refreshControl endRefreshing];
  1319. // Enable change user
  1320. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1321. [_hud hideHud];
  1322. }
  1323. }
  1324. - (void)readFolderWithForced:(BOOL)forced
  1325. {
  1326. [self setTitleBackgroundTableView:nil];
  1327. // init control
  1328. if (!_serverUrl || !app.activeAccount)
  1329. return;
  1330. // Search Mode
  1331. if (_isSearchMode) {
  1332. if (forced)
  1333. _reloadForcedFoderWhenSearchModeOff = YES;
  1334. [self updateSearchResultsForSearchController:self.searchController];
  1335. return;
  1336. }
  1337. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1338. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1339. if (_refreshControl.isRefreshing == NO)
  1340. [_hud visibleIndeterminateHud];
  1341. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1342. metadataNet.action = actionReadFolder;
  1343. metadataNet.date = [NSDate date];
  1344. metadataNet.directoryID = directoryID;
  1345. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1346. metadataNet.selector = selectorReadFolder;
  1347. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:app.activeAccount];
  1348. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1349. } else {
  1350. if ([_sectionDataSource.allRecordsDataSource count] == 0) [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_",nil)];
  1351. else [self setTitleBackgroundTableView:nil];
  1352. }
  1353. }
  1354. #pragma mark -
  1355. #pragma --------------------------------------------------------------------------------------------
  1356. #pragma mark ===== Search =====
  1357. #pragma --------------------------------------------------------------------------------------------
  1358. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1359. {
  1360. _isSearchMode = YES;
  1361. [self deleteRefreshControl];
  1362. NSString *fileName = [CCUtility removeForbiddenCharacters:searchController.searchBar.text hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1363. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1364. _searchFileName = fileName;
  1365. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName delegate:self];
  1366. }
  1367. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1368. [self reloadDatasource];
  1369. }
  1370. }
  1371. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1372. {
  1373. [self cancelSearchBar];
  1374. // Need reload folder
  1375. if (_reloadForcedFoderWhenSearchModeOff) {
  1376. _reloadForcedFoderWhenSearchModeOff = NO;
  1377. [self readFolderWithForced:YES];
  1378. }
  1379. }
  1380. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1381. {
  1382. if (message)
  1383. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1384. }
  1385. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1386. {
  1387. _searchResultMetadatas = [[NSArray alloc] initWithArray:metadatas];
  1388. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1389. }
  1390. - (void)cancelSearchBar
  1391. {
  1392. if (self.searchController.active) {
  1393. [self.searchController setActive:NO];
  1394. [self createRefreshControl];
  1395. _isSearchMode = NO;
  1396. _searchFileName = @"";
  1397. _dateReadDataSource = nil;
  1398. _searchResultMetadatas = [NSArray new];
  1399. [self reloadDatasource];
  1400. }
  1401. }
  1402. #pragma mark -
  1403. #pragma --------------------------------------------------------------------------------------------
  1404. #pragma mark ===== Delete File or Folder =====
  1405. #pragma --------------------------------------------------------------------------------------------
  1406. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1407. {
  1408. [self deleteFileOrFolderSuccess:metadataNet];
  1409. }
  1410. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1411. {
  1412. [_queueSelector removeObject:metadataNet.selector];
  1413. if ([_queueSelector count] == 0) {
  1414. [_hud hideHud];
  1415. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1416. // next
  1417. if ([_selectedMetadatas count] > 0) {
  1418. [_selectedMetadatas removeObjectAtIndex:0];
  1419. if ([_selectedMetadatas count] > 0)
  1420. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1421. }
  1422. }
  1423. }
  1424. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1425. {
  1426. if (metadata.cryptated) {
  1427. [_queueSelector addObject:selectorDeleteCrypto];
  1428. [_queueSelector addObject:selectorDeletePlist];
  1429. } else {
  1430. [_queueSelector addObject:selectorDelete];
  1431. }
  1432. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1433. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1434. }
  1435. - (void)deleteSelectionFile
  1436. {
  1437. [_selectedMetadatas removeAllObjects];
  1438. [_queueSelector removeAllObjects];
  1439. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1440. _numSelectedMetadatas = [_selectedMetadatas count];
  1441. if ([_selectedMetadatas count] > 0)
  1442. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1443. [self tableViewSelect:NO];
  1444. }
  1445. - (void)deleteFile
  1446. {
  1447. [_selectedMetadatas removeAllObjects];
  1448. [_queueSelector removeAllObjects];
  1449. _numSelectedMetadatas = 1;
  1450. [_selectedMetadatas addObject:_metadata];
  1451. if ([_selectedMetadatas count] > 0)
  1452. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1453. [self tableViewSelect:NO];
  1454. }
  1455. #pragma --------------------------------------------------------------------------------------------
  1456. #pragma mark ===== Rename / Move =====
  1457. #pragma --------------------------------------------------------------------------------------------
  1458. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1459. {
  1460. [self readFolderWithForced:YES];
  1461. }
  1462. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1463. {
  1464. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1465. }
  1466. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1467. {
  1468. CCTemplates *templates = [[CCTemplates alloc] init];
  1469. CCCrypto *crypto = [[CCCrypto alloc] init];
  1470. NSMutableDictionary *field = [crypto getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1471. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1472. if (fileNameModel) {
  1473. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1474. metadataNet.action = actionUploadTemplate;
  1475. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1476. metadataNet.fileNamePrint = fileName;
  1477. metadataNet.rev = metadata.rev;
  1478. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1479. metadataNet.session = k_upload_session_foreground;
  1480. metadataNet.taskStatus = k_taskStatusResume;
  1481. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1482. metadataNet.selectorPost = selectorAddOffline;
  1483. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1484. }
  1485. }
  1486. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1487. {
  1488. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1489. [_hud hideHud];
  1490. if (message)
  1491. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1492. [_selectedMetadatas removeAllObjects];
  1493. [_queueSelector removeAllObjects];
  1494. }
  1495. }
  1496. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1497. {
  1498. [_queueSelector removeObject:metadataNet.selector];
  1499. if ([_queueSelector count] == 0) {
  1500. [_hud hideHud];
  1501. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1502. NSString *directoryID = metadataNet.directoryID;
  1503. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1504. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1505. // FILE -> Metadata
  1506. if (metadataNet.directory == NO) {
  1507. // move metadata
  1508. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1509. }
  1510. // DIRECTORY -> Directory - CCMetadata
  1511. if (metadataNet.directory == YES) {
  1512. // delete all dir / subdir
  1513. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addServerUrl:fileName] activeAccount:app.activeAccount];
  1514. // delete all metadata and local file in dir / subdir
  1515. for (NSString *directoryIDDelete in directoryIDs)
  1516. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1517. // move metadata
  1518. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1519. // Add new directory
  1520. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1521. [CCCoreData addDirectory:newDirectory date:[NSDate date] permissions:nil activeAccount:app.activeAccount];
  1522. // Check Offline
  1523. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1524. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1525. }
  1526. // reload Datasource
  1527. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced])
  1528. [self readFolderWithForced:YES];
  1529. else
  1530. [self reloadDatasource];
  1531. // Next file
  1532. [_selectedMetadatas removeObjectAtIndex:0];
  1533. [self moveFileOrFolder:metadataNet.serverUrlTo];
  1534. }
  1535. }
  1536. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1537. {
  1538. if ([_selectedMetadatas count] > 0) {
  1539. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1540. // Plain
  1541. if (metadata.cryptated == NO) {
  1542. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1543. metadataNet.action = actionMoveFileOrFolder;
  1544. metadataNet.directory = metadata.directory;
  1545. metadataNet.fileID = metadata.fileID;
  1546. metadataNet.directoryID = metadata.directoryID;
  1547. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1548. metadataNet.fileName = metadata.fileName;
  1549. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1550. metadataNet.fileNameTo = metadata.fileName;
  1551. metadataNet.rev = metadata.rev;
  1552. metadataNet.selector = selectorMove;
  1553. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1554. metadataNet.serverUrlTo = serverUrlTo;
  1555. [_queueSelector addObject:metadataNet.selector];
  1556. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1557. }
  1558. // cyptated
  1559. if (metadata.cryptated == YES) {
  1560. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1561. metadataNet.action = actionMoveFileOrFolder;
  1562. metadataNet.directory = metadata.directory;
  1563. metadataNet.fileID = metadata.fileID;
  1564. metadataNet.directoryID = metadata.directoryID;
  1565. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1566. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1567. metadataNet.rev = metadata.rev;
  1568. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1569. metadataNet.serverUrlTo = serverUrlTo;
  1570. // data
  1571. metadataNet.fileName = metadata.fileNameData;
  1572. metadataNet.fileNameTo = metadata.fileNameData;
  1573. metadataNet.selector = selectorMoveCrypto;
  1574. [_queueSelector addObject:metadataNet.selector];
  1575. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1576. // plist
  1577. metadataNet.fileName = metadata.fileName;
  1578. metadataNet.fileNameTo = metadata.fileName;
  1579. metadataNet.selector = selectorMovePlist;
  1580. [_queueSelector addObject:metadataNet.selector];
  1581. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1582. }
  1583. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1584. }
  1585. }
  1586. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1587. {
  1588. // Test
  1589. if ([_serverUrl isEqualToString:serverUrlTo]) {
  1590. [self tableViewSelect:NO];
  1591. return;
  1592. }
  1593. [_selectedMetadatas removeAllObjects];
  1594. [_queueSelector removeAllObjects];
  1595. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1596. _numSelectedMetadatas = [_selectedMetadatas count];
  1597. [self moveFileOrFolder:serverUrlTo];
  1598. [self tableViewSelect:NO];
  1599. }
  1600. - (void)moveOpenWindow:(NSArray *)indexPaths
  1601. {
  1602. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1603. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1604. viewController.delegate = self;
  1605. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1606. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1607. viewController.tintColor = COLOR_BRAND;
  1608. viewController.barTintColor = COLOR_BAR;
  1609. viewController.tintColorTitle = COLOR_GRAY;
  1610. viewController.networkingOperationQueue = app.netQueue;
  1611. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1612. [self presentViewController:navigationController animated:YES completion:nil];
  1613. }
  1614. #pragma --------------------------------------------------------------------------------------------
  1615. #pragma mark ===== Create folder =====
  1616. #pragma --------------------------------------------------------------------------------------------
  1617. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1618. {
  1619. [_hud hideHud];
  1620. if (message)
  1621. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1622. }
  1623. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1624. {
  1625. [_hud hideHud];
  1626. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1627. [CCCoreData addDirectory:newDirectory date:[NSDate date] permissions:nil activeAccount:app.activeAccount];
  1628. // Check Offline
  1629. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1630. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1631. // Load Folder or the Datasource
  1632. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1633. [self readFolderWithForced:YES];
  1634. } else {
  1635. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1636. }
  1637. }
  1638. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1639. {
  1640. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1641. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1642. if (![fileNameFolder length]) return;
  1643. if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1644. else metadataNet.serverUrl = _serverUrl;
  1645. metadataNet.action = actionCreateFolder;
  1646. if (folderCameraUpload)
  1647. metadataNet.options = @"folderCameraUpload";
  1648. metadataNet.fileName = fileNameFolder;
  1649. metadataNet.selector = selectorCreateFolder;
  1650. metadataNet.selectorPost = selectorReadFolderForced;
  1651. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1652. if (!folderCameraUpload)
  1653. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1654. }
  1655. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1656. {
  1657. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1658. CCCrypto *crypto = [[CCCrypto alloc] init];
  1659. NSString *fileNamePlist;
  1660. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1661. if (![fileNameFolder length]) return;
  1662. NSString *title = [AESCrypt encrypt:fileNameFolder password:[crypto getKeyPasscode:[CCUtility getUUID]]];
  1663. fileNamePlist = [crypto createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1664. [crypto createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1665. // Create folder
  1666. metadataNet.action = actionCreateFolder;
  1667. metadataNet.fileName = fileNamePlist;
  1668. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1669. metadataNet.selector = selectorCreateFolder;
  1670. metadataNet.serverUrl = _serverUrl;
  1671. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1672. // upload plist file
  1673. metadataNet.action = actionUploadOnlyPlist;
  1674. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1675. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1676. metadataNet.selectorPost = selectorReadFolderForced;
  1677. metadataNet.serverUrl = _serverUrl;
  1678. metadataNet.session = k_upload_session_foreground;
  1679. metadataNet.taskStatus = k_taskStatusResume;
  1680. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1681. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1682. }
  1683. - (void)createFolderCameraUpload
  1684. {
  1685. [self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1686. }
  1687. #pragma --------------------------------------------------------------------------------------------
  1688. #pragma mark ===== Encrypted / Decrypted Folder =====
  1689. #pragma --------------------------------------------------------------------------------------------
  1690. - (void)encyptedDecryptedFolder
  1691. {
  1692. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1693. if (_metadata.cryptated) {
  1694. // DECRYPTED
  1695. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1696. //-------------------------- RENAME -------------------------------------------//
  1697. metadataNet.action = actionMoveFileOrFolder;
  1698. metadataNet.fileID = _metadata.fileID;
  1699. metadataNet.fileName = _metadata.fileNameData;
  1700. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1701. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1702. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1703. metadataNet.selector = selectorRename;
  1704. metadataNet.serverUrl = serverUrl;
  1705. metadataNet.serverUrlTo = serverUrl;
  1706. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1707. //-------------------------- DELETE -------------------------------------------//
  1708. metadataNet.action = actionDeleteFileDirectory;
  1709. metadataNet.fileID = _metadata.fileID;
  1710. metadataNet.fileName = _metadata.fileName;
  1711. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1712. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1713. metadataNet.selector = selectorDeletePlist;
  1714. metadataNet.selectorPost = selectorReadFolderForced;
  1715. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1716. } else {
  1717. // ENCRYPTED
  1718. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1719. CCCrypto *crypto = [[CCCrypto alloc] init];
  1720. // Create File Plist
  1721. NSString *fileNameCrypto = [crypto createFileDirectoryPlist:_metadata];
  1722. //-------------------------- RENAME -------------------------------------------//
  1723. metadataNet.action = actionMoveFileOrFolder;
  1724. metadataNet.fileID = _metadata.fileID;
  1725. metadataNet.fileName = _metadata.fileName;
  1726. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1727. metadataNet.fileNameTo = fileNameCrypto;
  1728. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1729. metadataNet.selector = selectorRename;
  1730. metadataNet.serverUrl = serverUrl;
  1731. metadataNet.serverUrlTo = serverUrl;
  1732. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1733. //-------------------------- UPLOAD -------------------------------------------//
  1734. metadataNet.action = actionUploadOnlyPlist;
  1735. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1736. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1737. metadataNet.selectorPost = selectorReadFolderForced;
  1738. metadataNet.serverUrl = serverUrl;
  1739. metadataNet.session = k_upload_session_foreground;
  1740. metadataNet.taskStatus = k_taskStatusResume;
  1741. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1742. }
  1743. }
  1744. #pragma --------------------------------------------------------------------------------------------
  1745. #pragma mark ===== Encrypted/Decrypted File =====
  1746. #pragma --------------------------------------------------------------------------------------------
  1747. - (void)encryptedSelectedFiles
  1748. {
  1749. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1750. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1751. for (CCMetadata *metadata in selectedMetadatas) {
  1752. if (metadata.cryptated == NO && metadata.directory == NO)
  1753. [metadatas addObject:metadata];
  1754. }
  1755. if ([metadatas count] > 0) {
  1756. NSLog(@"[LOG] Start encrypted selected files ...");
  1757. for (CCMetadata* metadata in metadatas) {
  1758. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1759. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1760. }
  1761. }
  1762. [self tableViewSelect:NO];
  1763. }
  1764. - (void)decryptedSelectedFiles
  1765. {
  1766. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1767. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1768. for (CCMetadata *metadata in selectedMetadatas) {
  1769. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1770. [metadatas addObject:metadata];
  1771. }
  1772. if ([metadatas count] > 0) {
  1773. NSLog(@"[LOG] Start decrypted selected files ...");
  1774. for (CCMetadata* metadata in metadatas) {
  1775. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1776. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1777. }
  1778. }
  1779. [self tableViewSelect:NO];
  1780. }
  1781. - (void)cmdEncryptedDecryptedFile
  1782. {
  1783. NSString *selector;
  1784. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1785. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1786. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1787. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1788. }
  1789. - (void)encryptedFile:(CCMetadata *)metadata
  1790. {
  1791. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1792. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1793. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1794. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1795. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1796. dispatch_async(dispatch_get_main_queue(), ^{
  1797. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1798. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1799. });
  1800. } else {
  1801. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1802. }
  1803. }
  1804. - (void)decryptedFile:(CCMetadata *)metadata
  1805. {
  1806. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1807. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1808. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1809. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1810. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1811. dispatch_async(dispatch_get_main_queue(), ^{
  1812. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1813. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1814. });
  1815. } else {
  1816. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1817. }
  1818. }
  1819. #pragma --------------------------------------------------------------------------------------------
  1820. #pragma mark ===== Progress & Task Button =====
  1821. #pragma --------------------------------------------------------------------------------------------
  1822. - (void)progressTask:(NSString *)fileID serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated progress:(float)progress;
  1823. {
  1824. // Check
  1825. if (!fileID)
  1826. return;
  1827. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1828. if (![serverUrl isEqualToString:_serverUrl])
  1829. return;
  1830. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1831. if (indexPath) {
  1832. CCControlCenterCell *cell = (CCControlCenterCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1833. if (cryptated) cell.progressView.progressTintColor = COLOR_ENCRYPTED;
  1834. else cell.progressView.progressTintColor = COLOR_CLEAR;
  1835. cell.progressView.hidden = NO;
  1836. [cell.progressView setProgress:progress];
  1837. }
  1838. }
  1839. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1840. {
  1841. UITouch * touch = [[event allTouches] anyObject];
  1842. CGPoint location = [touch locationInView:self.tableView];
  1843. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1844. if (indexPath) {
  1845. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1846. if (metadata)
  1847. [self reloadTaskButton:metadata];
  1848. }
  1849. }
  1850. - (void)reloadTaskButton:(CCMetadata *)metadata
  1851. {
  1852. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1853. __block NSURLSessionTask *findTask;
  1854. // DOWNLOAD
  1855. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1856. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1857. for (NSURLSessionUploadTask *task in downloadTasks)
  1858. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1859. findTask = task;
  1860. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1861. [task cancel];
  1862. }
  1863. if (!findTask) {
  1864. dispatch_async(dispatch_get_main_queue(), ^{
  1865. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1866. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1867. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1868. });
  1869. }
  1870. }];
  1871. }
  1872. // UPLOAD
  1873. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1874. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1875. for (NSURLSessionUploadTask *task in uploadTasks)
  1876. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1877. findTask = task;
  1878. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1879. [task cancel];
  1880. }
  1881. if (!findTask) {
  1882. dispatch_async(dispatch_get_main_queue(), ^{
  1883. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1884. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1885. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1886. });
  1887. }
  1888. }];
  1889. }
  1890. }
  1891. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1892. {
  1893. UITouch * touch = [[event allTouches] anyObject];
  1894. CGPoint location = [touch locationInView:self.tableView];
  1895. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1896. if (indexPath) {
  1897. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1898. if (metadata)
  1899. [self cancelTaskButton:metadata reloadTable:YES];
  1900. }
  1901. }
  1902. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  1903. {
  1904. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1905. __block NSURLSessionTask *findTask;
  1906. // DOWNLOAD
  1907. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1908. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1909. for (NSURLSessionTask *task in downloadTasks)
  1910. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1911. findTask = task;
  1912. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1913. [task cancel];
  1914. }
  1915. if (!findTask) {
  1916. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1917. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1918. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1919. }
  1920. }];
  1921. }
  1922. // UPLOAD
  1923. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1924. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1925. for (NSURLSessionUploadTask *task in uploadTasks)
  1926. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1927. findTask = task;
  1928. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1929. [task cancel];
  1930. }
  1931. if (!findTask) {
  1932. dispatch_async(dispatch_get_main_queue(), ^{
  1933. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1934. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1935. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1936. });
  1937. }
  1938. }];
  1939. }
  1940. }
  1941. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1942. {
  1943. UITouch * touch = [[event allTouches] anyObject];
  1944. CGPoint location = [touch locationInView:self.tableView];
  1945. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1946. if (indexPath) {
  1947. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1948. if (metadata)
  1949. [self stopTaskButton:metadata];
  1950. }
  1951. }
  1952. - (void)stopTaskButton:(CCMetadata *)metadata
  1953. {
  1954. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1955. __block NSURLSessionTask *findTask;
  1956. // UPLOAD
  1957. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1958. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1959. for (NSURLSessionUploadTask *task in uploadTasks)
  1960. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1961. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1962. findTask = task;
  1963. [task cancel];
  1964. }
  1965. if (!findTask) {
  1966. dispatch_async(dispatch_get_main_queue(), ^{
  1967. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1968. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1969. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1970. });
  1971. }
  1972. }];
  1973. }
  1974. }
  1975. #pragma --------------------------------------------------------------------------------------------
  1976. #pragma mark ===== Shared =====
  1977. #pragma --------------------------------------------------------------------------------------------
  1978. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1979. {
  1980. [_hud hideHud];
  1981. // change account ?
  1982. TableAccount *record = [CCCoreData getActiveAccount];
  1983. if([record.account isEqualToString:metadataNet.account] == NO)
  1984. return;
  1985. [CCCoreData updateShare:items sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount activeUrl:app.activeUrl];
  1986. if (openWindow) {
  1987. if (_shareOC) {
  1988. [_shareOC reloadData];
  1989. } else {
  1990. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  1991. // Apriamo la view
  1992. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1993. _shareOC.delegate = self;
  1994. _shareOC.metadata = metadata;
  1995. _shareOC.serverUrl = metadataNet.serverUrl;
  1996. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1997. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1998. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1999. [self presentViewController:_shareOC animated:YES completion:nil];
  2000. }
  2001. }
  2002. [self tableViewReload];
  2003. }
  2004. - (void)requestSharedByServer
  2005. {
  2006. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2007. metadataNet.action = actionReadShareServer;
  2008. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2009. }
  2010. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2011. {
  2012. [_hud hideHud];
  2013. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2014. if (_shareOC)
  2015. [_shareOC reloadData];
  2016. [self tableViewReload];
  2017. if (errorCode == 401)
  2018. [self changePasswordAccount];
  2019. }
  2020. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2021. {
  2022. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2023. metadataNet.action = actionShare;
  2024. metadataNet.fileID = metadata.fileID;
  2025. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2026. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2027. metadataNet.password = password;
  2028. metadataNet.selector = selectorShare;
  2029. metadataNet.serverUrl = serverUrl;
  2030. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2031. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2032. }
  2033. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2034. {
  2035. [_hud hideHud];
  2036. // rimuoviamo la condivisione da db
  2037. [CCCoreData unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount];
  2038. if (_shareOC)
  2039. [_shareOC reloadData];
  2040. [self tableViewReload];
  2041. }
  2042. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2043. {
  2044. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2045. metadataNet.action = actionUnShare;
  2046. metadataNet.fileID = metadata.fileID;
  2047. metadataNet.fileName = metadata.fileName;
  2048. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2049. metadataNet.selector = selectorUnshare;
  2050. metadataNet.serverUrl = serverUrl;
  2051. metadataNet.share = share;
  2052. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2053. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2054. }
  2055. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2056. {
  2057. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2058. metadataNet.action = actionUpdateShare;
  2059. metadataNet.fileID = metadata.fileID;
  2060. metadataNet.expirationTime = expirationTime;
  2061. metadataNet.password = password;
  2062. metadataNet.selector = selectorUpdateShare;
  2063. metadataNet.serverUrl = serverUrl;
  2064. metadataNet.share = share;
  2065. metadataNet.sharePermission = permission;
  2066. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2067. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2068. }
  2069. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2070. {
  2071. [_hud hideHud];
  2072. if (_shareOC)
  2073. [_shareOC reloadUserAndGroup:items];
  2074. }
  2075. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2076. {
  2077. [_hud hideHud];
  2078. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2079. }
  2080. - (void)getUserAndGroup:(NSString *)find
  2081. {
  2082. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2083. metadataNet.action = actionGetUserAndGroup;
  2084. metadataNet.options = find;
  2085. metadataNet.selector = selectorGetUserAndGroup;
  2086. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2087. [_hud visibleIndeterminateHud];
  2088. }
  2089. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2090. {
  2091. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2092. metadataNet.action = actionShareWith;
  2093. metadataNet.fileID = metadata.fileID;
  2094. metadataNet.directoryID = directoryID;
  2095. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2096. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2097. metadataNet.serverUrl = serverUrl;
  2098. metadataNet.selector = selectorShare;
  2099. metadataNet.share = user;
  2100. metadataNet.shareeType = shareeType;
  2101. metadataNet.sharePermission = permission;
  2102. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2103. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2104. }
  2105. - (void)openWindowShare:(CCMetadata *)metadata
  2106. {
  2107. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2108. metadataNet.action = actionReadShareServer;
  2109. metadataNet.fileID = metadata.fileID;
  2110. metadataNet.fileName = metadata.fileName;
  2111. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2112. metadataNet.selector = selectorOpenWindowShare;
  2113. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2114. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2115. [_hud visibleIndeterminateHud];
  2116. }
  2117. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2118. {
  2119. CGPoint location = [tapGesture locationInView:self.tableView];
  2120. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2121. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2122. if (metadata)
  2123. [self openWindowShare:metadata];
  2124. }
  2125. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2126. {
  2127. CGPoint location = [tapGesture locationInView:self.tableView];
  2128. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2129. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2130. if (metadata) {
  2131. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2132. vc.metadata = metadata;
  2133. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2134. [self presentViewController:vc animated:YES completion:nil];
  2135. }
  2136. }
  2137. #pragma --------------------------------------------------------------------------------------------
  2138. #pragma mark ===== Offline =====
  2139. #pragma --------------------------------------------------------------------------------------------
  2140. - (void)addOffline:(CCMetadata *)metadata
  2141. {
  2142. if (metadata.errorPasscode || !metadata.uuid) return;
  2143. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2144. if ([metadata.type isEqualToString: k_metadataType_file])
  2145. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2146. if ([metadata.type isEqualToString: k_metadataType_template])
  2147. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  2148. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2149. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2150. }
  2151. - (void)removeOffline:(CCMetadata *)metadata
  2152. {
  2153. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2154. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2155. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2156. }
  2157. #pragma --------------------------------------------------------------------------------------------
  2158. #pragma mark ===== Local =====
  2159. #pragma --------------------------------------------------------------------------------------------
  2160. - (void)addLocal:(CCMetadata *)metadata
  2161. {
  2162. if (metadata.errorPasscode || !metadata.uuid) return;
  2163. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2164. if ([metadata.type isEqualToString: k_metadataType_file])
  2165. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2166. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2167. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2168. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  2169. }
  2170. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2171. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2172. }
  2173. #pragma --------------------------------------------------------------------------------------------
  2174. #pragma mark ===== Reload =====
  2175. #pragma --------------------------------------------------------------------------------------------
  2176. - (void)reloadFile:(CCMetadata *)metadata
  2177. {
  2178. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2179. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2180. }
  2181. #pragma --------------------------------------------------------------------------------------------
  2182. #pragma mark ===== Open in... =====
  2183. #pragma --------------------------------------------------------------------------------------------
  2184. - (void)openIn:(CCMetadata *)metadata
  2185. {
  2186. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2187. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2188. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2189. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2190. }
  2191. #pragma --------------------------------------------------------------------------------------------
  2192. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2193. #pragma --------------------------------------------------------------------------------------------
  2194. - (void)orderTable:(NSString *)order
  2195. {
  2196. // Clear data-read of DataSource
  2197. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2198. [CCUtility setOrderSettings:order];
  2199. // refresh
  2200. [self reloadDatasource];
  2201. // new menu
  2202. [self createReMainMenu];
  2203. }
  2204. - (void)ascendingTable:(BOOL)ascending
  2205. {
  2206. // Clear data-read of DataSource
  2207. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2208. [CCUtility setAscendingSettings:ascending];
  2209. // refresh
  2210. [self reloadDatasource];
  2211. // new menu
  2212. [self createReMainMenu];
  2213. }
  2214. - (void)directoryOnTop:(BOOL)directoryOnTop
  2215. {
  2216. // Clear data-read of DataSource
  2217. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2218. [CCUtility setDirectoryOnTop:directoryOnTop];
  2219. // refresh
  2220. [self reloadDatasource];
  2221. // new menu
  2222. [self createReMainMenu];
  2223. }
  2224. - (void)tableGroupBy:(NSString *)groupBy
  2225. {
  2226. // Clear data-read of DataSource
  2227. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2228. [CCUtility setGroupBySettings:groupBy];
  2229. // refresh
  2230. [self reloadDatasource];
  2231. // new menu
  2232. [self createReMainMenu];
  2233. }
  2234. #pragma --------------------------------------------------------------------------------------------
  2235. #pragma mark ==== Menu change User ====
  2236. #pragma --------------------------------------------------------------------------------------------
  2237. - (void)menuChangeUser
  2238. {
  2239. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2240. return;
  2241. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [CCCoreData countTableAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2242. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  2243. return;
  2244. }
  2245. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2246. NSMutableArray *menuArray = [[NSMutableArray alloc] init];
  2247. for (TableAccount *record in listTableAccount) {
  2248. if ([record.account isEqualToString:app.activeAccount]) continue;
  2249. CCMenuItem *item = [[CCMenuItem alloc] init];
  2250. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2251. item.argument = record.account;
  2252. item.image = [UIImage imageNamed:image_Nextcloud];
  2253. item.target = self;
  2254. item.action = @selector(changeDefaultAccount:);
  2255. [menuArray addObject:item];
  2256. }
  2257. if ([menuArray count] == 0)
  2258. return;
  2259. OptionalConfiguration options;
  2260. Color textColor, backgroundColor;
  2261. textColor.R = 0;
  2262. textColor.G = 0;
  2263. textColor.B = 0;
  2264. backgroundColor.R = 1;
  2265. backgroundColor.G = 1;
  2266. backgroundColor.B = 1;
  2267. NSInteger originY = 60;
  2268. options.arrowSize = 9;
  2269. options.marginXSpacing = 7;
  2270. options.marginYSpacing = 10;
  2271. options.intervalSpacing = 20;
  2272. options.menuCornerRadius = 6.5;
  2273. options.maskToBackground = NO;
  2274. options.shadowOfMenu = YES;
  2275. options.hasSeperatorLine = YES;
  2276. options.seperatorLineHasInsets = YES;
  2277. options.textColor = textColor;
  2278. options.menuBackgroundColor = backgroundColor;
  2279. CGRect rect = self.view.frame;
  2280. rect.origin.y = rect.origin.y + originY;
  2281. rect.size.height = rect.size.height - originY;
  2282. [CCMenu setTitleFont:[UIFont systemFontOfSize:12.0]];
  2283. [CCMenu showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2284. }
  2285. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2286. {
  2287. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2288. // STOP, erase all in queue networking
  2289. [app cancelAllOperations];
  2290. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2291. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2292. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2293. if (tableAccount)
  2294. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2295. // go to home sweet home
  2296. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2297. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2298. });
  2299. }
  2300. #pragma --------------------------------------------------------------------------------------------
  2301. #pragma mark ==== ReMenu ====
  2302. #pragma --------------------------------------------------------------------------------------------
  2303. - (void)createReMenuBackgroundView:(REMenu *)menu
  2304. {
  2305. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2306. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2307. [UIView animateWithDuration:0.2 animations:^{
  2308. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2309. if (height < self.tabBarController.tabBar.frame.size.height)
  2310. height = self.tabBarController.tabBar.frame.size.height;
  2311. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2312. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2313. }];
  2314. }
  2315. - (void)createReMainMenu
  2316. {
  2317. NSString *ordinamento;
  2318. NSString *groupBy = _directoryGroupBy;
  2319. __block NSString *nuovoOrdinamento;
  2320. NSString *titoloNuovo, *titoloAttuale;
  2321. BOOL ascendente;
  2322. __block BOOL nuovoAscendente;
  2323. UIImage *image;
  2324. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2325. if (app.selezionaItem == nil) app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)
  2326. subtitle:@""
  2327. image:[UIImage imageNamed:image_seleziona]
  2328. highlightedImage:nil
  2329. action:^(REMenuItem *item) {
  2330. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2331. [self tableViewSelect:YES];
  2332. }
  2333. }];
  2334. else app.selezionaItem = [app.selezionaItem initWithTitle:NSLocalizedString(@"_select_", nil)
  2335. subtitle:@""
  2336. image:[UIImage imageNamed:image_seleziona]
  2337. highlightedImage:nil
  2338. action:^(REMenuItem *item) {
  2339. if ([_sectionDataSource.allRecordsDataSource count] > 0)
  2340. [self tableViewSelect:YES];
  2341. }];
  2342. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2343. ordinamento = _directoryOrder;
  2344. if ([ordinamento isEqualToString:@"fileName"]) {
  2345. image = [UIImage imageNamed:image_MenuOrdeyByDate];
  2346. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2347. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2348. nuovoOrdinamento = @"fileDate";
  2349. }
  2350. if ([ordinamento isEqualToString:@"fileDate"]) {
  2351. image = [UIImage imageNamed:image_MenuOrderByFileName];
  2352. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2353. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2354. nuovoOrdinamento = @"fileName";
  2355. }
  2356. if (app.ordinaItem == nil) app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2357. subtitle:titoloAttuale
  2358. image:image
  2359. highlightedImage:nil
  2360. action:^(REMenuItem *item) {
  2361. [self orderTable:nuovoOrdinamento];
  2362. }];
  2363. else app.ordinaItem = [app.ordinaItem initWithTitle:titoloNuovo
  2364. subtitle:titoloAttuale
  2365. image:image
  2366. highlightedImage:nil
  2367. action:^(REMenuItem *item) {
  2368. [self orderTable:nuovoOrdinamento];
  2369. }];
  2370. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2371. ascendente = [CCUtility getAscendingSettings];
  2372. if (ascendente) {
  2373. image = [UIImage imageNamed:image_MenuOrdinamentoDiscendente];
  2374. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2375. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2376. nuovoAscendente = false;
  2377. }
  2378. if (!ascendente) {
  2379. image = [UIImage imageNamed:image_MenuOrdinamentoAscendente];
  2380. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2381. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2382. nuovoAscendente = true;
  2383. }
  2384. if (app.ascendenteItem == nil) app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2385. subtitle:titoloAttuale
  2386. image:image
  2387. highlightedImage:nil
  2388. action:^(REMenuItem *item) {
  2389. [self ascendingTable:nuovoAscendente];
  2390. }];
  2391. else app.ascendenteItem = [app.ascendenteItem initWithTitle:titoloNuovo
  2392. subtitle:titoloAttuale
  2393. image:image
  2394. highlightedImage:nil
  2395. action:^(REMenuItem *item) {
  2396. [self ascendingTable:nuovoAscendente];
  2397. }];
  2398. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2399. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2400. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2401. if (app.alphabeticItem == nil) app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2402. subtitle:@""
  2403. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2404. highlightedImage:nil
  2405. action:^(REMenuItem *item) {
  2406. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2407. else [self tableGroupBy:@"alphabetic"];
  2408. }];
  2409. else app.alphabeticItem = [app.alphabeticItem initWithTitle:titoloNuovo
  2410. subtitle:@""
  2411. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2412. highlightedImage:nil
  2413. action:^(REMenuItem *item) {
  2414. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2415. else [self tableGroupBy:@"alphabetic"];
  2416. }];
  2417. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2418. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2419. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2420. if (app.typefileItem == nil) app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2421. subtitle:@""
  2422. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2423. highlightedImage:nil
  2424. action:^(REMenuItem *item) {
  2425. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2426. else [self tableGroupBy:@"typefile"];
  2427. }];
  2428. else app.typefileItem = [app.typefileItem initWithTitle:titoloNuovo
  2429. subtitle:@""
  2430. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2431. highlightedImage:nil
  2432. action:^(REMenuItem *item) {
  2433. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2434. else [self tableGroupBy:@"typefile"];
  2435. }];
  2436. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2437. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2438. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2439. if (app.dateItem == nil) app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2440. subtitle:@""
  2441. image:[UIImage imageNamed:image_MenuGroupByDate]
  2442. highlightedImage:nil
  2443. action:^(REMenuItem *item) {
  2444. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2445. else [self tableGroupBy:@"date"];
  2446. }];
  2447. else app.dateItem = [app.dateItem initWithTitle:titoloNuovo
  2448. subtitle:@""
  2449. image:[UIImage imageNamed:image_MenuGroupByDate]
  2450. highlightedImage:nil
  2451. action:^(REMenuItem *item) {
  2452. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2453. else [self tableGroupBy:@"date"];
  2454. }];
  2455. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2456. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2457. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2458. if (app.directoryOnTopItem == nil) app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2459. subtitle:@""
  2460. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2461. highlightedImage:nil
  2462. action:^(REMenuItem *item) {
  2463. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2464. else [self directoryOnTop:YES];
  2465. }];
  2466. else app.directoryOnTopItem = [app.directoryOnTopItem initWithTitle:titoloNuovo
  2467. subtitle:@""
  2468. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2469. highlightedImage:nil
  2470. action:^(REMenuItem *item) {
  2471. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2472. else [self directoryOnTop:YES];
  2473. }];
  2474. // REMENU --------------------------------------------------------------------------------------------------------------
  2475. if (app.reMainMenu == nil) app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2476. else app.reMainMenu = [app.reMainMenu initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2477. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2478. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2479. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2480. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2481. app.reMainMenu.separatorHeight = 0.5;
  2482. app.reMainMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2483. app.reMainMenu.backgroundColor = COLOR_BAR;
  2484. app.reMainMenu.textColor = [UIColor blackColor];
  2485. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2486. app.reMainMenu.textShadowColor = nil;
  2487. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2488. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2489. app.reMainMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2490. app.reMainMenu.highlightedSeparatorColor = nil;
  2491. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2492. app.reMainMenu.highlightedTextShadowColor = nil;
  2493. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2494. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2495. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2496. app.reMainMenu.subtitleTextShadowColor = nil;
  2497. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2498. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2499. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2500. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2501. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2502. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2503. app.reMainMenu.borderWidth = 0.3;
  2504. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2505. app.reMainMenu.animationDuration = 0.2;
  2506. app.reMainMenu.closeAnimationDuration = 0.2;
  2507. app.reMainMenu.bounce = NO;
  2508. [app.reMainMenu setClosePreparationBlock:^{
  2509. // Backgroun reMenu (Gesture)
  2510. [_reMenuBackgroundView removeFromSuperview];
  2511. [app.controlCenter disableSingleFingerTap];
  2512. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2513. }];
  2514. }
  2515. - (void)toggleReMainMenu
  2516. {
  2517. if (app.reMainMenu.isOpen) {
  2518. [app.reMainMenu close];
  2519. } else {
  2520. [app.reMainMenu showFromNavigationController:self.navigationController];
  2521. // Backgroun reMenu & (Gesture)
  2522. [self createReMenuBackgroundView:app.reMainMenu];
  2523. [app.controlCenter enableSingleFingerTap:@selector(toggleReMainMenu) target:self];
  2524. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2525. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2526. }
  2527. }
  2528. - (void)createReSelectMenu
  2529. {
  2530. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2531. if (app.deleteItem == nil) app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2532. subtitle:@""
  2533. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2534. highlightedImage:nil
  2535. action:^(REMenuItem *item) {
  2536. [self deleteSelectionFile];
  2537. }];
  2538. else app.deleteItem = [app.deleteItem initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2539. subtitle:@""
  2540. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2541. highlightedImage:nil
  2542. action:^(REMenuItem *item) {
  2543. [self deleteSelectionFile];
  2544. }];
  2545. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2546. if (app.moveItem == nil) app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2547. subtitle:@""
  2548. image:[UIImage imageNamed:image_moveSelectedFiles]
  2549. highlightedImage:nil
  2550. action:^(REMenuItem *item) {
  2551. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2552. }];
  2553. else app.moveItem = [app.moveItem initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2554. subtitle:@""
  2555. image:[UIImage imageNamed:image_moveSelectedFiles]
  2556. highlightedImage:nil
  2557. action:^(REMenuItem *item) {
  2558. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2559. }];
  2560. if (app.isCryptoCloudMode) {
  2561. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2562. if (app.encryptItem == nil) app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2563. subtitle:@""
  2564. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2565. highlightedImage:nil
  2566. action:^(REMenuItem *item) {
  2567. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2568. }];
  2569. else app.encryptItem = [app.encryptItem initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2570. subtitle:@""
  2571. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2572. highlightedImage:nil
  2573. action:^(REMenuItem *item) {
  2574. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2575. }];
  2576. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2577. if (app.decryptItem == nil) app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2578. subtitle:@""
  2579. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2580. highlightedImage:nil
  2581. action:^(REMenuItem *item) {
  2582. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2583. }];
  2584. else app.decryptItem = [app.decryptItem initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2585. subtitle:@""
  2586. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2587. highlightedImage:nil
  2588. action:^(REMenuItem *item) {
  2589. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2590. }];
  2591. }
  2592. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2593. if (app.downloadItem == nil) app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2594. subtitle:@""
  2595. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2596. highlightedImage:nil
  2597. action:^(REMenuItem *item) {
  2598. [self downloadSelectedFiles];
  2599. }];
  2600. else app.downloadItem = [app.downloadItem initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2601. subtitle:@""
  2602. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2603. highlightedImage:nil
  2604. action:^(REMenuItem *item) {
  2605. [self downloadSelectedFiles];
  2606. }];
  2607. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2608. if (app.saveItem == nil) app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2609. subtitle:@""
  2610. image:[UIImage imageNamed:image_saveSelectedFiles]
  2611. highlightedImage:nil
  2612. action:^(REMenuItem *item) {
  2613. [self saveSelectedFiles];
  2614. }];
  2615. else app.saveItem = [app.saveItem initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2616. subtitle:@""
  2617. image:[UIImage imageNamed:image_saveSelectedFiles]
  2618. highlightedImage:nil
  2619. action:^(REMenuItem *item) {
  2620. [self saveSelectedFiles];
  2621. }];
  2622. // REMENU --------------------------------------------------------------------------------------------------------------
  2623. if (app.isCryptoCloudMode) {
  2624. if (app.reSelectMenu == nil)
  2625. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2626. else
  2627. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2628. } else {
  2629. if (app.reSelectMenu == nil)
  2630. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2631. else
  2632. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2633. }
  2634. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2635. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2636. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2637. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2638. app.reSelectMenu.separatorHeight = 0.5;
  2639. app.reSelectMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2640. app.reSelectMenu.backgroundColor = COLOR_BAR;
  2641. app.reSelectMenu.textColor = [UIColor blackColor];
  2642. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2643. app.reSelectMenu.textShadowColor = nil;
  2644. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2645. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2646. app.reSelectMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2647. app.reSelectMenu.highlightedSeparatorColor = nil;
  2648. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2649. app.reSelectMenu.highlightedTextShadowColor = nil;
  2650. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2651. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2652. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2653. app.reSelectMenu.subtitleTextShadowColor = nil;
  2654. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2655. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2656. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2657. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2658. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2659. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2660. app.reSelectMenu.borderWidth = 0.3;
  2661. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2662. app.reSelectMenu.closeAnimationDuration = 0.2;
  2663. app.reSelectMenu.animationDuration = 0.2;
  2664. app.reSelectMenu.bounce = NO;
  2665. [app.reSelectMenu setClosePreparationBlock:^{
  2666. // Backgroun reMenu (Gesture)
  2667. [_reMenuBackgroundView removeFromSuperview];
  2668. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2669. }];
  2670. }
  2671. - (void)toggleReSelectMenu
  2672. {
  2673. if (app.reSelectMenu.isOpen) {
  2674. [app.reSelectMenu close];
  2675. } else {
  2676. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2677. // Backgroun reMenu & (Gesture)
  2678. [self createReMenuBackgroundView:app.reSelectMenu];
  2679. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2680. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2681. }
  2682. }
  2683. #pragma --------------------------------------------------------------------------------------------
  2684. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2685. #pragma --------------------------------------------------------------------------------------------
  2686. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2687. {
  2688. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2689. UITableView *tableView = (UITableView*)self.view;
  2690. CGPoint touchPoint = [recognizer locationInView:self.view];
  2691. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2692. if (indexPath)
  2693. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2694. else
  2695. _metadata = nil;
  2696. [self becomeFirstResponder];
  2697. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2698. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2699. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2700. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2701. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2702. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2703. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2704. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2705. if (app.isCryptoCloudMode)
  2706. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2707. else
  2708. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2709. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2710. [menuController setMenuVisible:YES animated:YES];
  2711. }
  2712. }
  2713. - (BOOL)canBecomeFirstResponder
  2714. {
  2715. return YES;
  2716. }
  2717. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2718. {
  2719. // For copy file, copy files, Open in ... :
  2720. //
  2721. // NO Directory
  2722. // NO Error Passcode
  2723. // NO In Session mode (download/upload)
  2724. // NO Template
  2725. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2726. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2727. // NO Cryptated with Title lenght = 0
  2728. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2729. return YES;
  2730. }
  2731. return NO;
  2732. }
  2733. if (@selector(copyFiles:) == action) {
  2734. if (_isSelectedMode) {
  2735. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2736. for (CCMetadata *metadata in selectedMetadatas) {
  2737. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2738. // NO Cryptated with Title lenght = 0
  2739. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2740. return YES;
  2741. }
  2742. }
  2743. }
  2744. return NO;
  2745. }
  2746. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2747. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2748. NSArray *items = [pasteboard items];
  2749. if ([items count] == 1) {
  2750. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2751. NSDictionary *dic = [items objectAtIndex:0];
  2752. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2753. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2754. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2755. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2756. if (directoryUser) {
  2757. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2758. return YES;
  2759. }
  2760. return NO;
  2761. } else return NO;
  2762. }
  2763. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2764. BOOL isValid = NO;
  2765. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2766. NSArray *items = [pasteboard items];
  2767. if ([items count] <= 1) return NO;
  2768. for (NSDictionary *dic in items) {
  2769. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2770. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2771. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2772. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2773. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2774. if (directoryUser) {
  2775. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2776. isValid = YES;
  2777. }
  2778. }
  2779. return isValid;
  2780. }
  2781. return NO;
  2782. }
  2783. /************************************ COPY ************************************/
  2784. - (void)copyFile:(id)sender
  2785. {
  2786. // Remove all item
  2787. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2788. pasteboard.items = [[NSArray alloc] init];
  2789. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2790. [self copyFileToPasteboard:_metadata];
  2791. } else {
  2792. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2793. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2794. }
  2795. }
  2796. - (void)copyFiles:(id)sender
  2797. {
  2798. // Remove all item
  2799. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2800. pasteboard.items = [[NSArray alloc] init];
  2801. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2802. for (CCMetadata *metadata in selectedMetadatas) {
  2803. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2804. [self copyFileToPasteboard:metadata];
  2805. } else {
  2806. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2807. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2808. }
  2809. }
  2810. [self tableViewSelect:NO];
  2811. }
  2812. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2813. {
  2814. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2815. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2816. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2817. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], @"it.twsweb.Crypto-Cloud.CCMetadata",nil];
  2818. [items addObject:item];
  2819. [pasteboard setItems:items];
  2820. }
  2821. /************************************ OPEN IN ... ************************************/
  2822. - (void)openinFile:(id)sender
  2823. {
  2824. [self openIn:_metadata];
  2825. }
  2826. /************************************ PASTE ************************************/
  2827. - (void)pasteFile:(id)sender
  2828. {
  2829. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2830. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2831. }
  2832. - (void)pasteFileEncrypted:(id)sender
  2833. {
  2834. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2835. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2836. }
  2837. - (void)pasteFiles:(id)sender
  2838. {
  2839. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2840. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2841. }
  2842. - (void)pasteFilesEncrypted:(id)sender
  2843. {
  2844. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2845. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2846. }
  2847. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2848. {
  2849. for (NSDictionary *dic in items) {
  2850. // key : it.twsweb.Crypto-Cloud.CCMetadata
  2851. // Value : (NSData) metadata
  2852. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2853. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2854. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2855. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2856. if (directoryUser) {
  2857. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2858. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2859. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2860. }
  2861. }
  2862. }
  2863. }
  2864. #pragma --------------------------------------------------------------------------------------------
  2865. #pragma mark ===== Lock Passcode =====
  2866. #pragma --------------------------------------------------------------------------------------------
  2867. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2868. {
  2869. return _failedAttempts;
  2870. }
  2871. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2872. {
  2873. return _lockUntilDate;
  2874. }
  2875. - (void)passcodeViewCloseButtonPressed:(id)sender
  2876. {
  2877. [self dismissViewControllerAnimated:YES completion:nil];
  2878. }
  2879. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2880. {
  2881. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2882. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2883. _lockUntilDate = nil;
  2884. _failedAttempts = 0;
  2885. aResultHandler(YES);
  2886. } else aResultHandler(NO);
  2887. } else aResultHandler(YES);
  2888. }
  2889. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2890. {
  2891. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2892. switch (aViewController.type) {
  2893. case BKPasscodeViewControllerCheckPasscodeType: {
  2894. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2895. CCCrypto *crypto = [[CCCrypto alloc] init];
  2896. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2897. if ([crypto verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2898. // scriviamo il passcode
  2899. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2900. [self readFolderWithForced:YES];
  2901. } else {
  2902. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2903. [alertView show];
  2904. }
  2905. }
  2906. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2907. // possiamo procedere alla prossima directory
  2908. [self performSegueDirectoryWithControlPasscode:false];
  2909. // avviamo la sessione Passcode Lock con now
  2910. app.sessionePasscodeLock = [NSDate date];
  2911. }
  2912. // disattivazione lock cartella
  2913. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2914. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2915. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2916. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2917. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2918. }
  2919. [self.tableView reloadData];
  2920. }
  2921. }
  2922. break;
  2923. default:
  2924. break;
  2925. }
  2926. }
  2927. - (void)comandoLockPassword
  2928. {
  2929. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2930. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2931. // se non è abilitato il Lock Passcode esci
  2932. if ([[CCUtility getBlockCode] length] == 0) {
  2933. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2934. [alertView show];
  2935. return;
  2936. }
  2937. // se è richiesta la disattivazione si chiede la password
  2938. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2939. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2940. viewController.delegate = self;
  2941. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2942. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2943. viewController.inputViewTitlePassword = YES;
  2944. if ([CCUtility getSimplyBlockCode]) {
  2945. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2946. viewController.passcodeInputView.maximumLength = 6;
  2947. } else {
  2948. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2949. viewController.passcodeInputView.maximumLength = 64;
  2950. }
  2951. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  2952. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2953. viewController.touchIDManager = touchIDManager;
  2954. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2955. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2956. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_ENCRYPTED;
  2957. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2958. [self presentViewController:navigationController animated:YES completion:nil];
  2959. return;
  2960. }
  2961. // ---------------- ACTIVATE PASSWORD
  2962. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2963. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2964. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2965. } else {
  2966. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2967. }
  2968. }
  2969. #pragma mark -
  2970. #pragma --------------------------------------------------------------------------------------------
  2971. #pragma mark ===== Swipe Tablet -> menu =====
  2972. #pragma --------------------------------------------------------------------------------------------
  2973. // more
  2974. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2975. return NSLocalizedString(@"_more_", nil);
  2976. }
  2977. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2978. {
  2979. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2980. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2981. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder;
  2982. BOOL offlineFolder = NO;
  2983. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2984. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2985. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2986. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2987. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2988. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  2989. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2990. offlineFolder = YES;
  2991. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2992. if (_metadata.directory) {
  2993. // calcolo lockServerUrl
  2994. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2995. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2996. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2997. }
  2998. /******************************************* AHKActionSheet *******************************************/
  2999. UIImage *iconHeader;
  3000. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3001. actionSheet.animationDuration = 0.2;
  3002. actionSheet.blurRadius = 0.0f;
  3003. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3004. actionSheet.buttonHeight = 50.0;
  3005. actionSheet.cancelButtonHeight = 50.0f;
  3006. actionSheet.separatorHeight = 5.0f;
  3007. actionSheet.automaticallyTintButtonImages = @(NO);
  3008. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_ENCRYPTED };
  3009. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_GRAY };
  3010. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:COLOR_BRAND };
  3011. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:COLOR_GRAY };
  3012. actionSheet.separatorColor = COLOR_SEPARATOR_TABLE;
  3013. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3014. /******************************************* DIRECTORY *******************************************/
  3015. if (_metadata.directory) {
  3016. UIImage *iconHeader;
  3017. BOOL lockDirectory = NO;
  3018. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  3019. NSString *upDir = [CCUtility deletingLastPathComponentFromServerUrl:dirServerUrl];
  3020. NSString *homeDir = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  3021. // Directory bloccata ?
  3022. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3023. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3024. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3025. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3026. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3027. image: iconHeader
  3028. backgroundColor: COLOR_NAVBAR_IOS7
  3029. height: 50.0
  3030. type: AHKActionSheetButtonTypeDisabled
  3031. handler: nil
  3032. ];
  3033. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3034. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3035. image:[UIImage imageNamed:image_actionSheetRename]
  3036. backgroundColor:[UIColor whiteColor]
  3037. height: 50.0
  3038. type:AHKActionSheetButtonTypeDefault
  3039. handler:^(AHKActionSheet *as) {
  3040. // close swipe
  3041. [self setEditing:NO animated:YES];
  3042. //chiediamo il nome del file
  3043. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3044. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3045. alertView.tag = alertRename;
  3046. UITextField *textField = [alertView textFieldAtIndex:0];
  3047. textField.text = _metadata.fileNamePrint;
  3048. [alertView show];
  3049. }];
  3050. }
  3051. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3052. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3053. image:[UIImage imageNamed:image_actionSheetMove]
  3054. backgroundColor:[UIColor whiteColor]
  3055. height: 50.0
  3056. type:AHKActionSheetButtonTypeDefault
  3057. handler:^(AHKActionSheet *as) {
  3058. // close swipe
  3059. [self setEditing:NO animated:YES];
  3060. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3061. }];
  3062. }
  3063. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3064. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3065. image:[UIImage imageNamed:image_actionSheetCrypto]
  3066. backgroundColor:[UIColor whiteColor]
  3067. height: 50.0
  3068. type:AHKActionSheetButtonTypeEncrypted
  3069. handler:^(AHKActionSheet *as) {
  3070. // close swipe
  3071. [self setEditing:NO animated:YES];
  3072. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3073. }];
  3074. }
  3075. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3076. [actionSheet addButtonWithTitle:titoloLock
  3077. image:[UIImage imageNamed:image_actionSheetLock]
  3078. backgroundColor:[UIColor whiteColor]
  3079. height: 50.0
  3080. type:AHKActionSheetButtonTypeEncrypted
  3081. handler:^(AHKActionSheet *as) {
  3082. // close swipe
  3083. [self setEditing:NO animated:YES];
  3084. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3085. }];
  3086. }
  3087. if (_metadata.cryptated == NO && app.hasServerShareSupport && !lockDirectory) {
  3088. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3089. image:[UIImage imageNamed:image_actionSheetShare]
  3090. backgroundColor:[UIColor whiteColor]
  3091. height: 50.0
  3092. type:AHKActionSheetButtonTypeDefault
  3093. handler:^(AHKActionSheet *as) {
  3094. // close swipe
  3095. [self setEditing:NO animated:YES];
  3096. [self openWindowShare:_metadata];
  3097. }];
  3098. }
  3099. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3100. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3101. image:[UIImage imageNamed:image_folderphotocamera]
  3102. backgroundColor:[UIColor whiteColor]
  3103. height: 50.0
  3104. type:AHKActionSheetButtonTypeDefault
  3105. handler:^(AHKActionSheet *as) {
  3106. // close swipe
  3107. [self setEditing:NO animated:YES];
  3108. // Settings new folder Automatatic upload
  3109. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3110. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3111. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3112. [CCCoreData clearDateReadDirectory:oldPath activeAccount:app.activeAccount];
  3113. if (app.activeAccount && app.activeUrl && app.activePhotosCameraUpload)
  3114. [app.activePhotosCameraUpload reloadDatasourceForced];
  3115. [self readFolderWithForced:YES];
  3116. }];
  3117. }
  3118. if (!lockDirectory && ([upDir isEqualToString:homeDir] || ![CCCoreData isOfflineDirectoryServerUrl:upDir activeAccount:app.activeAccount])) {
  3119. [actionSheet addButtonWithTitle:titleOfflineFolder
  3120. image:[UIImage imageNamed:image_actionSheetOffline]
  3121. backgroundColor:[UIColor whiteColor]
  3122. height: 50.0
  3123. type:AHKActionSheetButtonTypeDefault
  3124. handler:^(AHKActionSheet *as) {
  3125. // close swipe
  3126. [self setEditing:NO animated:YES];
  3127. if (offlineFolder == NO) {
  3128. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"",nil) message:NSLocalizedString(@"_offline_folder_confirm_",nil) delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3129. alertView.tag = alertOfflineFolder;
  3130. [alertView show];
  3131. } else {
  3132. // remove tag offline for all folder/subfolder/file
  3133. NSArray *directories = [CCCoreData getOfflineDirectoryActiveAccount:app.activeAccount];
  3134. for (TableDirectory *directory in directories)
  3135. if ([directory.serverUrl containsString:dirServerUrl]) {
  3136. [CCCoreData setOfflineDirectoryServerUrl:directory.serverUrl offline:NO activeAccount:app.activeAccount];
  3137. [CCCoreData removeOfflineAllFileFromServerUrl:directory.serverUrl activeAccount:app.activeAccount];
  3138. }
  3139. [self performSelector:@selector(reloadDatasource) withObject:nil];
  3140. }
  3141. }];
  3142. }
  3143. [actionSheet show];
  3144. }
  3145. /******************************************* FILE *******************************************/
  3146. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3147. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3148. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3149. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3150. else
  3151. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3152. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3153. image: iconHeader
  3154. backgroundColor: COLOR_NAVBAR_IOS7
  3155. height: 50.0
  3156. type: AHKActionSheetButtonTypeDisabled
  3157. handler: nil
  3158. ];
  3159. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3160. image:[UIImage imageNamed:image_actionSheetRename]
  3161. backgroundColor:[UIColor whiteColor]
  3162. height: 50.0
  3163. type:AHKActionSheetButtonTypeDefault
  3164. handler:^(AHKActionSheet *as) {
  3165. // close swipe
  3166. [self setEditing:NO animated:YES];
  3167. //chiediamo il nome del file
  3168. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3169. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3170. alertView.tag = alertRename;
  3171. UITextField *textField = [alertView textFieldAtIndex:0];
  3172. textField.text = _metadata.fileNamePrint;
  3173. [alertView show];
  3174. }];
  3175. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3176. image:[UIImage imageNamed:image_actionSheetMove]
  3177. backgroundColor:[UIColor whiteColor]
  3178. height: 50.0
  3179. type:AHKActionSheetButtonTypeDefault
  3180. handler:^(AHKActionSheet *as) {
  3181. // close swipe
  3182. [self setEditing:NO animated:YES];
  3183. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3184. }];
  3185. [actionSheet addButtonWithTitle:NSLocalizedString(@"_reload_", nil)
  3186. image:[UIImage imageNamed:image_actionSheetReload]
  3187. backgroundColor:[UIColor whiteColor]
  3188. height: 50.0
  3189. type:AHKActionSheetButtonTypeDefault
  3190. handler:^(AHKActionSheet *as) {
  3191. // close swipe
  3192. [self setEditing:NO animated:YES];
  3193. [self performSelector:@selector(reloadFile:) withObject:_metadata];
  3194. }];
  3195. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3196. image:[UIImage imageNamed:image_actionSheetOpenIn]
  3197. backgroundColor:[UIColor whiteColor]
  3198. height: 50.0
  3199. type:AHKActionSheetButtonTypeDefault
  3200. handler:^(AHKActionSheet *as) {
  3201. // close swipe
  3202. [self setEditing:NO animated:YES];
  3203. [self performSelector:@selector(openIn:) withObject:_metadata];
  3204. }];
  3205. if (_metadata.cryptated == NO && app.hasServerShareSupport) {
  3206. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3207. image:[UIImage imageNamed:image_actionSheetShare]
  3208. backgroundColor:[UIColor whiteColor]
  3209. height: 50.0
  3210. type:AHKActionSheetButtonTypeDefault
  3211. handler:^(AHKActionSheet *as) {
  3212. // close swipe
  3213. [self setEditing:NO animated:YES];
  3214. [self openWindowShare:_metadata];
  3215. }];
  3216. }
  3217. if (app.isCryptoCloudMode) {
  3218. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3219. image:[UIImage imageNamed:image_actionSheetCrypto]
  3220. backgroundColor:[UIColor whiteColor]
  3221. height: 50.0
  3222. type:AHKActionSheetButtonTypeEncrypted
  3223. handler:^(AHKActionSheet *as) {
  3224. // close swipe
  3225. [self setEditing:NO animated:YES];
  3226. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3227. }];
  3228. }
  3229. [actionSheet addButtonWithTitle:titoloOffline
  3230. image:[UIImage imageNamed:image_actionSheetOffline]
  3231. backgroundColor:[UIColor whiteColor]
  3232. height: 50.0
  3233. type:AHKActionSheetButtonTypeDefault
  3234. handler:^(AHKActionSheet *as) {
  3235. // close swipe
  3236. [self setEditing:NO animated:YES];
  3237. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) {
  3238. [self removeOffline:_metadata];
  3239. } else {
  3240. [self addOffline:_metadata];
  3241. }
  3242. }];
  3243. [actionSheet addButtonWithTitle:NSLocalizedString(@"_add_local_", nil)
  3244. image:[UIImage imageNamed:image_actionSheetLocal]
  3245. backgroundColor:[UIColor whiteColor]
  3246. height: 50.0
  3247. type:AHKActionSheetButtonTypeDefault
  3248. handler:^(AHKActionSheet *as) {
  3249. // close swipe
  3250. [self setEditing:NO animated:YES];
  3251. [self performSelector:@selector(addLocal:) withObject:_metadata];
  3252. }];
  3253. [actionSheet show];
  3254. }
  3255. /******************************************* TEMPLATE *******************************************/
  3256. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3257. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3258. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3259. image: iconHeader
  3260. backgroundColor: COLOR_NAVBAR_IOS7
  3261. height: 50.0
  3262. type: AHKActionSheetButtonTypeDisabled
  3263. handler: nil
  3264. ];
  3265. if ([_metadata.model isEqualToString:@"note"]) {
  3266. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3267. image:[UIImage imageNamed:image_actionSheetRename]
  3268. backgroundColor:[UIColor whiteColor]
  3269. height: 50.0
  3270. type:AHKActionSheetButtonTypeDefault
  3271. handler:^(AHKActionSheet *as) {
  3272. // close swipe
  3273. [self setEditing:NO animated:YES];
  3274. //chiediamo il nome del file
  3275. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3276. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3277. alertView.tag = alertRename;
  3278. UITextField *textField = [alertView textFieldAtIndex:0];
  3279. textField.text = _metadata.fileNamePrint;
  3280. [alertView show];
  3281. }];
  3282. }
  3283. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3284. image:[UIImage imageNamed:image_actionSheetMove]
  3285. backgroundColor:[UIColor whiteColor]
  3286. height: 50.0
  3287. type:AHKActionSheetButtonTypeDefault
  3288. handler:^(AHKActionSheet *as) {
  3289. // close swipe
  3290. [self setEditing:NO animated:YES];
  3291. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3292. }];
  3293. [actionSheet addButtonWithTitle:titoloOffline
  3294. image:[UIImage imageNamed:image_actionSheetOffline]
  3295. backgroundColor:[UIColor whiteColor]
  3296. height: 50.0
  3297. type:AHKActionSheetButtonTypeDefault
  3298. handler:^(AHKActionSheet *as) {
  3299. // close swipe
  3300. [self setEditing:NO animated:YES];
  3301. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount])
  3302. [self removeOffline:_metadata];
  3303. else
  3304. [self addOffline:_metadata];
  3305. }];
  3306. [actionSheet addButtonWithTitle:NSLocalizedString(@"_add_local_", nil)
  3307. image:[UIImage imageNamed:image_actionSheetLocal]
  3308. backgroundColor:[UIColor whiteColor]
  3309. height: 50.0
  3310. type:AHKActionSheetButtonTypeDefault
  3311. handler:^(AHKActionSheet *as) {
  3312. // close swipe
  3313. [self setEditing:NO animated:YES];
  3314. [self performSelector:@selector(addLocal:) withObject:_metadata];
  3315. }];
  3316. [actionSheet show];
  3317. }
  3318. }
  3319. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3320. {
  3321. return NSLocalizedString(@"_delete_", nil);
  3322. }
  3323. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3324. {
  3325. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3326. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3327. else return YES;
  3328. }
  3329. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3330. {
  3331. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3332. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3333. else return UITableViewCellEditingStyleDelete;
  3334. }
  3335. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3336. {
  3337. BOOL lockDirectory = NO;
  3338. // Directory locked ?
  3339. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addServerUrl:_metadata.fileNameData];
  3340. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3341. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3342. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  3343. return;
  3344. }
  3345. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3346. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3347. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3348. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3349. style:UIAlertActionStyleDestructive
  3350. handler:^(UIAlertAction *action) {
  3351. [self performSelector:@selector(deleteFile) withObject:nil];
  3352. }]];
  3353. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3354. style:UIAlertActionStyleCancel
  3355. handler:^(UIAlertAction *action) {
  3356. [alertController dismissViewControllerAnimated:YES completion:nil];
  3357. }]];
  3358. alertController.popoverPresentationController.sourceView = self.view;
  3359. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3360. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3361. [alertController.view layoutIfNeeded];
  3362. [self presentViewController:alertController animated:YES completion:nil];
  3363. }
  3364. }
  3365. #pragma --------------------------------------------------------------------------------------------
  3366. #pragma mark - ==== Datasource ====
  3367. #pragma --------------------------------------------------------------------------------------------
  3368. - (void)clearDateReadDataSource:(NSNotification *)notification
  3369. {
  3370. _dateReadDataSource = Nil;
  3371. }
  3372. - (void)reloadDatasource
  3373. {
  3374. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3375. }
  3376. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3377. {
  3378. if (app.activeAccount == nil || app.activeUrl == nil || serverUrl == nil)
  3379. return;
  3380. // Search Mode
  3381. if(_isSearchMode) {
  3382. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3383. _sectionDataSource = [CCSection creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3384. } else {
  3385. [self readFolderWithForced:NO];
  3386. }
  3387. [self tableViewReload];
  3388. [self setTitleBackgroundTableView:nil];
  3389. [app updateApplicationIconBadgeNumber];
  3390. return;
  3391. }
  3392. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3393. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3394. if ([selector isEqualToString:selectorDownloadOffline]) {
  3395. [app.controlCenter reloadDatasource];
  3396. } else {
  3397. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3398. if (main) {
  3399. [main reloadDatasource];
  3400. } else {
  3401. [self tableViewReload];
  3402. [app.controlCenter reloadDatasource];
  3403. }
  3404. }
  3405. return;
  3406. }
  3407. // Offline folder ?
  3408. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3409. [app.controlCenter reloadDatasource];
  3410. // Settaggio variabili per le ottimizzazioni
  3411. _directoryGroupBy = [CCUtility getGroupBySettings];
  3412. _directoryOrder = [CCUtility getOrderSettings];
  3413. // Controllo data lettura Data Source
  3414. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3415. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3416. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3417. _dateReadDataSource = [NSDate date];
  3418. // Data Source
  3419. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3420. _sectionDataSource = [CCSection creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3421. } else {
  3422. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3423. }
  3424. [self tableViewReload];
  3425. [self setTitleBackgroundTableView];
  3426. [app updateApplicationIconBadgeNumber];
  3427. }
  3428. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3429. {
  3430. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3431. if (selectedRows.count > 0) {
  3432. for (NSIndexPath *selectionIndex in selectedRows) {
  3433. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3434. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3435. [metadatas addObject:metadata];
  3436. }
  3437. }
  3438. return metadatas;
  3439. }
  3440. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3441. {
  3442. NSInteger section = indexPath.section + 1;
  3443. NSInteger row = indexPath.row + 1;
  3444. NSInteger totSections =[_sectionDataSource.sections count] ;
  3445. if ((totSections < section) || (section > totSections)) {
  3446. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3447. return nil;
  3448. }
  3449. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3450. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3451. if (fileIDs) {
  3452. NSInteger totRows =[fileIDs count] ;
  3453. if ((totRows < row) || (row > totRows)) {
  3454. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3455. return nil;
  3456. }
  3457. } else {
  3458. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3459. return nil;
  3460. }
  3461. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3462. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3463. }
  3464. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3465. {
  3466. NSInteger totSections =[_sectionDataSource.sections count] ;
  3467. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3468. #if DEBUG
  3469. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3470. [alertView show];
  3471. #endif
  3472. return nil;
  3473. }
  3474. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3475. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3476. }
  3477. #pragma --------------------------------------------------------------------------------------------
  3478. #pragma mark - ==== Table ====
  3479. #pragma --------------------------------------------------------------------------------------------
  3480. - (void)tableViewSelect:(BOOL)edit
  3481. {
  3482. // chiudiamo eventuali swipe aperti
  3483. if (edit) [self.tableView setEditing:NO animated:NO];
  3484. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3485. [self.tableView setEditing:edit animated:YES];
  3486. _isSelectedMode = edit;
  3487. if (edit)
  3488. [self setUINavigationBarSelected];
  3489. else
  3490. [self setUINavigationBarDefault];
  3491. [self setTitleNOAnimation];
  3492. }
  3493. - (void)tableViewReload
  3494. {
  3495. // ricordiamoci le row selezionate
  3496. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3497. [self.tableView reloadData];
  3498. for (NSIndexPath *path in indexPaths)
  3499. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3500. [self setTableViewFooter];
  3501. if (self.tableView.editing)
  3502. [self setTitleNOAnimation];
  3503. }
  3504. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3505. {
  3506. return 60;
  3507. }
  3508. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3509. {
  3510. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3511. }
  3512. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3513. {
  3514. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3515. }
  3516. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3517. {
  3518. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3519. NSString *sectionTitle = [sections objectAtIndex:section];
  3520. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3521. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3522. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3523. return 20.f;
  3524. }
  3525. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3526. {
  3527. float shift;
  3528. UIVisualEffectView *visualEffectView;
  3529. // Titolo
  3530. NSString *titleSection;
  3531. // Controllo
  3532. if ([_sectionDataSource.sections count] == 0)
  3533. return nil;
  3534. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3535. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3536. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3537. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3538. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3539. else titleSection = NSLocalizedString(titleSection,nil);
  3540. // Formato titolo
  3541. NSString *currentDevice = [CCUtility currentDevice];
  3542. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3543. visualEffectView = [[UIVisualEffectView alloc] init];
  3544. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  3545. } else {
  3546. UIVisualEffect *blurEffect;
  3547. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3548. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3549. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR;
  3550. }
  3551. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3552. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3553. else shift = - 20;
  3554. } else shift = - 10;
  3555. // Title
  3556. UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3557. titleLabel.backgroundColor=[UIColor clearColor];
  3558. titleLabel.textColor = COLOR_GRAY;
  3559. titleLabel.font = [UIFont systemFontOfSize:12];
  3560. titleLabel.textAlignment = NSTextAlignmentLeft;
  3561. titleLabel.text = titleSection;
  3562. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3563. [visualEffectView addSubview:titleLabel];
  3564. // Elements
  3565. UILabel *elementLabel=[[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3566. elementLabel.backgroundColor=[UIColor clearColor];
  3567. elementLabel.textColor = COLOR_GRAY;
  3568. elementLabel.font = [UIFont systemFontOfSize:12];
  3569. elementLabel.textAlignment = NSTextAlignmentRight;
  3570. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3571. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3572. NSUInteger rowsCount = [metadatas count];
  3573. if (rowsCount == 0) return nil;
  3574. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3575. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3576. [visualEffectView addSubview:elementLabel];
  3577. return visualEffectView;
  3578. }
  3579. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3580. {
  3581. return [_sectionDataSource.sections indexOfObject:title];
  3582. }
  3583. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3584. {
  3585. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3586. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3587. else
  3588. return nil;
  3589. }
  3590. /*
  3591. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3592. {
  3593. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3594. }
  3595. }
  3596. */
  3597. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3598. {
  3599. NSString *typeCell;
  3600. NSString *dataFile;
  3601. NSString *lunghezzaFile;
  3602. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3603. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3604. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3605. else typeCell = @"CellMainTransfer";
  3606. if (!metadata)
  3607. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3608. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3609. // separator
  3610. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3611. // change color selection
  3612. UIView *selectionColor = [[UIView alloc] init];
  3613. selectionColor.backgroundColor = COLOR_SELECT_BACKGROUND;
  3614. cell.selectedBackgroundView = selectionColor;
  3615. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3616. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = COLOR_TRANSFER_BACKGROUND;
  3617. // ----------------------------------------------------------------------------------------------------------
  3618. // DEFAULT
  3619. // ----------------------------------------------------------------------------------------------------------
  3620. cell.fileImageView.image = nil;
  3621. cell.statusImageView.image = nil;
  3622. cell.offlineImageView.image = nil;
  3623. cell.synchronizedImageView.image = nil;
  3624. cell.sharedImageView.image = nil;
  3625. cell.labelTitle.enabled = YES;
  3626. cell.labelTitle.text = @"";
  3627. cell.labelInfoFile.enabled = YES;
  3628. cell.labelInfoFile.text = @"";
  3629. cell.progressView.progress = 0.0;
  3630. cell.progressView.hidden = YES;
  3631. cell.cancelTaskButton.hidden = YES;
  3632. cell.reloadTaskButton.hidden = YES;
  3633. cell.stopTaskButton.hidden = YES;
  3634. // colori e font
  3635. if (metadata.cryptated) {
  3636. cell.labelTitle.textColor = COLOR_ENCRYPTED;
  3637. cell.labelInfoFile.textColor = [UIColor blackColor];
  3638. } else {
  3639. cell.labelTitle.textColor = COLOR_CLEAR;
  3640. cell.labelInfoFile.textColor = [UIColor blackColor];
  3641. }
  3642. // ----------------------------------------------------------------------------------------------------------
  3643. // File Name & Folder
  3644. // ----------------------------------------------------------------------------------------------------------
  3645. // nome del file
  3646. cell.labelTitle.text = metadata.fileNamePrint;
  3647. // è una directory
  3648. if (metadata.directory) {
  3649. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3650. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3651. lunghezzaFile = @" ";
  3652. // ----------------------------------------------------------------------------------------------------------
  3653. // Offline Folder
  3654. // ----------------------------------------------------------------------------------------------------------
  3655. NSString *directoryServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:metadata.fileNameData];
  3656. BOOL isOfflineDirectory = [CCCoreData isOfflineDirectoryServerUrl:directoryServerUrl activeAccount:app.activeAccount];
  3657. // Verify Offline
  3658. if (_isOfflineServerUrl == YES && isOfflineDirectory == NO) {
  3659. [CCCoreData setOfflineDirectoryServerUrl:directoryServerUrl offline:YES activeAccount:app.activeAccount];
  3660. isOfflineDirectory = YES;
  3661. }
  3662. if (isOfflineDirectory) {
  3663. // Image Offline
  3664. if (metadata.cryptated) cell.offlineImageView.image = [UIImage imageNamed:image_offlinecrypto];
  3665. else cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3666. // Animation synchronized gif
  3667. if ([[CCOfflineFileFolder sharedOfflineFileFolder] offlineFolderAnimationDirectory:[[NSArray alloc] initWithObjects:directoryServerUrl, nil] callViewController:NO]) {
  3668. NSURL *myURL;
  3669. if (metadata.cryptated) myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3670. else myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3671. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  3672. }
  3673. }
  3674. } else {
  3675. // è un file
  3676. dataFile = [CCUtility dateDiff:metadata.date];
  3677. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3678. // Plist ancora da scaricare
  3679. if (metadata.cryptated && [metadata.title length] == 0) {
  3680. dataFile = @" ";
  3681. lunghezzaFile = @" ";
  3682. }
  3683. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3684. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3685. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3686. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3687. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3688. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3689. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3690. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3691. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3692. else
  3693. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3694. }
  3695. // Plist ancora da scaricare
  3696. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3697. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3698. cell.accessoryType = UITableViewCellAccessoryNone;
  3699. }
  3700. // ----------------------------------------------------------------------------------------------------------
  3701. // File Image View
  3702. // ----------------------------------------------------------------------------------------------------------
  3703. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3704. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3705. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3706. if (cell.fileImageView.image == nil) {
  3707. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3708. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3709. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3710. dispatch_async(dispatch_get_main_queue(), ^{
  3711. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3712. if (cell)
  3713. cell.fileImageView.image = image;
  3714. });
  3715. });
  3716. }
  3717. } else {
  3718. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3719. if (metadata.thumbnailExists)
  3720. [self downloadThumbnail:metadata];
  3721. }
  3722. // ----------------------------------------------------------------------------------------------------------
  3723. // Image Status cyptated & Lock Passcode
  3724. // ----------------------------------------------------------------------------------------------------------
  3725. // File Cyptated
  3726. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3727. cell.statusImageView.image = [UIImage imageNamed:image_lock];
  3728. }
  3729. // Directory con passcode lock attivato
  3730. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:metadata.fileNameData];
  3731. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length])) cell.statusImageView.image = [UIImage imageNamed:image_passcode];
  3732. // ----------------------------------------------------------------------------------------------------------
  3733. // Offline
  3734. // ----------------------------------------------------------------------------------------------------------
  3735. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3736. if (isOfflineFile) {
  3737. if (metadata.cryptated) cell.offlineImageView.image = [UIImage imageNamed:image_offlinecrypto];
  3738. else cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3739. }
  3740. // ----------------------------------------------------------------------------------------------------------
  3741. // Share
  3742. // ----------------------------------------------------------------------------------------------------------
  3743. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3744. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3745. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3746. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3747. // Aggiungiamo il Tap per le shared
  3748. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3749. if (isShare) {
  3750. cell.sharedImageView.image = [UIImage imageNamed:image_shareConnect];
  3751. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3752. [tap setNumberOfTapsRequired:1];
  3753. cell.sharedImageView.userInteractionEnabled = YES;
  3754. [cell.sharedImageView addGestureRecognizer:tap];
  3755. }
  3756. if (isMounted) {
  3757. cell.sharedImageView.image = [UIImage imageNamed:image_shareMounted];
  3758. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3759. [tap setNumberOfTapsRequired:1];
  3760. cell.sharedImageView.userInteractionEnabled = YES;
  3761. [cell.sharedImageView addGestureRecognizer:tap];
  3762. }
  3763. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3764. if ([shareLink length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareLink];
  3765. if ([shareUserAndGroup length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareUser];
  3766. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3767. [tap setNumberOfTapsRequired:1];
  3768. cell.sharedImageView.userInteractionEnabled = YES;
  3769. [cell.sharedImageView addGestureRecognizer:tap];
  3770. }
  3771. } else {
  3772. cell.sharedImageView.userInteractionEnabled = NO;
  3773. }
  3774. // ----------------------------------------------------------------------------------------------------------
  3775. // downloadFile
  3776. // ----------------------------------------------------------------------------------------------------------
  3777. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3778. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusdownloadcrypto];
  3779. else cell.statusImageView.image = [UIImage imageNamed:image_statusdownload];
  3780. // sessionTaskIdentifier : RELOAD + STOP
  3781. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3782. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3783. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3784. cell.cancelTaskButton.hidden = NO;
  3785. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3786. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3787. cell.reloadTaskButton.hidden = NO;
  3788. }
  3789. // sessionTaskIdentifierPlist : RELOAD
  3790. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3791. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3792. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3793. cell.reloadTaskButton.hidden = NO;
  3794. }
  3795. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3796. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3797. if (progress > 0) {
  3798. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_ENCRYPTED;
  3799. else cell.progressView.progressTintColor = COLOR_CLEAR;
  3800. cell.progressView.progress = progress;
  3801. cell.progressView.hidden = NO;
  3802. }
  3803. // ----------------------------------------------------------------------------------------------------------
  3804. // downloadFile Error
  3805. // ----------------------------------------------------------------------------------------------------------
  3806. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3807. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3808. if ([metadata.sessionError length] == 0)
  3809. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3810. else
  3811. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3812. }
  3813. }
  3814. // ----------------------------------------------------------------------------------------------------------
  3815. // uploadFile
  3816. // ----------------------------------------------------------------------------------------------------------
  3817. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3818. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusuploadcrypto];
  3819. else cell.statusImageView.image = [UIImage imageNamed:image_statusupload];
  3820. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetaskcrypto] forState:UIControlStateNormal];
  3821. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetask] forState:UIControlStateNormal];
  3822. cell.cancelTaskButton.hidden = NO;
  3823. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3824. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3825. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3826. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusstopcrypto];
  3827. else cell.statusImageView.image = [UIImage imageNamed:image_statusstop];
  3828. cell.reloadTaskButton.hidden = NO;
  3829. cell.stopTaskButton.hidden = YES;
  3830. } else {
  3831. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3832. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3833. cell.stopTaskButton.hidden = NO;
  3834. cell.reloadTaskButton.hidden = YES;
  3835. }
  3836. // se non c'è una preview in bianconero metti l'immagine di default
  3837. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3838. cell.fileImageView.image = [UIImage imageNamed:image_uploaddisable];
  3839. cell.labelTitle.enabled = NO;
  3840. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3841. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3842. if (progress > 0) {
  3843. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_ENCRYPTED;
  3844. else cell.progressView.progressTintColor = COLOR_CLEAR;
  3845. cell.progressView.progress = progress;
  3846. cell.progressView.hidden = NO;
  3847. }
  3848. // ----------------------------------------------------------------------------------------------------------
  3849. // uploadFileError
  3850. // ----------------------------------------------------------------------------------------------------------
  3851. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3852. cell.labelTitle.enabled = NO;
  3853. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3854. if ([metadata.sessionError length] == 0)
  3855. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3856. else
  3857. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3858. }
  3859. }
  3860. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3861. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3862. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3863. return cell;
  3864. }
  3865. - (void)setTableViewFooter
  3866. {
  3867. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3868. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3869. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3870. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3871. UIFont *appFont = [UIFont systemFontOfSize:12];
  3872. footerLabel.font = appFont;
  3873. footerLabel.textColor = [UIColor grayColor];
  3874. footerLabel.backgroundColor = [UIColor clearColor];
  3875. footerLabel.textAlignment = NSTextAlignmentCenter;
  3876. NSString *folders;
  3877. NSString *files;
  3878. NSString *footerText;
  3879. if (_sectionDataSource.directories > 1) {
  3880. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3881. } else if (_sectionDataSource.directories == 1){
  3882. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3883. } else {
  3884. folders = @"";
  3885. }
  3886. if (_sectionDataSource.files > 1) {
  3887. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3888. } else if (_sectionDataSource.files == 1){
  3889. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3890. } else {
  3891. files = @"";
  3892. }
  3893. if ([folders isEqualToString:@""]) {
  3894. footerText = files;
  3895. } else if ([files isEqualToString:@""]) {
  3896. footerText = folders;
  3897. } else {
  3898. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3899. }
  3900. footerLabel.text = footerText;
  3901. [footerView addSubview:footerLabel];
  3902. [self.tableView setTableFooterView:footerView];
  3903. }
  3904. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3905. {
  3906. NSString *textMessage;
  3907. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3908. // se non può essere selezionata deseleziona
  3909. if ([cell isEditing] == NO)
  3910. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3911. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3912. if (self.tableView.editing) {
  3913. [self setTitleNOAnimation];
  3914. return;
  3915. }
  3916. // test crash
  3917. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3918. if (indexPath.row >= [metadatas count]) return;
  3919. // settiamo il record file.
  3920. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3921. //
  3922. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3923. // se è in corso una sessione
  3924. if ([_metadata.session length] > 0) return;
  3925. if (_metadata.errorPasscode) {
  3926. // se UUID è nil lo sta ancora caricando quindi esci
  3927. if (!_metadata.uuid) return;
  3928. // esiste un hint ??
  3929. CCCrypto *crypto = [[CCCrypto alloc] init];
  3930. NSString *hint = [crypto getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3931. // qui !! la richiesta della nuova passcode
  3932. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3933. // stesso UUID ... la password è stata modificata !!!!!!
  3934. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3935. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3936. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3937. [alertView show];
  3938. } else {
  3939. // UUID diverso.
  3940. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3941. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3942. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3943. [alertView show];
  3944. }
  3945. // chiediamo la passcode e ricarichiamo tutto.
  3946. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3947. viewController.delegate = self;
  3948. viewController.fromType = CCBKPasscodeFromPasscode;
  3949. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3950. viewController.passcodeInputView.maximumLength = 64;
  3951. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3952. viewController.inputViewTitlePassword = NO;
  3953. viewController.title = _brand_;
  3954. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3955. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_ENCRYPTED;
  3956. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3957. [self presentViewController:navigationController animated:YES completion:nil];
  3958. }
  3959. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3960. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3961. NSString* selector;
  3962. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3963. else selector = selectorLoadPlist;
  3964. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3965. return;
  3966. }
  3967. // se il plist è caricato ed è un modello aprilo
  3968. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3969. // file
  3970. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3971. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3972. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3973. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3974. } else {
  3975. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3976. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3977. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3978. }
  3979. }
  3980. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3981. }
  3982. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3983. {
  3984. [self setTitleNOAnimation];
  3985. }
  3986. #pragma --------------------------------------------------------------------------------------------
  3987. #pragma mark ===== Offline Folder Cell =====
  3988. #pragma --------------------------------------------------------------------------------------------
  3989. - (void)offlineFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3990. {
  3991. BOOL cryptated = NO;
  3992. CCCellMain *cell;
  3993. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3994. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3995. if (recordMetadata.directory == NO)
  3996. continue;
  3997. if ([[CCUtility stringAppendServerUrl:_serverUrl addServerUrl:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3998. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3999. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  4000. cryptated = recordMetadata.cryptated;
  4001. break;
  4002. }
  4003. }
  4004. if (!cell)
  4005. return;
  4006. if (animation) {
  4007. NSURL *myURL;
  4008. if (cryptated)
  4009. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4010. else
  4011. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4012. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  4013. } else {
  4014. cell.synchronizedImageView.image = nil;
  4015. }
  4016. }
  4017. #pragma --------------------------------------------------------------------------------------------
  4018. #pragma mark ===== Navigation ====
  4019. #pragma --------------------------------------------------------------------------------------------
  4020. - (BOOL)shouldPerformSegue:(NSString *)serverUrl
  4021. {
  4022. // if background return
  4023. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4024. // se non siamo in primo piano o se non siamo nella stessa directory esci
  4025. if (self.view.window == NO || ([serverUrl isEqualToString:_serverUrl] == NO && serverUrl))
  4026. return NO;
  4027. // Collapsed ma siamo già in detail esci
  4028. if (self.splitViewController.isCollapsed)
  4029. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4030. // Video in esecuzione esci
  4031. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4032. return YES;
  4033. }
  4034. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4035. {
  4036. id viewController = segue.destinationViewController;
  4037. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4038. UINavigationController *nav = viewController;
  4039. _detailViewController = (CCDetail *)nav.topViewController;
  4040. } else {
  4041. _detailViewController = segue.destinationViewController;
  4042. }
  4043. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  4044. for (NSString *fileID in _sectionDataSource.allFileID) {
  4045. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4046. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4047. [allRecordsDataSourceImagesVideos addObject:metadata];
  4048. }
  4049. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4050. _detailViewController.metadataDetail = _metadataSegue;
  4051. _detailViewController.dateFilterQuery = nil;
  4052. _detailViewController.isCameraUpload = NO;
  4053. [_detailViewController setTitle:_metadata.fileNamePrint];
  4054. }
  4055. // can i go to next viewcontroller
  4056. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4057. {
  4058. NSString *nomeDir;
  4059. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4060. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4061. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  4062. // 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
  4063. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4064. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4065. viewController.delegate = self;
  4066. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4067. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4068. viewController.inputViewTitlePassword = YES;
  4069. if ([CCUtility getSimplyBlockCode]) {
  4070. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4071. viewController.passcodeInputView.maximumLength = 6;
  4072. } else {
  4073. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4074. viewController.passcodeInputView.maximumLength = 64;
  4075. }
  4076. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  4077. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4078. viewController.touchIDManager = touchIDManager;
  4079. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4080. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4081. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_ENCRYPTED;
  4082. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4083. [self presentViewController:navController animated:YES completion:nil];
  4084. return;
  4085. }
  4086. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4087. else nomeDir = _metadata.fileName;
  4088. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:nomeDir];
  4089. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4090. if (viewController.isViewLoaded == false) {
  4091. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4092. viewController.isFolderEncrypted = _metadata.cryptated;
  4093. viewController.serverUrl = serverUrlPush;
  4094. viewController.titleMain = _metadata.fileNamePrint;
  4095. viewController.textBackButton = _titleMain;
  4096. // save self
  4097. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4098. }
  4099. // OFF SearchBar
  4100. [viewController cancelSearchBar];
  4101. [self.navigationController pushViewController:viewController animated:YES];
  4102. }
  4103. }
  4104. @end