CCMain.m 237 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535
  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. #ifdef DEBUG
  877. // Get End-To-End PrivateKey (if enabled)
  878. if (capabilities.isEndToEndEncryptionEnabled) {
  879. if ([CCUtility isEndToEndEnabled:app.activeAccount]) {
  880. // Activity
  881. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"Encryption E2E available" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  882. } else {
  883. // Initialize
  884. [self initEndToEnd];
  885. }
  886. }
  887. #endif
  888. }
  889. #pragma mark -
  890. #pragma --------------------------------------------------------------------------------------------
  891. #pragma mark ==== Request Server Information ====
  892. #pragma --------------------------------------------------------------------------------------------
  893. - (void)requestServerCapabilities
  894. {
  895. // test
  896. if (app.activeAccount.length == 0)
  897. return;
  898. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  899. metadataNet.action = actionGetCapabilities;
  900. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  901. }
  902. #pragma mark -
  903. #pragma --------------------------------------------------------------------------------------------
  904. #pragma mark ==== Middleware Ping ====
  905. #pragma --------------------------------------------------------------------------------------------
  906. - (void)middlewarePing
  907. {
  908. // test
  909. if (app.activeAccount.length == 0)
  910. return;
  911. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  912. metadataNet.action = actionMiddlewarePing;
  913. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  914. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  915. }
  916. #pragma mark -
  917. #pragma --------------------------------------------------------------------------------------------
  918. #pragma mark ==== End-to-End Encryption ====
  919. #pragma --------------------------------------------------------------------------------------------
  920. // ++++++++++++++++++++++ INITIALIZE ++++++++++++++++++++++
  921. - (void)initEndToEnd
  922. {
  923. // request keys to server
  924. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  925. metadataNet.action = actionGetEndToEndPublicKeys;
  926. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  927. metadataNet.action = actionGetEndToEndPrivateKeyCipher;
  928. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  929. metadataNet.action = actionGetEndToEndServerPublicKey;
  930. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  931. }
  932. // ++++++++++++++++++++++ PUBLIC KEYS (SIGN) ++++++++++++++++++++++
  933. - (void)getEndToEndPublicKeysSuccess:(CCMetadataNet *)metadataNet
  934. {
  935. // store key locally keychain
  936. [CCUtility setEndToEndPublicKeySign:app.activeAccount publicKey:metadataNet.key];
  937. // Activity
  938. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"E2E PublicKeys present on Server and stored to keychain" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  939. }
  940. - (void)getEndToEndPublicKeysFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  941. {
  942. switch (errorCode) {
  943. case 400:
  944. message = @"bad request: unpredictable internal error";
  945. [app messageNotification:@"E2E public keys" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  946. break;
  947. case 404: {
  948. // remove keychain
  949. [CCUtility setEndToEndPublicKeySign:app.activeAccount publicKey:nil];
  950. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  951. NSString *publicKey = [[NCEndToEndEncryption sharedManager] createEndToEndPublicKey:app.activeUserID directoryUser:app.directoryUser];
  952. if (publicKey) {
  953. metadataNet.action = actionSignEndToEndPublicKey;
  954. metadataNet.key = publicKey;
  955. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  956. } else {
  957. // Activity
  958. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"E2E Error to create PublicKeyEncoded" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  959. }
  960. message = @"public keys couldn't be found";
  961. }
  962. break;
  963. case 409:
  964. message = @"forbidden: the user can't access the public keys";
  965. [app messageNotification:@"E2E public keys" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  966. break;
  967. default:
  968. [app messageNotification:@"E2E public keys" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  969. break;
  970. }
  971. // Activity
  972. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  973. }
  974. - (void)signEndToEndPublicKeySuccess:(CCMetadataNet *)metadataNet
  975. {
  976. // Insert CSR To Cheychain end delete
  977. NSString *publicKey = [[NCEndToEndEncryption sharedManager] getCSRFromDisk:app.directoryUser delete:YES];
  978. // OK signed key locally keychain
  979. [CCUtility setEndToEndPublicKeySign:app.activeAccount publicKey:publicKey];
  980. // Activity
  981. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"E2E PublicKey sign on Server and stored locally" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  982. }
  983. - (void)signEndToEndPublicKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  984. {
  985. [app messageNotification:@"E2E sign public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  986. // Activity
  987. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  988. }
  989. - (void)deleteEndToEndPublicKeySuccess:(CCMetadataNet *)metadataNet
  990. {
  991. [app messageNotification:@"E2E delete public key" description:@"Public key was deleted" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  992. }
  993. - (void)deleteEndToEndPublicKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  994. {
  995. [app messageNotification:@"E2E delete public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  996. }
  997. // ++++++++++++++++++++++ PRIVATE KEY ++++++++++++++++++++++
  998. - (void)getEndToEndPrivateKeyCipherSuccess:(CCMetadataNet *)metadataNet
  999. {
  1000. // Verify KeyPair on server
  1001. NSString *privateKey = [[NCEndToEndEncryption sharedManager] decryptPrivateKeyCipher:metadataNet.key mnemonic:k_Mnemonic_test];
  1002. if (privateKey) {
  1003. // OK privatekey locally keychain
  1004. [CCUtility setEndToEndPrivateKey:app.activeAccount privateKey:privateKey];
  1005. // Strore mnemonic locally keychain
  1006. [CCUtility setEndToEndMnemonic:app.activeAccount mnemonic:k_Mnemonic_test];
  1007. // Activity
  1008. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"E2E PrivateKey present on Server and stored to keychain" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1009. } else {
  1010. // Activity
  1011. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"E2E PrivateKey error to decrypt" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1012. }
  1013. }
  1014. - (void)getEndToEndPrivateKeyCipherFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1015. {
  1016. switch (errorCode) {
  1017. case 400:
  1018. message = @"bad request: unpredictable internal error";
  1019. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1020. break;
  1021. case 404: {
  1022. // remove keychain
  1023. [CCUtility setEndToEndPrivateKey:app.activeAccount privateKey:nil];
  1024. [CCUtility setEndToEndMnemonic:app.activeAccount mnemonic:nil];
  1025. NSString *mnemonic = [[NYMnemonic generateMnemonicString:@128 language:@"english"] stringByReplacingOccurrencesOfString:@" " withString:@""];
  1026. mnemonic = k_Mnemonic_test;
  1027. NSString *privateKeyChiper = [[NCEndToEndEncryption sharedManager] createEndToEndPrivateKey:app.activeUserID directoryUser:app.directoryUser mnemonic:mnemonic];
  1028. if (privateKeyChiper) {
  1029. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1030. metadataNet.action = actionStoreEndToEndPrivateKeyCipher;
  1031. metadataNet.key = privateKeyChiper;
  1032. metadataNet.password = mnemonic;
  1033. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1034. } else {
  1035. // Activity
  1036. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"Error to create PrivateKeyEncoded" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1037. }
  1038. message = @"private key doesn't exists";
  1039. }
  1040. break;
  1041. case 409:
  1042. message = @"forbidden: the user can't access the private key";
  1043. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1044. break;
  1045. default:
  1046. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1047. break;
  1048. }
  1049. // Activity
  1050. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1051. }
  1052. - (void)storeEndToEndPrivateKeyCipherSuccess:(CCMetadataNet *)metadataNet
  1053. {
  1054. // Insert PrivateKey To Cheychain end delete
  1055. NSString *privateKey = [[NCEndToEndEncryption sharedManager] getPrivateKeyFromDisk:app.directoryUser delete:YES];
  1056. // OK privatekey locally keychain
  1057. [CCUtility setEndToEndPrivateKey:app.activeAccount privateKey:privateKey];
  1058. // Strore mnemonic locally keychain
  1059. [CCUtility setEndToEndMnemonic:app.activeAccount mnemonic:metadataNet.password];
  1060. // Activity
  1061. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"E2E PrivateKey stored on Server and stored locally" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1062. }
  1063. - (void)storeEndToEndPrivateKeyCipherFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1064. {
  1065. [app messageNotification:@"E2E sign private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1066. // Activity
  1067. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1068. }
  1069. - (void)deleteEndToEndPrivateKeySuccess:(CCMetadataNet *)metadataNet
  1070. {
  1071. [app messageNotification:@"E2E delete private key" description:@"Private key was deleted" visible:YES delay:1 type:TWMessageBarMessageTypeSuccess errorCode:0];
  1072. }
  1073. - (void)deleteEndToEndPrivateKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1074. {
  1075. [app messageNotification:@"E2E delete private key" description:message visible:YES delay:1 type:TWMessageBarMessageTypeError errorCode:errorCode];
  1076. }
  1077. // ++++++++++++++++++++++ SERVER PUBLIC KEY ++++++++++++++++++++++
  1078. - (void)getEndToEndServerPublicKeySuccess:(CCMetadataNet *)metadataNet
  1079. {
  1080. }
  1081. - (void)getEndToEndServerPublicKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1082. {
  1083. switch (errorCode) {
  1084. case 400:
  1085. message = @"bad request: unpredictable internal error";
  1086. [app messageNotification:@"E2E Server public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1087. break;
  1088. case 404: {
  1089. message = @"private key doesn't exists";
  1090. }
  1091. break;
  1092. case 409:
  1093. message = @"forbidden: the user can't access the private key";
  1094. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1095. break;
  1096. default:
  1097. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1098. break;
  1099. }
  1100. // Activity
  1101. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1102. }
  1103. #pragma mark -
  1104. #pragma --------------------------------------------------------------------------------------------
  1105. #pragma mark ==== Download Thumbnail Delegate ====
  1106. #pragma --------------------------------------------------------------------------------------------
  1107. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1108. {
  1109. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  1110. }
  1111. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  1112. {
  1113. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  1114. if ([self indexPathIsValid:indexPath]) {
  1115. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  1116. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  1117. }
  1118. }
  1119. #pragma --------------------------------------------------------------------------------------------
  1120. #pragma mark ==== Download ====
  1121. #pragma --------------------------------------------------------------------------------------------
  1122. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1123. {
  1124. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1125. // File do not exists on server, remove in local
  1126. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1127. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1128. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1129. if (metadata.directory && serverUrl) {
  1130. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1131. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  1132. }
  1133. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1134. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1135. }
  1136. if ([selector isEqualToString:selectorLoadViewImage]) {
  1137. dispatch_async(dispatch_get_main_queue(), ^{
  1138. // Updating Detail
  1139. if (app.activeDetail)
  1140. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1141. // Updating Photos
  1142. if (app.activePhotos)
  1143. [app.activePhotos downloadFileFailure:errorCode];
  1144. });
  1145. } else {
  1146. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  1147. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1148. }
  1149. [self reloadDatasource:serverUrl];
  1150. }
  1151. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1152. {
  1153. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1154. if (metadata == nil)
  1155. return;
  1156. // Download
  1157. if ([selector isEqualToString:selectorDownloadFile]) {
  1158. [self reloadDatasource:serverUrl];
  1159. }
  1160. // Synchronized
  1161. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1162. [self reloadDatasource:serverUrl];
  1163. }
  1164. // add Favorite
  1165. if ([selector isEqualToString:selectorAddFavorite]) {
  1166. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1167. }
  1168. // open View File
  1169. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1170. [self reloadDatasource:serverUrl];
  1171. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1172. selector = selectorOpenIn;
  1173. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1174. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1175. selector = selectorOpenIn;
  1176. } else {
  1177. _metadata = metadata;
  1178. if ([self shouldPerformSegue])
  1179. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1180. }
  1181. }
  1182. // Open with...
  1183. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1184. [self reloadDatasource:serverUrl];
  1185. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1186. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1187. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName]];
  1188. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1189. _docController.delegate = self;
  1190. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1191. }
  1192. // Save to Photo Album
  1193. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1194. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1195. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1196. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1197. if (image)
  1198. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1199. else
  1200. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1201. }
  1202. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1203. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1204. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName])) {
  1205. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1206. } else {
  1207. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1208. }
  1209. }
  1210. [self reloadDatasource:serverUrl];
  1211. }
  1212. // Copy File
  1213. if ([selector isEqualToString:selectorLoadCopy]) {
  1214. [self reloadDatasource:serverUrl];
  1215. [self copyFileToPasteboard:metadata];
  1216. }
  1217. //download file plist
  1218. if ([selector isEqualToString:selectorLoadPlist]) {
  1219. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1220. long countSelectorLoadPlist = 0;
  1221. for (NSOperation *operation in [app.netQueue operations]) {
  1222. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1223. countSelectorLoadPlist++;
  1224. }
  1225. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1226. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1227. dispatch_async(dispatch_get_main_queue(), ^{
  1228. [self reloadDatasource:serverUrl];
  1229. });
  1230. }
  1231. });
  1232. }
  1233. //selectorLoadViewImage
  1234. if ([selector isEqualToString:selectorLoadViewImage]) {
  1235. // Detail
  1236. if (app.activeDetail)
  1237. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1238. // Photos
  1239. if (app.activePhotos)
  1240. [app.activePhotos downloadFileSuccess:metadata];
  1241. [self reloadDatasource:serverUrl];
  1242. }
  1243. // if exists postselector call self with selectorPost
  1244. if ([selectorPost length] > 0)
  1245. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1246. // Auto Download Upload
  1247. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1248. // ONLY BACKGROUND
  1249. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1250. } else {
  1251. // ONLY FOREFROUND
  1252. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1253. }
  1254. }
  1255. - (void)downloadSelectedFilesFolders
  1256. {
  1257. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1258. return;
  1259. NSLog(@"[LOG] Start download selected ...");
  1260. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1261. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1262. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1263. for (tableMetadata *metadata in selectedMetadatas) {
  1264. if (metadata.directory) {
  1265. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1266. if (serverUrl) {
  1267. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1268. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1269. }
  1270. } else {
  1271. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1272. }
  1273. }
  1274. [_hud hideHud];
  1275. });
  1276. [self tableViewSelect:NO];
  1277. }
  1278. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1279. {
  1280. }
  1281. #pragma --------------------------------------------------------------------------------------------
  1282. #pragma mark ===== Upload new Photos/Videos =====
  1283. #pragma --------------------------------------------------------------------------------------------
  1284. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1285. {
  1286. // Auto Download Upload
  1287. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1288. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1289. // Change priority Auto Upload
  1290. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1291. // Activity
  1292. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1293. }
  1294. if (errorCode != kCFURLErrorCancelled)
  1295. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1296. } else {
  1297. // Delete record on Table Auto Upload
  1298. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1299. // Activity
  1300. [[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];
  1301. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1302. }
  1303. } else {
  1304. // Read File test do not exists
  1305. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1306. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1307. // reUpload
  1308. if (metadata)
  1309. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1310. }
  1311. // Print error
  1312. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1313. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1314. }
  1315. }
  1316. [self reloadDatasource:serverUrl];
  1317. }
  1318. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1319. {
  1320. // Auto Download Upload
  1321. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1322. // ONLY BACKGROUND
  1323. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1324. } else {
  1325. // ONLY FOREFROUND
  1326. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1327. }
  1328. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1329. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1330. [self readFolder:serverUrl];
  1331. } else {
  1332. [self reloadDatasource:serverUrl];
  1333. }
  1334. });
  1335. }
  1336. //
  1337. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1338. //
  1339. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1340. {
  1341. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1342. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1343. });
  1344. }
  1345. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1346. {
  1347. NSArray *assets = [arguments objectAtIndex:0];
  1348. NSString *serverUrl = [arguments objectAtIndex:1];
  1349. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1350. NSString *session = [arguments objectAtIndex:3];
  1351. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1352. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1353. if (!directoryID) return;
  1354. // if request create the folder for Photos & the subfolders
  1355. if ([autoUploadPath isEqualToString:serverUrl])
  1356. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1357. return;
  1358. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1359. for (PHAsset *asset in assets) {
  1360. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1361. NSDate *assetDate = asset.creationDate;
  1362. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1363. // Create serverUrl if use sub folder
  1364. if (useSubFolder) {
  1365. [formatter setDateFormat:@"yyyy"];
  1366. NSString *yearString = [formatter stringFromDate:assetDate];
  1367. [formatter setDateFormat:@"MM"];
  1368. NSString *monthString = [formatter stringFromDate:assetDate];
  1369. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1370. }
  1371. // Check if is in upload
  1372. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1373. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1374. if ([isRecordInSessions count] > 0) {
  1375. // next upload
  1376. continue;
  1377. } else {
  1378. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1379. metadataNet.action = actionReadFile;
  1380. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1381. metadataNet.fileName = fileName;
  1382. metadataNet.session = session;
  1383. metadataNet.selector = selectorReadFileUploadFile;
  1384. metadataNet.serverUrl = serverUrl;
  1385. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1386. }
  1387. }
  1388. }
  1389. #pragma --------------------------------------------------------------------------------------------
  1390. #pragma mark ==== Read File ====
  1391. #pragma --------------------------------------------------------------------------------------------
  1392. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1393. {
  1394. // Unauthorized
  1395. if (errorCode == kOCErrorServerUnauthorized)
  1396. [app openLoginView:self loginType:loginModifyPasswordUser];
  1397. // UploadFile
  1398. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1399. // File not exists
  1400. if (errorCode == 404) {
  1401. metadataNet.errorCode = 0;
  1402. metadataNet.selector = selectorUploadFile;
  1403. metadataNet.selectorPost = nil;
  1404. metadataNet.taskStatus = k_taskStatusResume;
  1405. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1406. } else {
  1407. // error ho many retry befor notification and go to on next asses
  1408. if (metadataNet.errorRetry < 3) {
  1409. // Retry read file
  1410. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1411. } else {
  1412. // STOP check file, view message error
  1413. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1414. }
  1415. }
  1416. }
  1417. }
  1418. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1419. {
  1420. // Read Folder
  1421. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1422. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1423. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1424. [self readFolder:metadataNet.serverUrl];
  1425. }
  1426. }
  1427. // UploadFile
  1428. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1429. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1430. metadataNet.selector = selectorUploadFile;
  1431. metadataNet.selectorPost = nil;
  1432. metadataNet.taskStatus = k_taskStatusResume;
  1433. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1434. }
  1435. }
  1436. - (void)readFileReloadFolder
  1437. {
  1438. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1439. return;
  1440. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1441. metadataNet.action = actionReadFile;
  1442. metadataNet.priority = NSOperationQueuePriorityHigh;
  1443. metadataNet.selector = selectorReadFileReloadFolder;
  1444. metadataNet.serverUrl = _serverUrl;
  1445. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1446. }
  1447. #pragma --------------------------------------------------------------------------------------------
  1448. #pragma mark ==== Read Folder ====
  1449. #pragma --------------------------------------------------------------------------------------------
  1450. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1451. {
  1452. // stoprefresh
  1453. [_refreshControl endRefreshing];
  1454. // Unauthorized
  1455. if (errorCode == kOCErrorServerUnauthorized)
  1456. [app openLoginView:self loginType:loginModifyPasswordUser];
  1457. _loadingFolder = NO;
  1458. [self tableViewReloadData];
  1459. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1460. // verify active user
  1461. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1462. if (message && [record.account isEqualToString:metadataNet.account])
  1463. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1464. [self reloadDatasource:metadataNet.serverUrl];
  1465. }
  1466. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1467. {
  1468. // stoprefresh
  1469. [_refreshControl endRefreshing];
  1470. // verify active user
  1471. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1472. if (![record.account isEqualToString:metadataNet.account])
  1473. return;
  1474. // save father e update permission
  1475. if(!_isSearchMode && metadataFolder)
  1476. _fatherPermission = metadataFolder.permissions;
  1477. NSArray *recordsInSessions;
  1478. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1479. if (_isSearchMode) {
  1480. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1481. } else {
  1482. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1483. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1484. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1485. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1486. }
  1487. for (tableMetadata *metadata in metadatas) {
  1488. // verify if the record is in download/upload progress
  1489. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1490. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1491. // is in Download or Upload
  1492. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1493. continue;
  1494. }
  1495. }
  1496. // Insert in Array
  1497. [metadatasToInsertInDB addObject:metadata];
  1498. }
  1499. // insert in Database
  1500. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1501. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1502. // read plist
  1503. if (!_isSearchMode)
  1504. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1505. // File is changed ??
  1506. if (!_isSearchMode && metadatasToInsertInDB)
  1507. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1508. });
  1509. // Search Mode
  1510. if (_isSearchMode) {
  1511. // Fix managed -> Unmanaged _searchResultMetadatas
  1512. if (metadatasToInsertInDB)
  1513. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1514. [self reloadDatasource:metadataNet.serverUrl];
  1515. }
  1516. // this is the same directory
  1517. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1518. // reload
  1519. [self reloadDatasource:metadataNet.serverUrl];
  1520. // Enable change user
  1521. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1522. _loadingFolder = NO;
  1523. [self tableViewReloadData];
  1524. }
  1525. }
  1526. - (void)readFolder:(NSString *)serverUrl
  1527. {
  1528. // init control
  1529. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1530. [_refreshControl endRefreshing];
  1531. return;
  1532. }
  1533. // Search Mode
  1534. if (_isSearchMode) {
  1535. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1536. _searchFileName = @""; // forced reload searchg
  1537. [self updateSearchResultsForSearchController:self.searchController];
  1538. return;
  1539. }
  1540. _loadingFolder = YES;
  1541. [self tableViewReloadData];
  1542. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1543. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1544. metadataNet.action = actionReadFolder;
  1545. metadataNet.date = [NSDate date];
  1546. metadataNet.depth = @"1";
  1547. metadataNet.directoryID = directory.directoryID;
  1548. metadataNet.priority = NSOperationQueuePriorityHigh;
  1549. metadataNet.selector = selectorReadFolder;
  1550. metadataNet.serverUrl = serverUrl;
  1551. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1552. }
  1553. #pragma mark -
  1554. #pragma --------------------------------------------------------------------------------------------
  1555. #pragma mark ===== Search =====
  1556. #pragma --------------------------------------------------------------------------------------------
  1557. -(void)searchStartTimer
  1558. {
  1559. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1560. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1561. _noFilesSearchTitle = @"";
  1562. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1563. [self.tableView reloadEmptyDataSet];
  1564. }
  1565. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1566. {
  1567. //[self setNeedsStatusBarAppearanceUpdate];
  1568. _isSearchMode = YES;
  1569. [self deleteRefreshControl];
  1570. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1571. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1572. _searchFileName = fileName;
  1573. // First : filter
  1574. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1575. if (!directoryID) return;
  1576. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileName CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1577. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1578. [_searchResultMetadatas removeAllObjects];
  1579. for (tableMetadata *record in records)
  1580. [_searchResultMetadatas addObject:record];
  1581. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1582. metadataNet.account = app.activeAccount;
  1583. metadataNet.directoryID = directoryID;
  1584. metadataNet.selector = selectorSearch;
  1585. metadataNet.serverUrl = _serverUrl;
  1586. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1587. // Version >= 12
  1588. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1589. [_timerWaitInput invalidate];
  1590. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1591. }
  1592. }
  1593. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1594. [self reloadDatasource];
  1595. }
  1596. }
  1597. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1598. {
  1599. [self cancelSearchBar];
  1600. [self readFolder:_serverUrl];
  1601. }
  1602. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1603. {
  1604. // Unauthorized
  1605. if (errorCode == kOCErrorServerUnauthorized)
  1606. [app openLoginView:self loginType:loginModifyPasswordUser];
  1607. if (message && errorCode != kOCErrorServerUnauthorized)
  1608. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1609. _searchFileName = @"";
  1610. }
  1611. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1612. {
  1613. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1614. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1615. }
  1616. - (void)cancelSearchBar
  1617. {
  1618. if (self.searchController.active) {
  1619. [self.searchController setActive:NO];
  1620. [self createRefreshControl];
  1621. _isSearchMode = NO;
  1622. _searchFileName = @"";
  1623. _dateReadDataSource = nil;
  1624. _searchResultMetadatas = [NSMutableArray new];
  1625. [self reloadDatasource];
  1626. }
  1627. //[self setNeedsStatusBarAppearanceUpdate];
  1628. }
  1629. #pragma mark -
  1630. #pragma --------------------------------------------------------------------------------------------
  1631. #pragma mark ===== Delete File or Folder =====
  1632. #pragma --------------------------------------------------------------------------------------------
  1633. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1634. {
  1635. // Unauthorized
  1636. if (errorCode == kOCErrorServerUnauthorized)
  1637. [app openLoginView:self loginType:loginModifyPasswordUser];
  1638. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1639. [self deleteFileOrFolderSuccess:metadataNet];
  1640. }
  1641. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1642. {
  1643. [_queueSelector removeObject:metadataNet.selector];
  1644. if ([_queueSelector count] == 0) {
  1645. [_hud hideHud];
  1646. // next
  1647. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1648. if ([_selectedFileIDsMetadatas count] > 0) {
  1649. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1650. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1651. } else {
  1652. // End Select Table View
  1653. [self tableViewSelect:NO];
  1654. // Reload
  1655. if (_isSearchMode)
  1656. [self readFolder:metadataNet.serverUrl];
  1657. else
  1658. [self reloadDatasource:metadataNet.serverUrl];
  1659. }
  1660. }
  1661. }
  1662. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1663. {
  1664. [_queueSelector addObject:selectorDelete];
  1665. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1666. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1667. }
  1668. - (void)deleteFile
  1669. {
  1670. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1671. return;
  1672. [_queueSelector removeAllObjects];
  1673. if ([_selectedFileIDsMetadatas count] > 0) {
  1674. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1675. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1676. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1677. } else {
  1678. _numSelectedFileIDsMetadatas = 1;
  1679. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1680. }
  1681. }
  1682. #pragma --------------------------------------------------------------------------------------------
  1683. #pragma mark ===== Rename / Move =====
  1684. #pragma --------------------------------------------------------------------------------------------
  1685. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1686. {
  1687. [self readFolder:metadataNet.serverUrl];
  1688. }
  1689. - (void)renameFile:(NSArray *)arguments
  1690. {
  1691. tableMetadata* metadata = [arguments objectAtIndex:0];
  1692. NSString *fileName = [arguments objectAtIndex:1];
  1693. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1694. }
  1695. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1696. {
  1697. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1698. [_hud hideHud];
  1699. if (message && errorCode != kOCErrorServerUnauthorized)
  1700. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1701. // End Select Table View
  1702. [self tableViewSelect:NO];
  1703. // reload Datasource
  1704. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1705. [self readFolder:metadataNet.serverUrl];
  1706. else
  1707. [self reloadDatasource];
  1708. }
  1709. }
  1710. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1711. {
  1712. [_queueSelector removeObject:metadataNet.selector];
  1713. if ([_queueSelector count] == 0) {
  1714. [_hud hideHud];
  1715. NSString *fileName = metadataNet.fileName;
  1716. NSString *directoryID = metadataNet.directoryID;
  1717. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1718. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1719. if (!serverUrlTo) return;
  1720. // FILE -> Metadata
  1721. if (metadataNet.directory == NO)
  1722. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1723. // DIRECTORY -> Directory - CCMetadata
  1724. if (metadataNet.directory == YES) {
  1725. // delete all dir / subdir
  1726. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1727. // move metadata
  1728. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1729. // Add new directory
  1730. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1731. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1732. }
  1733. // next
  1734. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1735. if ([_selectedFileIDsMetadatas count] > 0) {
  1736. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1737. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1738. } else {
  1739. // End Select Table View
  1740. [self tableViewSelect:NO];
  1741. // reload Datasource
  1742. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1743. [self readFolder:metadataNet.serverUrl];
  1744. else
  1745. [self reloadDatasource];
  1746. }
  1747. }
  1748. }
  1749. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1750. {
  1751. tableMetadata *metadata = [arguments objectAtIndex:0];
  1752. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1753. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1754. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1755. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1756. if (!serverUrl) return;
  1757. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1758. if (!directoryIDTo) return;
  1759. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1760. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1761. if(!error) {
  1762. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1763. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1764. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1765. }];
  1766. [alert addAction:ok];
  1767. [self presentViewController:alert animated:YES completion:nil];
  1768. });
  1769. // End Select Table View
  1770. [self tableViewSelect:NO];
  1771. // reload Datasource
  1772. [self readFileReloadFolder];
  1773. return;
  1774. }
  1775. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1776. metadataNet.action = actionMoveFileOrFolder;
  1777. metadataNet.directory = metadata.directory;
  1778. metadataNet.fileID = metadata.fileID;
  1779. metadataNet.directoryID = metadata.directoryID;
  1780. metadataNet.directoryIDTo = directoryIDTo;
  1781. metadataNet.fileName = metadata.fileName;
  1782. metadataNet.fileNameTo = metadata.fileName;
  1783. metadataNet.etag = metadata.etag;
  1784. metadataNet.selector = selectorMove;
  1785. metadataNet.serverUrl = serverUrl;
  1786. metadataNet.serverUrlTo = serverUrlTo;
  1787. [_queueSelector addObject:metadataNet.selector];
  1788. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1789. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1790. }
  1791. // DELEGATE : Move
  1792. - (void)dismissMove
  1793. {
  1794. [self reloadDatasource];
  1795. }
  1796. // DELEGATE : Move
  1797. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1798. {
  1799. [_queueSelector removeAllObjects];
  1800. if ([_selectedFileIDsMetadatas count] > 0) {
  1801. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1802. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1803. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1804. } else {
  1805. _numSelectedFileIDsMetadatas = 1;
  1806. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1807. }
  1808. }
  1809. - (void)moveOpenWindow:(NSArray *)indexPaths
  1810. {
  1811. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1812. return;
  1813. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1814. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1815. viewController.delegate = self;
  1816. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1817. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1818. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1819. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1820. viewController.networkingOperationQueue = app.netQueue;
  1821. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1822. [self presentViewController:navigationController animated:YES completion:nil];
  1823. }
  1824. #pragma --------------------------------------------------------------------------------------------
  1825. #pragma mark ===== Create folder =====
  1826. #pragma --------------------------------------------------------------------------------------------
  1827. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1828. {
  1829. // Unauthorized
  1830. if (errorCode == kOCErrorServerUnauthorized)
  1831. [app openLoginView:self loginType:loginModifyPasswordUser];
  1832. if (message && errorCode != kOCErrorServerUnauthorized)
  1833. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1834. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1835. [self reloadDatasource];
  1836. // We are in directory fail ?
  1837. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1838. if (vc)
  1839. [vc.navigationController popViewControllerAnimated:YES];
  1840. }
  1841. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1842. {
  1843. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1844. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1845. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1846. if (metadata) {
  1847. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1848. metadata.fileID = metadataNet.fileID;
  1849. metadata.date = metadataNet.date;
  1850. metadata.permissions = @"RDNVCK";
  1851. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1852. [self reloadDatasource];
  1853. } else {
  1854. [self readFileReloadFolder];
  1855. }
  1856. }
  1857. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1858. {
  1859. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1860. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1861. if (![fileNameFolder length]) return;
  1862. //if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1863. //else metadataNet.serverUrl = _serverUrl;
  1864. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1865. if (!directoryID) return;
  1866. metadataNet.action = actionCreateFolder;
  1867. metadataNet.directoryID = directoryID;
  1868. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1869. metadataNet.fileName = fileNameFolder;
  1870. metadataNet.selector = selectorCreateFolder;
  1871. metadataNet.serverUrl = serverUrl;
  1872. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1873. // Create Directory on metadata
  1874. 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];
  1875. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1876. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1877. [self reloadDatasource];
  1878. }
  1879. #pragma --------------------------------------------------------------------------------------------
  1880. #pragma mark ===== Mark/Delete Encrypted Folder =====
  1881. #pragma --------------------------------------------------------------------------------------------
  1882. - (void)markEndToEndFolderEncryptedSuccess:(CCMetadataNet *)metadataNet
  1883. {
  1884. }
  1885. - (void)markEndToEndFolderEncryptedFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1886. {
  1887. // Unauthorized
  1888. if (errorCode == kOCErrorServerUnauthorized)
  1889. [app openLoginView:self loginType:loginModifyPasswordUser];
  1890. if (errorCode != kOCErrorServerUnauthorized)
  1891. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1892. }
  1893. - (void)markEndToEndFolderEncrypted
  1894. {
  1895. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1896. metadataNet.action = actionMarkEndToEndFolderEncrypted;
  1897. metadataNet.fileID = _metadata.fileID;
  1898. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1899. }
  1900. - (void)deleteEndToEndFolderEncryptedSuccess:(CCMetadataNet *)metadataNet
  1901. {
  1902. }
  1903. - (void)deleteEndToEndFolderEncryptedFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1904. {
  1905. // Unauthorized
  1906. if (errorCode == kOCErrorServerUnauthorized)
  1907. [app openLoginView:self loginType:loginModifyPasswordUser];
  1908. if (errorCode != kOCErrorServerUnauthorized)
  1909. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1910. }
  1911. - (void)deleteEndToEndFolderEncrypted
  1912. {
  1913. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1914. metadataNet.action = actionDeleteEndToEndFolderEncrypted;
  1915. metadataNet.fileID = _metadata.fileID;
  1916. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1917. }
  1918. #pragma --------------------------------------------------------------------------------------------
  1919. #pragma mark ===== Encrypted/Decrypted File =====
  1920. #pragma --------------------------------------------------------------------------------------------
  1921. - (void)encryptedSelectedFiles
  1922. {
  1923. }
  1924. - (void)decryptedSelectedFiles
  1925. {
  1926. }
  1927. - (void)cmdEncryptedDecryptedFile
  1928. {
  1929. }
  1930. - (void)encryptedFile:(tableMetadata *)metadata
  1931. {
  1932. }
  1933. - (void)decryptedFile:(tableMetadata *)metadata
  1934. {
  1935. }
  1936. #pragma --------------------------------------------------------------------------------------------
  1937. #pragma mark ===== Progress & Task Button =====
  1938. #pragma --------------------------------------------------------------------------------------------
  1939. - (void)triggerProgressTask:(NSNotification *)notification
  1940. {
  1941. NSDictionary *dict = notification.userInfo;
  1942. NSString *fileID = [dict valueForKey:@"fileID"];
  1943. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1944. float progress = [[dict valueForKey:@"progress"] floatValue];
  1945. // Check
  1946. if (!fileID || [fileID isEqualToString: @""])
  1947. return;
  1948. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1949. if (![serverUrl isEqualToString:_serverUrl])
  1950. return;
  1951. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1952. if ([self indexPathIsValid:indexPath]) {
  1953. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1954. cell.progressView.progressTintColor = [UIColor blackColor];
  1955. cell.progressView.hidden = NO;
  1956. [cell.progressView setProgress:progress];
  1957. }
  1958. }
  1959. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1960. {
  1961. UITouch * touch = [[event allTouches] anyObject];
  1962. CGPoint location = [touch locationInView:self.tableView];
  1963. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1964. if ([self indexPathIsValid:indexPath]) {
  1965. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1966. if (metadata)
  1967. [self reloadTaskButton:metadata];
  1968. }
  1969. }
  1970. - (void)reloadTaskButton:(tableMetadata *)metadata
  1971. {
  1972. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1973. __block NSURLSessionTask *findTask;
  1974. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1975. NSString *fileID = metadata.fileID;
  1976. // DOWNLOAD
  1977. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1978. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1979. for (NSURLSessionUploadTask *task in downloadTasks)
  1980. if (task.taskIdentifier == sessionTaskIdentifier) {
  1981. findTask = task;
  1982. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1983. [task cancel];
  1984. }
  1985. if (!findTask) {
  1986. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1987. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1988. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1989. }
  1990. }];
  1991. }
  1992. // UPLOAD
  1993. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1994. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1995. for (NSURLSessionUploadTask *task in uploadTasks)
  1996. if (task.taskIdentifier == sessionTaskIdentifier) {
  1997. findTask = task;
  1998. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1999. [task cancel];
  2000. }
  2001. if (!findTask) {
  2002. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2003. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2004. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2005. }
  2006. }];
  2007. }
  2008. }
  2009. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2010. {
  2011. UITouch * touch = [[event allTouches] anyObject];
  2012. CGPoint location = [touch locationInView:self.tableView];
  2013. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2014. if ([self indexPathIsValid:indexPath]) {
  2015. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2016. if (metadata)
  2017. [self cancelTaskButton:metadata reloadTable:YES];
  2018. }
  2019. }
  2020. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2021. {
  2022. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2023. __block NSURLSessionTask *findTask;
  2024. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2025. NSString *fileID = metadata.fileID;
  2026. // DOWNLOAD
  2027. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2028. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2029. for (NSURLSessionTask *task in downloadTasks)
  2030. if (task.taskIdentifier == sessionTaskIdentifier) {
  2031. findTask = task;
  2032. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2033. [task cancel];
  2034. }
  2035. if (!findTask) {
  2036. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2037. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2038. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2039. }
  2040. }];
  2041. }
  2042. // UPLOAD
  2043. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2044. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2045. for (NSURLSessionUploadTask *task in uploadTasks)
  2046. if (task.taskIdentifier == sessionTaskIdentifier) {
  2047. findTask = task;
  2048. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2049. [task cancel];
  2050. }
  2051. if (!findTask) {
  2052. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2053. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2054. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2055. }
  2056. }];
  2057. }
  2058. }
  2059. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2060. {
  2061. UITouch * touch = [[event allTouches] anyObject];
  2062. CGPoint location = [touch locationInView:self.tableView];
  2063. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2064. if ([self indexPathIsValid:indexPath]) {
  2065. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2066. if (metadata)
  2067. [self stopTaskButton:metadata];
  2068. }
  2069. }
  2070. - (void)stopTaskButton:(tableMetadata *)metadata
  2071. {
  2072. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2073. __block NSURLSessionTask *findTask;
  2074. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2075. NSString *fileID = metadata.fileID;
  2076. // UPLOAD
  2077. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2078. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2079. for (NSURLSessionUploadTask *task in uploadTasks)
  2080. if (task.taskIdentifier == sessionTaskIdentifier) {
  2081. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2082. findTask = task;
  2083. [task cancel];
  2084. }
  2085. if (!findTask) {
  2086. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2087. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2088. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2089. }
  2090. }];
  2091. }
  2092. }
  2093. #pragma --------------------------------------------------------------------------------------------
  2094. #pragma mark ===== Shared =====
  2095. #pragma --------------------------------------------------------------------------------------------
  2096. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2097. {
  2098. [_hud hideHud];
  2099. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2100. // change account ?
  2101. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2102. if([record.account isEqualToString:metadataNet.account] == NO)
  2103. return;
  2104. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2105. if (result) {
  2106. appDelegate.sharesLink = result[0];
  2107. appDelegate.sharesUserAndGroup = result[1];
  2108. }
  2109. // Notify Shares View
  2110. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2111. if (openWindow) {
  2112. if (_shareOC) {
  2113. [_shareOC reloadData];
  2114. } else {
  2115. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2116. // Apriamo la view
  2117. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2118. _shareOC.delegate = self;
  2119. _shareOC.metadata = metadata;
  2120. _shareOC.serverUrl = metadataNet.serverUrl;
  2121. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2122. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2123. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2124. [self presentViewController:_shareOC animated:YES completion:nil];
  2125. }
  2126. }
  2127. [self tableViewReloadData];
  2128. }
  2129. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2130. {
  2131. [_hud hideHud];
  2132. // Unauthorized
  2133. if (errorCode == kOCErrorServerUnauthorized)
  2134. [app openLoginView:self loginType:loginModifyPasswordUser];
  2135. if (errorCode != kOCErrorServerUnauthorized)
  2136. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2137. if (_shareOC)
  2138. [_shareOC reloadData];
  2139. [self tableViewReloadData];
  2140. }
  2141. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2142. {
  2143. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2144. metadataNet.action = actionShare;
  2145. metadataNet.fileID = metadata.fileID;
  2146. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2147. metadataNet.password = password;
  2148. metadataNet.selector = selectorShare;
  2149. metadataNet.serverUrl = serverUrl;
  2150. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2151. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2152. }
  2153. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2154. {
  2155. [_hud hideHud];
  2156. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2157. // rimuoviamo la condivisione da db
  2158. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2159. if (result) {
  2160. appDelegate.sharesLink = result[0];
  2161. appDelegate.sharesUserAndGroup = result[1];
  2162. }
  2163. if (_shareOC)
  2164. [_shareOC reloadData];
  2165. [self tableViewReloadData];
  2166. }
  2167. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2168. {
  2169. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2170. metadataNet.action = actionUnShare;
  2171. metadataNet.fileID = metadata.fileID;
  2172. metadataNet.fileName = metadata.fileName;
  2173. metadataNet.selector = selectorUnshare;
  2174. metadataNet.serverUrl = serverUrl;
  2175. metadataNet.share = share;
  2176. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2177. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2178. }
  2179. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2180. {
  2181. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2182. metadataNet.action = actionUpdateShare;
  2183. metadataNet.fileID = metadata.fileID;
  2184. metadataNet.expirationTime = expirationTime;
  2185. metadataNet.password = password;
  2186. metadataNet.selector = selectorUpdateShare;
  2187. metadataNet.serverUrl = serverUrl;
  2188. metadataNet.share = share;
  2189. metadataNet.sharePermission = permission;
  2190. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2191. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2192. }
  2193. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2194. {
  2195. [_hud hideHud];
  2196. if (_shareOC)
  2197. [_shareOC reloadUserAndGroup:items];
  2198. }
  2199. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2200. {
  2201. [_hud hideHud];
  2202. // Unauthorized
  2203. if (errorCode == kOCErrorServerUnauthorized)
  2204. [app openLoginView:self loginType:loginModifyPasswordUser];
  2205. if (errorCode != kOCErrorServerUnauthorized)
  2206. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2207. }
  2208. - (void)getUserAndGroup:(NSString *)find
  2209. {
  2210. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2211. metadataNet.action = actionGetUserAndGroup;
  2212. metadataNet.options = find;
  2213. metadataNet.selector = selectorGetUserAndGroup;
  2214. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2215. [_hud visibleIndeterminateHud];
  2216. }
  2217. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2218. {
  2219. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2220. metadataNet.action = actionShareWith;
  2221. metadataNet.fileID = metadata.fileID;
  2222. metadataNet.directoryID = directoryID;
  2223. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2224. metadataNet.serverUrl = serverUrl;
  2225. metadataNet.selector = selectorShare;
  2226. metadataNet.share = user;
  2227. metadataNet.shareeType = shareeType;
  2228. metadataNet.sharePermission = permission;
  2229. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2230. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2231. }
  2232. - (void)openWindowShare:(tableMetadata *)metadata
  2233. {
  2234. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2235. if (!serverUrl) return;
  2236. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2237. metadataNet.action = actionReadShareServer;
  2238. metadataNet.fileID = metadata.fileID;
  2239. metadataNet.fileName = metadata.fileName;
  2240. metadataNet.selector = selectorOpenWindowShare;
  2241. metadataNet.serverUrl = serverUrl;
  2242. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2243. [_hud visibleIndeterminateHud];
  2244. }
  2245. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2246. {
  2247. CGPoint location = [tapGesture locationInView:self.tableView];
  2248. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2249. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2250. if (metadata)
  2251. [self openWindowShare:metadata];
  2252. }
  2253. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2254. {
  2255. CGPoint location = [tapGesture locationInView:self.tableView];
  2256. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2257. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2258. if (metadata) {
  2259. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2260. vc.metadata = metadata;
  2261. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2262. [self presentViewController:vc animated:YES completion:nil];
  2263. }
  2264. }
  2265. #pragma --------------------------------------------------------------------------------------------
  2266. #pragma mark ===== Favorite =====
  2267. #pragma --------------------------------------------------------------------------------------------
  2268. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2269. {
  2270. _dateReadDataSource = nil;
  2271. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2272. if (_isSearchMode)
  2273. [self readFolder:metadataNet.serverUrl];
  2274. else
  2275. [self reloadDatasource:metadataNet.serverUrl];
  2276. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2277. if (metadata.directory && metadata.favorite) {
  2278. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2279. [app.activeFavorites addFavoriteFolder:dir];
  2280. }
  2281. }
  2282. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2283. {
  2284. // Unauthorized
  2285. if (errorCode == kOCErrorServerUnauthorized)
  2286. [app openLoginView:self loginType:loginModifyPasswordUser];
  2287. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2288. }
  2289. - (void)addFavorite:(tableMetadata *)metadata
  2290. {
  2291. if (metadata.directory) {
  2292. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2293. } else {
  2294. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2295. if (serverUrl)
  2296. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2297. }
  2298. }
  2299. - (void)removeFavorite:(tableMetadata *)metadata
  2300. {
  2301. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2302. }
  2303. #pragma --------------------------------------------------------------------------------------------
  2304. #pragma mark ===== Open in... =====
  2305. #pragma --------------------------------------------------------------------------------------------
  2306. - (void)openIn:(tableMetadata *)metadata
  2307. {
  2308. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2309. if (!serverUrl) return;
  2310. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2311. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2312. if ([self indexPathIsValid:indexPath])
  2313. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2314. }
  2315. #pragma --------------------------------------------------------------------------------------------
  2316. #pragma mark ===== Remove Local File =====
  2317. #pragma --------------------------------------------------------------------------------------------
  2318. - (void)removeLocalFile:(tableMetadata *)metadata
  2319. {
  2320. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2321. if (!serverUrl) return;
  2322. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2323. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2324. [self reloadDatasource:serverUrl];
  2325. }
  2326. #pragma --------------------------------------------------------------------------------------------
  2327. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2328. #pragma --------------------------------------------------------------------------------------------
  2329. - (void)orderTable:(NSString *)order
  2330. {
  2331. [CCUtility setOrderSettings:order];
  2332. // Clear data-read of DataSource
  2333. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2334. }
  2335. - (void)ascendingTable:(BOOL)ascending
  2336. {
  2337. [CCUtility setAscendingSettings:ascending];
  2338. // Clear data-read of DataSource
  2339. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2340. }
  2341. - (void)directoryOnTop:(BOOL)directoryOnTop
  2342. {
  2343. [CCUtility setDirectoryOnTop:directoryOnTop];
  2344. // Clear data-read of DataSource
  2345. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2346. }
  2347. - (void)tableGroupBy:(NSString *)groupBy
  2348. {
  2349. [CCUtility setGroupBySettings:groupBy];
  2350. // Clear data-read of DataSource
  2351. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2352. }
  2353. #pragma --------------------------------------------------------------------------------------------
  2354. #pragma mark ==== Menu LOGO ====
  2355. #pragma --------------------------------------------------------------------------------------------
  2356. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2357. {
  2358. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2359. return;
  2360. // Brand
  2361. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2362. return;
  2363. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2364. NSUInteger numInQueue = [app.netQueue operationCount];
  2365. if (numInSession+numInQueue > 0) {
  2366. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2367. return;
  2368. }
  2369. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2370. NSMutableArray *menuArray = [NSMutableArray new];
  2371. for (NSString *account in listAccount) {
  2372. if ([account isEqualToString:app.activeAccount]) continue;
  2373. CCMenuItem *item = [[CCMenuItem alloc] init];
  2374. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2375. item.argument = account;
  2376. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2377. item.target = self;
  2378. item.action = @selector(changeDefaultAccount:);
  2379. [menuArray addObject:item];
  2380. }
  2381. if ([menuArray count] == 0)
  2382. return;
  2383. OptionalConfiguration options;
  2384. Color textColor, backgroundColor;
  2385. textColor.R = 0;
  2386. textColor.G = 0;
  2387. textColor.B = 0;
  2388. backgroundColor.R = 1;
  2389. backgroundColor.G = 1;
  2390. backgroundColor.B = 1;
  2391. options.arrowSize = 9;
  2392. options.marginXSpacing = 7;
  2393. options.marginYSpacing = 10;
  2394. options.intervalSpacing = 20;
  2395. options.menuCornerRadius = 6.5;
  2396. options.maskToBackground = NO;
  2397. options.shadowOfMenu = YES;
  2398. options.hasSeperatorLine = YES;
  2399. options.seperatorLineHasInsets = YES;
  2400. options.textColor = textColor;
  2401. options.menuBackgroundColor = backgroundColor;
  2402. CGRect rect = self.view.frame;
  2403. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2404. CGFloat safeAreaTop = 0;
  2405. CGFloat offsetY = 35;
  2406. if (@available(iOS 11, *)) {
  2407. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2408. }
  2409. rect.origin.y = locationY + safeAreaTop + offsetY;
  2410. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2411. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2412. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2413. }
  2414. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2415. {
  2416. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2417. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2418. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2419. if (tableAccount)
  2420. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2421. // go to home sweet home
  2422. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2423. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2424. });
  2425. }
  2426. #pragma --------------------------------------------------------------------------------------------
  2427. #pragma mark ==== ReMenu ====
  2428. #pragma --------------------------------------------------------------------------------------------
  2429. - (void)createReMenuBackgroundView:(REMenu *)menu
  2430. {
  2431. CGFloat safeAreaBottom = 0;
  2432. CGFloat safeAreaTop = 0;
  2433. CGFloat statusBar = 0;
  2434. if (@available(iOS 11, *)) {
  2435. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2436. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2437. }
  2438. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2439. statusBar = 13;
  2440. }
  2441. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2442. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2443. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2444. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2445. [UIView animateWithDuration:0.2 animations:^{
  2446. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2447. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2448. if (y>minimum) {
  2449. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2450. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2451. }
  2452. }];
  2453. }
  2454. - (void)createReMainMenu
  2455. {
  2456. NSString *ordinamento;
  2457. NSString *groupBy = _directoryGroupBy;
  2458. __block NSString *nuovoOrdinamento;
  2459. NSString *titoloNuovo, *titoloAttuale;
  2460. BOOL ascendente;
  2461. __block BOOL nuovoAscendente;
  2462. UIImage *image;
  2463. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2464. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2465. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2466. [self tableViewSelect:YES];
  2467. }
  2468. }];
  2469. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2470. ordinamento = _directoryOrder;
  2471. if ([ordinamento isEqualToString:@"fileName"]) {
  2472. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2473. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2474. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2475. nuovoOrdinamento = @"date";
  2476. }
  2477. if ([ordinamento isEqualToString:@"date"]) {
  2478. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2479. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2480. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2481. nuovoOrdinamento = @"fileName";
  2482. }
  2483. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2484. [self orderTable:nuovoOrdinamento];
  2485. }];
  2486. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2487. ascendente = [CCUtility getAscendingSettings];
  2488. if (ascendente) {
  2489. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2490. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2491. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2492. nuovoAscendente = false;
  2493. }
  2494. if (!ascendente) {
  2495. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2496. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2497. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2498. nuovoAscendente = true;
  2499. }
  2500. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2501. [self ascendingTable:nuovoAscendente];
  2502. }];
  2503. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2504. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2505. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2506. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2507. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2508. else [self tableGroupBy:@"alphabetic"];
  2509. }];
  2510. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2511. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2512. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2513. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2514. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2515. else [self tableGroupBy:@"typefile"];
  2516. }];
  2517. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2518. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2519. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2520. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2521. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2522. else [self tableGroupBy:@"date"];
  2523. }];
  2524. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2525. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2526. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2527. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2528. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2529. else [self directoryOnTop:YES];
  2530. }];
  2531. // REMENU --------------------------------------------------------------------------------------------------------------
  2532. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2533. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2534. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2535. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2536. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2537. app.reMainMenu.separatorHeight = 0.5;
  2538. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2539. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2540. app.reMainMenu.textColor = [UIColor blackColor];
  2541. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2542. app.reMainMenu.textShadowColor = nil;
  2543. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2544. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2545. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2546. app.reMainMenu.highlightedSeparatorColor = nil;
  2547. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2548. app.reMainMenu.highlightedTextShadowColor = nil;
  2549. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2550. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2551. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2552. app.reMainMenu.subtitleTextShadowColor = nil;
  2553. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2554. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2555. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2556. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2557. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2558. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2559. app.reMainMenu.borderWidth = 0.3;
  2560. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2561. app.reMainMenu.animationDuration = 0.2;
  2562. app.reMainMenu.closeAnimationDuration = 0.2;
  2563. app.reMainMenu.bounce = NO;
  2564. [app.reMainMenu setClosePreparationBlock:^{
  2565. // Backgroun reMenu (Gesture)
  2566. [_reMenuBackgroundView removeFromSuperview];
  2567. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2568. }];
  2569. }
  2570. - (void)toggleReMainMenu
  2571. {
  2572. if (app.reMainMenu.isOpen) {
  2573. [app.reMainMenu close];
  2574. } else {
  2575. [self createReMainMenu];
  2576. [app.reMainMenu showFromNavigationController:self.navigationController];
  2577. // Backgroun reMenu & (Gesture)
  2578. [self createReMenuBackgroundView:app.reMainMenu];
  2579. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2580. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2581. }
  2582. }
  2583. - (void)createReSelectMenu
  2584. {
  2585. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2586. 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) {
  2587. [self deleteFile];
  2588. }];
  2589. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2590. 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) {
  2591. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2592. }];
  2593. /*
  2594. if (app.isCryptoCloudMode) {
  2595. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2596. 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) {
  2597. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2598. }];
  2599. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2600. 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) {
  2601. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2602. }];
  2603. }
  2604. */
  2605. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2606. 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) {
  2607. [self downloadSelectedFilesFolders];
  2608. }];
  2609. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2610. 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) {
  2611. [self saveSelectedFiles];
  2612. }];
  2613. // REMENU --------------------------------------------------------------------------------------------------------------
  2614. /*
  2615. if (app.isCryptoCloudMode) {
  2616. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2617. } else {
  2618. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2619. }
  2620. */
  2621. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2622. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2623. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2624. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2625. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2626. app.reSelectMenu.separatorHeight = 0.5;
  2627. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2628. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2629. app.reSelectMenu.textColor = [UIColor blackColor];
  2630. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2631. app.reSelectMenu.textShadowColor = nil;
  2632. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2633. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2634. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2635. app.reSelectMenu.highlightedSeparatorColor = nil;
  2636. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2637. app.reSelectMenu.highlightedTextShadowColor = nil;
  2638. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2639. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2640. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2641. app.reSelectMenu.subtitleTextShadowColor = nil;
  2642. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2643. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2644. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2645. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2646. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2647. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2648. app.reSelectMenu.borderWidth = 0.3;
  2649. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2650. app.reSelectMenu.closeAnimationDuration = 0.2;
  2651. app.reSelectMenu.animationDuration = 0.2;
  2652. app.reSelectMenu.bounce = NO;
  2653. [app.reSelectMenu setClosePreparationBlock:^{
  2654. // Backgroun reMenu (Gesture)
  2655. [_reMenuBackgroundView removeFromSuperview];
  2656. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2657. }];
  2658. }
  2659. - (void)toggleReSelectMenu
  2660. {
  2661. if (app.reSelectMenu.isOpen) {
  2662. [app.reSelectMenu close];
  2663. } else {
  2664. [self createReSelectMenu];
  2665. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2666. // Backgroun reMenu & (Gesture)
  2667. [self createReMenuBackgroundView:app.reSelectMenu];
  2668. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2669. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2670. }
  2671. }
  2672. #pragma --------------------------------------------------------------------------------------------
  2673. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2674. #pragma --------------------------------------------------------------------------------------------
  2675. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2676. {
  2677. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2678. UITableView *tableView = (UITableView*)self.view;
  2679. CGPoint touchPoint = [recognizer locationInView:self.view];
  2680. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2681. if ([self indexPathIsValid:indexPath])
  2682. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2683. else
  2684. _metadata = nil;
  2685. [self becomeFirstResponder];
  2686. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2687. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2688. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2689. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2690. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2691. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2692. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2693. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2694. [menuController setMenuVisible:YES animated:YES];
  2695. }
  2696. }
  2697. - (BOOL)canBecomeFirstResponder
  2698. {
  2699. return YES;
  2700. }
  2701. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2702. {
  2703. // For copy file, copy files, Open in ... :
  2704. //
  2705. // NO Directory
  2706. // NO Error Passcode
  2707. // NO In Session mode (download/upload)
  2708. // NO Template
  2709. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2710. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2711. else return NO;
  2712. }
  2713. if (@selector(copyFiles:) == action) {
  2714. if (_isSelectedMode) {
  2715. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2716. for (tableMetadata *metadata in selectedMetadatas) {
  2717. if (!metadata.directory && metadata.session.length == 0)
  2718. return YES;
  2719. }
  2720. }
  2721. return NO;
  2722. }
  2723. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2724. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2725. NSArray *items = [pasteboard items];
  2726. if ([items count] == 1) {
  2727. // Value : (NSData) fileID
  2728. NSDictionary *dic = [items objectAtIndex:0];
  2729. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2730. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2731. if (fileID) {
  2732. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2733. if (metadata) {
  2734. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2735. if (account) {
  2736. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2737. if (directoryUser)
  2738. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2739. return YES;
  2740. }
  2741. }
  2742. }
  2743. }
  2744. return NO;
  2745. }
  2746. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2747. BOOL isValid = NO;
  2748. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2749. NSArray *items = [pasteboard items];
  2750. if ([items count] <= 1) return NO;
  2751. for (NSDictionary *dic in items) {
  2752. // Value : (NSData) fileID
  2753. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2754. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2755. if (fileID) {
  2756. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2757. if (metadata) {
  2758. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2759. if (account) {
  2760. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2761. if (directoryUser) {
  2762. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2763. isValid = YES;
  2764. } else {
  2765. isValid = NO;
  2766. break;
  2767. }
  2768. } else {
  2769. isValid = NO;
  2770. break;
  2771. }
  2772. } else {
  2773. isValid = NO;
  2774. break;
  2775. }
  2776. } else {
  2777. isValid = NO;
  2778. break;
  2779. }
  2780. } else {
  2781. isValid = NO;
  2782. break;
  2783. }
  2784. }
  2785. return isValid;
  2786. }
  2787. return NO;
  2788. }
  2789. /************************************ COPY ************************************/
  2790. - (void)copyFile:(id)sender
  2791. {
  2792. // Remove all item
  2793. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2794. pasteboard.items = [[NSArray alloc] init];
  2795. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2796. [self copyFileToPasteboard:_metadata];
  2797. } else {
  2798. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2799. if (serverUrl)
  2800. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2801. }
  2802. }
  2803. - (void)copyFiles:(id)sender
  2804. {
  2805. // Remove all item
  2806. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2807. pasteboard.items = [[NSArray alloc] init];
  2808. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2809. for (tableMetadata *metadata in selectedMetadatas) {
  2810. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2811. [self copyFileToPasteboard:metadata];
  2812. } else {
  2813. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2814. if (serverUrl)
  2815. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2816. }
  2817. }
  2818. [self tableViewSelect:NO];
  2819. }
  2820. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2821. {
  2822. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2823. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2824. // Value : (NSData) fileID
  2825. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2826. [items addObject:item];
  2827. [pasteboard setItems:items];
  2828. }
  2829. /************************************ OPEN IN ... ******************************/
  2830. - (void)openinFile:(id)sender
  2831. {
  2832. [self openIn:_metadata];
  2833. }
  2834. /************************************ PASTE ************************************/
  2835. - (void)pasteFile:(id)sender
  2836. {
  2837. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2838. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2839. }
  2840. - (void)pasteFileEncrypted:(id)sender
  2841. {
  2842. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2843. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2844. }
  2845. - (void)pasteFiles:(id)sender
  2846. {
  2847. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2848. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2849. }
  2850. - (void)pasteFilesEncrypted:(id)sender
  2851. {
  2852. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2853. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2854. }
  2855. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2856. {
  2857. float timer = 0;
  2858. for (NSDictionary *dic in items) {
  2859. // Value : (NSData) fileID
  2860. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2861. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2862. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2863. if (metadata) {
  2864. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2865. if (account) {
  2866. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2867. if (directoryUser) {
  2868. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2869. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]];
  2870. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2871. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2872. });
  2873. timer += 0.1;
  2874. }
  2875. }
  2876. }
  2877. }
  2878. }
  2879. }
  2880. #pragma --------------------------------------------------------------------------------------------
  2881. #pragma mark ===== Lock Passcode =====
  2882. #pragma --------------------------------------------------------------------------------------------
  2883. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2884. {
  2885. return _failedAttempts;
  2886. }
  2887. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2888. {
  2889. return _lockUntilDate;
  2890. }
  2891. - (void)passcodeViewCloseButtonPressed:(id)sender
  2892. {
  2893. [self dismissViewControllerAnimated:YES completion:nil];
  2894. }
  2895. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2896. {
  2897. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2898. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2899. _lockUntilDate = nil;
  2900. _failedAttempts = 0;
  2901. aResultHandler(YES);
  2902. } else aResultHandler(NO);
  2903. } else aResultHandler(YES);
  2904. }
  2905. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2906. {
  2907. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2908. switch (aViewController.type) {
  2909. case BKPasscodeViewControllerCheckPasscodeType: {
  2910. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2911. // possiamo procedere alla prossima directory
  2912. [self performSegueDirectoryWithControlPasscode:false];
  2913. // avviamo la sessione Passcode Lock con now
  2914. app.sessionePasscodeLock = [NSDate date];
  2915. }
  2916. // disattivazione lock cartella
  2917. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2918. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2919. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2920. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2921. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2922. }
  2923. [self tableViewReloadData];
  2924. }
  2925. }
  2926. break;
  2927. default:
  2928. break;
  2929. }
  2930. }
  2931. - (void)comandoLockPassword
  2932. {
  2933. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2934. if (!serverUrl) return;
  2935. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2936. // se non è abilitato il Lock Passcode esci
  2937. if ([[CCUtility getBlockCode] length] == 0) {
  2938. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2939. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2940. [alertController addAction:okAction];
  2941. [self presentViewController:alertController animated:YES completion:nil];
  2942. return;
  2943. }
  2944. // se è richiesta la disattivazione si chiede la password
  2945. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2946. if (directory.lock) {
  2947. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2948. viewController.delegate = self;
  2949. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2950. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2951. viewController.inputViewTitlePassword = YES;
  2952. if ([CCUtility getSimplyBlockCode]) {
  2953. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2954. viewController.passcodeInputView.maximumLength = 6;
  2955. } else {
  2956. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2957. viewController.passcodeInputView.maximumLength = 64;
  2958. }
  2959. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2960. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2961. viewController.touchIDManager = touchIDManager;
  2962. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2963. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2964. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2965. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2966. [self presentViewController:navigationController animated:YES completion:nil];
  2967. return;
  2968. }
  2969. // ---------------- ACTIVATE PASSWORD
  2970. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2971. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2972. if ([self indexPathIsValid:indexPath])
  2973. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2974. } else {
  2975. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2976. }
  2977. }
  2978. #pragma mark -
  2979. #pragma --------------------------------------------------------------------------------------------
  2980. #pragma mark ===== Swipe Tablet -> menu =====
  2981. #pragma --------------------------------------------------------------------------------------------
  2982. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2983. {
  2984. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2985. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2986. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2987. return NO;
  2988. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2989. return NO;
  2990. else
  2991. return YES;
  2992. }
  2993. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2994. {
  2995. }
  2996. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2997. {
  2998. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2999. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3000. if (direction == MGSwipeDirectionRightToLeft) {
  3001. // Delete
  3002. if (index == 0)
  3003. [self swipeDelete:indexPath];
  3004. // More
  3005. if (index == 1)
  3006. [self swipeMore:indexPath];
  3007. }
  3008. if (direction == MGSwipeDirectionLeftToRight) {
  3009. if (_metadata.favorite)
  3010. [self removeFavorite:_metadata];
  3011. else
  3012. [self addFavorite:_metadata];
  3013. }
  3014. return YES;
  3015. }
  3016. - (void)swipeDelete:(NSIndexPath *)indexPath
  3017. {
  3018. // Directory locked ?
  3019. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  3020. if (!lockServerUrl) return;
  3021. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3022. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  3023. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3024. return;
  3025. }
  3026. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3027. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  3028. [self performSelector:@selector(deleteFile) withObject:nil];
  3029. }]];
  3030. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3031. [alertController dismissViewControllerAnimated:YES completion:nil];
  3032. }]];
  3033. alertController.popoverPresentationController.sourceView = self.view;
  3034. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3035. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3036. [alertController.view layoutIfNeeded];
  3037. [self presentViewController:alertController animated:YES completion:nil];
  3038. }
  3039. - (void)swipeMore:(NSIndexPath *)indexPath
  3040. {
  3041. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3042. if (!serverUrl) return;
  3043. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  3044. titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3045. if (_metadata.favorite) {
  3046. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3047. } else {
  3048. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3049. }
  3050. if (_metadata.directory) {
  3051. // calcolo lockServerUrl
  3052. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3053. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3054. if (directory.lock)
  3055. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3056. else
  3057. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3058. }
  3059. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  3060. // ******************************************* AHKActionSheet *******************************************
  3061. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  3062. actionSheet.animationDuration = 0.2;
  3063. actionSheet.buttonHeight = 50.0;
  3064. actionSheet.cancelButtonHeight = 50.0f;
  3065. actionSheet.separatorHeight = 5.0f;
  3066. actionSheet.automaticallyTintButtonImages = @(NO);
  3067. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3068. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3069. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  3070. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  3071. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3072. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3073. // ******************************************* DIRECTORY *******************************************
  3074. if (_metadata.directory) {
  3075. BOOL lockDirectory = NO;
  3076. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3077. // Directory bloccata ?
  3078. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  3079. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3080. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3081. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3082. [actionSheet addButtonWithTitle: _metadata.fileName
  3083. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3084. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3085. height: 50.0
  3086. type: AHKActionSheetButtonTypeDisabled
  3087. handler: nil
  3088. ];
  3089. if (!lockDirectory) {
  3090. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3091. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3092. backgroundColor:[UIColor whiteColor]
  3093. height: 50.0
  3094. type:AHKActionSheetButtonTypeDefault
  3095. handler:^(AHKActionSheet *as) {
  3096. [self openWindowShare:_metadata];
  3097. }];
  3098. }
  3099. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3100. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3101. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3102. backgroundColor:[UIColor whiteColor]
  3103. height: 50.0
  3104. type:AHKActionSheetButtonTypeDefault
  3105. handler:^(AHKActionSheet *as) {
  3106. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3107. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3108. textField.text = _metadata.fileName;
  3109. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  3110. //textField.delegate = self;
  3111. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3112. }];
  3113. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3114. NSLog(@"Cancel action");
  3115. }];
  3116. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3117. UITextField *fileName = alertController.textFields.firstObject;
  3118. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3119. }];
  3120. okAction.enabled = NO;
  3121. [alertController addAction:cancelAction];
  3122. [alertController addAction:okAction];
  3123. [self presentViewController:alertController animated:YES completion:nil];
  3124. }];
  3125. }
  3126. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3127. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3128. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3129. backgroundColor:[UIColor whiteColor]
  3130. height: 50.0
  3131. type:AHKActionSheetButtonTypeDefault
  3132. handler:^(AHKActionSheet *as) {
  3133. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3134. }];
  3135. }
  3136. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3137. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3138. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3139. backgroundColor:[UIColor whiteColor]
  3140. height: 50.0
  3141. type:AHKActionSheetButtonTypeDefault
  3142. handler:^(AHKActionSheet *as) {
  3143. // Settings new folder Automatatic upload
  3144. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3145. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3146. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3147. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3148. if (app.activeAccount.length > 0 && app.activePhotos)
  3149. [app.activePhotos reloadDatasourceForced];
  3150. [self readFolder:serverUrl];
  3151. NSLog(@"[LOG] Update Folder Photo");
  3152. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3153. if ([autoUploadPath length] > 0) {
  3154. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  3155. }
  3156. }];
  3157. }
  3158. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && [CCUtility isEndToEndEnabled:app.activeAccount]) {
  3159. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3160. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3161. backgroundColor:[UIColor whiteColor]
  3162. height: 50.0
  3163. type:AHKActionSheetButtonTypeEncrypted
  3164. handler:^(AHKActionSheet *as) {
  3165. [self performSelector:@selector(deleteEndToEndFolderEncrypted) withObject:nil];
  3166. }];
  3167. }
  3168. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3169. [actionSheet addButtonWithTitle:titoloLock
  3170. image:[UIImage imageNamed:@"actionSheetLock"]
  3171. backgroundColor:[UIColor whiteColor]
  3172. height: 50.0
  3173. type:AHKActionSheetButtonTypeEncrypted
  3174. handler:^(AHKActionSheet *as) {
  3175. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3176. }];
  3177. }
  3178. [actionSheet show];
  3179. }
  3180. // ******************************************* FILE *******************************************
  3181. if (!_metadata.directory) {
  3182. UIImage *iconHeader;
  3183. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3184. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3185. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3186. else
  3187. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3188. [actionSheet addButtonWithTitle: _metadata.fileName
  3189. image: iconHeader
  3190. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3191. height: 50.0
  3192. type: AHKActionSheetButtonTypeDisabled
  3193. handler: nil
  3194. ];
  3195. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3196. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  3197. backgroundColor:[UIColor whiteColor]
  3198. height: 50.0
  3199. type:AHKActionSheetButtonTypeDefault
  3200. handler:^(AHKActionSheet *as) {
  3201. [self openWindowShare:_metadata];
  3202. }];
  3203. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3204. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3205. backgroundColor:[UIColor whiteColor]
  3206. height: 50.0
  3207. type:AHKActionSheetButtonTypeDefault
  3208. handler:^(AHKActionSheet *as) {
  3209. [self performSelector:@selector(openIn:) withObject:_metadata];
  3210. }];
  3211. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3212. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3213. backgroundColor:[UIColor whiteColor]
  3214. height: 50.0
  3215. type:AHKActionSheetButtonTypeDefault
  3216. handler:^(AHKActionSheet *as) {
  3217. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3218. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3219. textField.text = _metadata.fileName;
  3220. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3221. }];
  3222. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3223. NSLog(@"Cancel action");
  3224. }];
  3225. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3226. UITextField *fileName = alertController.textFields.firstObject;
  3227. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3228. }];
  3229. okAction.enabled = NO;
  3230. [alertController addAction:cancelAction];
  3231. [alertController addAction:okAction];
  3232. [self presentViewController:alertController animated:YES completion:nil];
  3233. }];
  3234. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3235. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3236. backgroundColor:[UIColor whiteColor]
  3237. height: 50.0
  3238. type:AHKActionSheetButtonTypeDefault
  3239. handler:^(AHKActionSheet *as) {
  3240. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3241. }];
  3242. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3243. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3244. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3245. backgroundColor:[UIColor whiteColor]
  3246. height: 50.0
  3247. type:AHKActionSheetButtonTypeDefault
  3248. handler:^(AHKActionSheet *as) {
  3249. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3250. }];
  3251. }
  3252. /*
  3253. if (app.isCryptoCloudMode) {
  3254. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3255. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3256. backgroundColor:[UIColor whiteColor]
  3257. height: 50.0
  3258. type:AHKActionSheetButtonTypeEncrypted
  3259. handler:^(AHKActionSheet *as) {
  3260. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3261. }];
  3262. }
  3263. */
  3264. #ifdef DEBUG
  3265. /*
  3266. [actionSheet addButtonWithTitle:@"Hide file"
  3267. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3268. backgroundColor:[UIColor whiteColor]
  3269. height: 50.0
  3270. type:AHKActionSheetButtonTypeDefault
  3271. handler:^(AHKActionSheet *as) {
  3272. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3273. [self reloadDatasource];
  3274. }];
  3275. */
  3276. #endif
  3277. [actionSheet show];
  3278. }
  3279. }
  3280. #pragma --------------------------------------------------------------------------------------------
  3281. #pragma mark - ==== Datasource ====
  3282. #pragma --------------------------------------------------------------------------------------------
  3283. - (void)clearDateReadDataSource:(NSNotification *)notification
  3284. {
  3285. _dateReadDataSource = Nil;
  3286. [self reloadDatasource];
  3287. }
  3288. - (void)reloadDatasource
  3289. {
  3290. [self reloadDatasource:_serverUrl];
  3291. }
  3292. - (void)reloadDatasource:(NSString *)serverUrl
  3293. {
  3294. // test
  3295. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3296. return;
  3297. // Search Mode
  3298. if(_isSearchMode) {
  3299. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3300. [self tableViewReloadData];
  3301. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3302. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3303. _noFilesSearchDescription = @"";
  3304. }
  3305. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3306. _noFilesSearchTitle = @"";
  3307. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3308. }
  3309. [self.tableView reloadEmptyDataSet];
  3310. return;
  3311. }
  3312. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3313. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3314. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3315. if (main) {
  3316. [main reloadDatasource];
  3317. } else {
  3318. [self tableViewReloadData];
  3319. [app.activeTransfers reloadDatasource];
  3320. }
  3321. return;
  3322. }
  3323. [app.activeTransfers reloadDatasource];
  3324. // Settaggio variabili per le ottimizzazioni
  3325. _directoryGroupBy = [CCUtility getGroupBySettings];
  3326. _directoryOrder = [CCUtility getOrderSettings];
  3327. // Controllo data lettura Data Source
  3328. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3329. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3330. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3331. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3332. _dateReadDataSource = [NSDate date];
  3333. // Data Source
  3334. NSString *sorted = _directoryOrder;
  3335. if ([sorted isEqualToString:@"fileName"])
  3336. sorted = @"fileName";
  3337. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3338. if (directoryID) {
  3339. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3340. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3341. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3342. }
  3343. } else {
  3344. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3345. }
  3346. [self tableViewReloadData];
  3347. }
  3348. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3349. {
  3350. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3351. if (selectedRows.count > 0) {
  3352. for (NSIndexPath *selectionIndex in selectedRows) {
  3353. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3354. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3355. [metadatas addObject:metadata];
  3356. }
  3357. }
  3358. return metadatas;
  3359. }
  3360. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3361. {
  3362. NSInteger section = indexPath.section + 1;
  3363. NSInteger row = indexPath.row + 1;
  3364. NSInteger totSections = [_sectionDataSource.sections count] ;
  3365. if ((totSections < section) || (section > totSections)) {
  3366. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3367. return nil;
  3368. }
  3369. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3370. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3371. if (fileIDs) {
  3372. NSInteger totRows =[fileIDs count] ;
  3373. if ((totRows < row) || (row > totRows)) {
  3374. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3375. return nil;
  3376. }
  3377. } else {
  3378. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3379. return nil;
  3380. }
  3381. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3382. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3383. return metadata;
  3384. }
  3385. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3386. {
  3387. NSInteger totSections =[_sectionDataSource.sections count] ;
  3388. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3389. return nil;
  3390. }
  3391. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3392. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3393. }
  3394. #pragma --------------------------------------------------------------------------------------------
  3395. #pragma mark - ==== Table ====
  3396. #pragma --------------------------------------------------------------------------------------------
  3397. - (void)tableViewSelect:(BOOL)edit
  3398. {
  3399. // chiudiamo eventuali swipe aperti
  3400. if (edit)
  3401. [self.tableView setEditing:NO animated:NO];
  3402. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3403. [self.tableView setEditing:edit animated:YES];
  3404. _isSelectedMode = edit;
  3405. if (edit)
  3406. [self setUINavigationBarSelected];
  3407. else
  3408. [self setUINavigationBarDefault];
  3409. [_selectedFileIDsMetadatas removeAllObjects];
  3410. [self setTitle];
  3411. }
  3412. - (void)tableViewReloadData
  3413. {
  3414. // store selected cells before relod
  3415. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3416. //store swipeOffset before relod
  3417. [_statusSwipeCell removeAllObjects];
  3418. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3419. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3420. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3421. }
  3422. // reload table view
  3423. [self.tableView reloadData];
  3424. // selected cells stored
  3425. for (NSIndexPath *path in indexPaths)
  3426. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3427. [self setTableViewFooter];
  3428. if (self.tableView.editing)
  3429. [self setTitle];
  3430. }
  3431. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3432. {
  3433. if (tableView.editing == 1) {
  3434. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3435. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3436. return NO;
  3437. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3438. return NO;
  3439. else
  3440. return YES;
  3441. } else {
  3442. [_selectedFileIDsMetadatas removeAllObjects];
  3443. }
  3444. return YES;
  3445. }
  3446. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3447. {
  3448. return 60;
  3449. }
  3450. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3451. {
  3452. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3453. }
  3454. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3455. {
  3456. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3457. }
  3458. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3459. {
  3460. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3461. NSString *sectionTitle = [sections objectAtIndex:section];
  3462. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3463. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3464. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3465. return 20.f;
  3466. }
  3467. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3468. {
  3469. float shift;
  3470. UIVisualEffectView *visualEffectView;
  3471. NSString *titleSection;
  3472. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3473. return nil;
  3474. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3475. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3476. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3477. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3478. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3479. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3480. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3481. else titleSection = NSLocalizedString(titleSection,nil);
  3482. // Format title
  3483. NSString *currentDevice = [CCUtility currentDevice];
  3484. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3485. visualEffectView = [[UIVisualEffectView alloc] init];
  3486. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3487. } else {
  3488. UIVisualEffect *blurEffect;
  3489. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3490. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3491. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3492. }
  3493. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3494. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3495. shift = - 35;
  3496. else
  3497. shift = - 20;
  3498. } else shift = - 10;
  3499. // Title
  3500. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3501. titleLabel.backgroundColor = [UIColor clearColor];
  3502. titleLabel.textColor = [UIColor blackColor];
  3503. titleLabel.font = [UIFont systemFontOfSize:12];
  3504. titleLabel.textAlignment = NSTextAlignmentLeft;
  3505. titleLabel.text = titleSection;
  3506. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3507. [visualEffectView.contentView addSubview:titleLabel];
  3508. // Elements
  3509. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3510. elementLabel.backgroundColor = [UIColor clearColor];
  3511. elementLabel.textColor = [UIColor blackColor];;
  3512. elementLabel.font = [UIFont systemFontOfSize:12];
  3513. elementLabel.textAlignment = NSTextAlignmentRight;
  3514. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3515. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3516. NSUInteger rowsCount = [metadatas count];
  3517. if (rowsCount == 0) return nil;
  3518. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3519. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3520. [visualEffectView.contentView addSubview:elementLabel];
  3521. return visualEffectView;
  3522. }
  3523. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3524. {
  3525. return [_sectionDataSource.sections indexOfObject:title];
  3526. }
  3527. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3528. {
  3529. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3530. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3531. else
  3532. return nil;
  3533. }
  3534. /*
  3535. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3536. {
  3537. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3538. }
  3539. }
  3540. */
  3541. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3542. {
  3543. NSString *typeCell;
  3544. NSString *dataFile;
  3545. NSString *lunghezzaFile;
  3546. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3547. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3548. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3549. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3550. if (!serverUrl)
  3551. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3552. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3553. else typeCell = @"CellMainTransfer";
  3554. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3555. // variable base
  3556. cell.delegate = self;
  3557. cell.indexPath = indexPath;
  3558. // separator
  3559. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3560. // change color selection
  3561. UIView *selectionColor = [[UIView alloc] init];
  3562. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3563. cell.selectedBackgroundView = selectionColor;
  3564. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3565. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3566. // ----------------------------------------------------------------------------------------------------------
  3567. // DEFAULT
  3568. // ----------------------------------------------------------------------------------------------------------
  3569. cell.file.image = nil;
  3570. cell.status.image = nil;
  3571. cell.favorite.image = nil;
  3572. cell.shared.image = nil;
  3573. cell.local.image = nil;
  3574. cell.labelTitle.enabled = YES;
  3575. cell.labelTitle.text = @"";
  3576. cell.labelInfoFile.enabled = YES;
  3577. cell.labelInfoFile.text = @"";
  3578. cell.progressView.progress = 0.0;
  3579. cell.progressView.hidden = YES;
  3580. cell.cancelTaskButton.hidden = YES;
  3581. cell.reloadTaskButton.hidden = YES;
  3582. cell.stopTaskButton.hidden = YES;
  3583. cell.labelTitle.textColor = [UIColor blackColor];
  3584. // ----------------------------------------------------------------------------------------------------------
  3585. // File Name & Folder
  3586. // ----------------------------------------------------------------------------------------------------------
  3587. // nome del file
  3588. cell.labelTitle.text = metadata.fileName;
  3589. // è una directory
  3590. if (metadata.directory) {
  3591. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3592. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3593. lunghezzaFile = @" ";
  3594. // ----------------------------------------------------------------------------------------------------------
  3595. // Favorite Folder
  3596. // ----------------------------------------------------------------------------------------------------------
  3597. if (metadata.favorite) {
  3598. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3599. }
  3600. } else {
  3601. // File
  3602. dataFile = [CCUtility dateDiff:metadata.date];
  3603. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3604. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3605. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3606. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3607. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3608. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3609. cell.local.image = [UIImage imageNamed:@"local"];
  3610. else
  3611. cell.local.image = nil;
  3612. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3613. cell.accessoryType = UITableViewCellAccessoryNone;
  3614. }
  3615. // ----------------------------------------------------------------------------------------------------------
  3616. // File Image View
  3617. // ----------------------------------------------------------------------------------------------------------
  3618. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3619. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3620. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3621. } else {
  3622. if (metadata.directory)
  3623. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3624. else
  3625. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3626. if (metadata.thumbnailExists)
  3627. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3628. }
  3629. // ----------------------------------------------------------------------------------------------------------
  3630. // Image Status cyptated & Lock Passcode
  3631. // ----------------------------------------------------------------------------------------------------------
  3632. // Directory con passcode lock attivato
  3633. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3634. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3635. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3636. cell.status.image = [UIImage imageNamed:@"passcode"];
  3637. // ----------------------------------------------------------------------------------------------------------
  3638. // Favorite
  3639. // ----------------------------------------------------------------------------------------------------------
  3640. if (metadata.favorite) {
  3641. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3642. }
  3643. // ----------------------------------------------------------------------------------------------------------
  3644. // Share
  3645. // ----------------------------------------------------------------------------------------------------------
  3646. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3647. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3648. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3649. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3650. // Aggiungiamo il Tap per le shared
  3651. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3652. // Shared with you
  3653. if (isShare) {
  3654. if (metadata.directory) {
  3655. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3656. cell.accessoryType = UITableViewCellAccessoryNone;
  3657. }
  3658. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3659. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3660. [tap setNumberOfTapsRequired:1];
  3661. cell.shared.userInteractionEnabled = YES;
  3662. [cell.shared addGestureRecognizer:tap];
  3663. }
  3664. // Mounted with you
  3665. if (isMounted) {
  3666. if (metadata.directory) {
  3667. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3668. cell.accessoryType = UITableViewCellAccessoryNone;
  3669. }
  3670. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3671. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3672. [tap setNumberOfTapsRequired:1];
  3673. cell.shared.userInteractionEnabled = YES;
  3674. [cell.shared addGestureRecognizer:tap];
  3675. }
  3676. // You share
  3677. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3678. if (metadata.directory) {
  3679. if ([shareLink length] > 0)
  3680. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3681. if ([shareUserAndGroup length] > 0)
  3682. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3683. cell.shared.userInteractionEnabled = NO;
  3684. } else {
  3685. if ([shareLink length] > 0)
  3686. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3687. if ([shareUserAndGroup length] > 0)
  3688. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3689. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3690. [tap setNumberOfTapsRequired:1];
  3691. cell.shared.userInteractionEnabled = YES;
  3692. [cell.shared addGestureRecognizer:tap];
  3693. }
  3694. }
  3695. } else {
  3696. cell.shared.userInteractionEnabled = NO;
  3697. }
  3698. // ----------------------------------------------------------------------------------------------------------
  3699. // downloadFile
  3700. // ----------------------------------------------------------------------------------------------------------
  3701. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3702. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3703. // sessionTaskIdentifier : RELOAD + STOP
  3704. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3705. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3706. cell.cancelTaskButton.hidden = NO;
  3707. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3708. cell.reloadTaskButton.hidden = NO;
  3709. }
  3710. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3711. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3712. if (progress > 0) {
  3713. cell.progressView.progressTintColor = [UIColor blackColor];
  3714. cell.progressView.progress = progress;
  3715. cell.progressView.hidden = NO;
  3716. }
  3717. // ----------------------------------------------------------------------------------------------------------
  3718. // downloadFile Error
  3719. // ----------------------------------------------------------------------------------------------------------
  3720. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3721. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3722. if ([metadata.sessionError length] == 0)
  3723. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3724. else
  3725. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3726. }
  3727. }
  3728. // ----------------------------------------------------------------------------------------------------------
  3729. // uploadFile
  3730. // ----------------------------------------------------------------------------------------------------------
  3731. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3732. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3733. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3734. cell.cancelTaskButton.hidden = NO;
  3735. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3736. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3737. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3738. cell.reloadTaskButton.hidden = NO;
  3739. cell.stopTaskButton.hidden = YES;
  3740. } else {
  3741. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3742. cell.stopTaskButton.hidden = NO;
  3743. cell.reloadTaskButton.hidden = YES;
  3744. }
  3745. // se non c'è una preview in bianconero metti l'immagine di default
  3746. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3747. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3748. cell.labelTitle.enabled = NO;
  3749. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3750. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3751. if (progress > 0) {
  3752. cell.progressView.progressTintColor = [UIColor blackColor];
  3753. cell.progressView.progress = progress;
  3754. cell.progressView.hidden = NO;
  3755. }
  3756. // ----------------------------------------------------------------------------------------------------------
  3757. // uploadFileError
  3758. // ----------------------------------------------------------------------------------------------------------
  3759. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3760. cell.labelTitle.enabled = NO;
  3761. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3762. if ([metadata.sessionError length] == 0)
  3763. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3764. else
  3765. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3766. }
  3767. }
  3768. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3769. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3770. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3771. // ======== MGSwipe ========
  3772. if (metadata.favorite)
  3773. 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]]];
  3774. else
  3775. 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]]];
  3776. cell.leftExpansion.buttonIndex = 0;
  3777. cell.leftExpansion.fillOnTrigger = NO;
  3778. //centerIconOverText
  3779. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3780. [favoriteButton centerIconOverText];
  3781. //Right
  3782. 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]]];
  3783. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3784. //centerIconOverText
  3785. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3786. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3787. [deleteButton centerIconOverText];
  3788. [moreButton centerIconOverText];
  3789. //restore swipeOffset after relod
  3790. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3791. if (swipeOffset < 0) {
  3792. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3793. [_statusSwipeCell removeObjectForKey:indexPath];
  3794. } else if (swipeOffset > 0) {
  3795. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3796. [_statusSwipeCell removeObjectForKey:indexPath];
  3797. }
  3798. return cell;
  3799. }
  3800. - (void)setTableViewFooter
  3801. {
  3802. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3803. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3804. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3805. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3806. UIFont *appFont = [UIFont systemFontOfSize:12];
  3807. footerLabel.font = appFont;
  3808. footerLabel.textColor = [UIColor grayColor];
  3809. footerLabel.backgroundColor = [UIColor clearColor];
  3810. footerLabel.textAlignment = NSTextAlignmentCenter;
  3811. NSString *folders;
  3812. NSString *files;
  3813. NSString *footerText;
  3814. if (_sectionDataSource.directories > 1) {
  3815. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3816. } else if (_sectionDataSource.directories == 1){
  3817. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3818. } else {
  3819. folders = @"";
  3820. }
  3821. if (_sectionDataSource.files > 1) {
  3822. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3823. } else if (_sectionDataSource.files == 1){
  3824. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3825. } else {
  3826. files = @"";
  3827. }
  3828. if ([folders isEqualToString:@""]) {
  3829. footerText = files;
  3830. } else if ([files isEqualToString:@""]) {
  3831. footerText = folders;
  3832. } else {
  3833. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3834. }
  3835. footerLabel.text = footerText;
  3836. [footerView addSubview:footerLabel];
  3837. [self.tableView setTableFooterView:footerView];
  3838. }
  3839. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3840. {
  3841. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3842. // settiamo il record file.
  3843. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3844. if (!_metadata)
  3845. return;
  3846. // se non può essere selezionata deseleziona
  3847. if ([cell isEditing] == NO)
  3848. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3849. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3850. if (self.tableView.editing) {
  3851. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3852. [self setTitle];
  3853. return;
  3854. }
  3855. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3856. if (!serverUrl) return;
  3857. // se è in corso una sessione
  3858. if ([_metadata.session length] > 0) return;
  3859. // file
  3860. if (_metadata.directory == NO) {
  3861. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3862. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3863. #ifdef DEBUG
  3864. // TEST ENCRYPTED/DECRYPTED
  3865. if ([_metadata.fileName containsString:@".dms"]) {
  3866. [[NCEndToEndEncryption sharedManager] decryptMetadata:_metadata activeUrl:app.directoryUser];
  3867. }
  3868. if ([_metadata.fileName containsString:@"test_encry_marino.jpg"]) {
  3869. [[NCEndToEndEncryption sharedManager] encryptMetadata:_metadata activeUrl:app.directoryUser];
  3870. }
  3871. #endif
  3872. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3873. } else {
  3874. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3875. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3876. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3877. }
  3878. }
  3879. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3880. }
  3881. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3882. {
  3883. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3884. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3885. [self setTitle];
  3886. }
  3887. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3888. {
  3889. if (!indexPath)
  3890. return NO;
  3891. NSInteger section = indexPath.section;
  3892. NSInteger row = indexPath.row;
  3893. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3894. if (section > lastSectionIndex || lastSectionIndex < 0)
  3895. return NO;
  3896. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3897. if (rowCount < 0)
  3898. return NO;
  3899. return row <= rowCount;
  3900. }
  3901. #pragma --------------------------------------------------------------------------------------------
  3902. #pragma mark ===== Navigation ====
  3903. #pragma --------------------------------------------------------------------------------------------
  3904. - (BOOL)shouldPerformSegue
  3905. {
  3906. // if background return
  3907. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3908. if (self.view.window == NO)
  3909. return NO;
  3910. // Collapsed ma siamo già in detail esci
  3911. if (self.splitViewController.isCollapsed)
  3912. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3913. return YES;
  3914. }
  3915. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3916. {
  3917. id viewController = segue.destinationViewController;
  3918. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3919. tableMetadata *metadata;
  3920. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3921. UINavigationController *nav = viewController;
  3922. _detailViewController = (CCDetail *)nav.topViewController;
  3923. } else {
  3924. _detailViewController = segue.destinationViewController;
  3925. }
  3926. if ([sender isKindOfClass:[tableMetadata class]]) {
  3927. metadata = sender;
  3928. [allRecordsDataSourceImagesVideos addObject:sender];
  3929. } else {
  3930. metadata = _metadata;
  3931. for (NSString *fileID in _sectionDataSource.allEtag) {
  3932. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3933. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3934. [allRecordsDataSourceImagesVideos addObject:metadata];
  3935. }
  3936. }
  3937. _detailViewController.metadataDetail = metadata;
  3938. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3939. _detailViewController.dateFilterQuery = nil;
  3940. [_detailViewController setTitle:metadata.fileName];
  3941. }
  3942. // can i go to next viewcontroller
  3943. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3944. {
  3945. NSString *nomeDir;
  3946. if(self.tableView.editing == NO) {
  3947. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3948. if (!serverUrl) return;
  3949. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3950. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3951. // 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
  3952. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3953. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3954. viewController.delegate = self;
  3955. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3956. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3957. viewController.inputViewTitlePassword = YES;
  3958. if ([CCUtility getSimplyBlockCode]) {
  3959. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3960. viewController.passcodeInputView.maximumLength = 6;
  3961. } else {
  3962. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3963. viewController.passcodeInputView.maximumLength = 64;
  3964. }
  3965. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3966. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3967. viewController.touchIDManager = touchIDManager;
  3968. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3969. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3970. //viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3971. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3972. [self presentViewController:navController animated:YES completion:nil];
  3973. return;
  3974. }
  3975. nomeDir = _metadata.fileName;
  3976. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3977. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3978. if (!viewController) {
  3979. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3980. viewController.serverUrl = serverUrlPush;
  3981. viewController.titleMain = _metadata.fileName;
  3982. viewController.textBackButton = _titleMain;
  3983. // save self
  3984. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3985. [self.navigationController pushViewController:viewController animated:YES];
  3986. } else {
  3987. if (viewController.isViewLoaded) {
  3988. // Fix : Application tried to present modally an active controller
  3989. if ([self.navigationController isBeingPresented]) {
  3990. // being presented
  3991. } else if ([self.navigationController isMovingToParentViewController]) {
  3992. // being pushed
  3993. } else {
  3994. [self.navigationController pushViewController:viewController animated:YES];
  3995. }
  3996. }
  3997. }
  3998. }
  3999. }
  4000. @end