CCMain.m 250 KB

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