CCMain.m 233 KB

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