CCMain.m 237 KB

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