CCMain.m 259 KB

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