CCMain.m 237 KB

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