CCMain.m 249 KB

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