CCMain.m 259 KB

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