CCMain.m 238 KB

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