CCMain.m 235 KB

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