CCMain.m 249 KB

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