CCMain.m 252 KB

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