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