CCMain.m 238 KB

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