CCMain.m 241 KB

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