CCMain.m 238 KB

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