CCMain.m 260 KB

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