im-node.js 196 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  4. var platformAdaptersNode = require('@leancloud/platform-adapters-node');
  5. var protobufLight = _interopDefault(require('protobufjs/dist/protobuf-light'));
  6. var EventEmitter = _interopDefault(require('eventemitter3'));
  7. var d = _interopDefault(require('debug'));
  8. var shuffle = _interopDefault(require('lodash/shuffle'));
  9. var values = _interopDefault(require('lodash/values'));
  10. var StateMachine = _interopDefault(require('javascript-state-machine'));
  11. var isPlainObject = _interopDefault(require('lodash/isPlainObject'));
  12. var promiseTimeout = require('promise-timeout');
  13. var uuid = _interopDefault(require('uuid/v4'));
  14. var base64Arraybuffer = require('base64-arraybuffer');
  15. var remove = _interopDefault(require('lodash/remove'));
  16. var isEmpty = _interopDefault(require('lodash/isEmpty'));
  17. var cloneDeep = _interopDefault(require('lodash/cloneDeep'));
  18. var find = _interopDefault(require('lodash/find'));
  19. var get = _interopDefault(require('lodash/get'));
  20. var messageCompiled = protobufLight.newBuilder({})['import']({
  21. package: 'push_server.messages2',
  22. syntax: 'proto2',
  23. options: {
  24. objc_class_prefix: 'AVIM'
  25. },
  26. messages: [{
  27. name: 'JsonObjectMessage',
  28. syntax: 'proto2',
  29. fields: [{
  30. rule: 'required',
  31. type: 'string',
  32. name: 'data',
  33. id: 1
  34. }]
  35. }, {
  36. name: 'UnreadTuple',
  37. syntax: 'proto2',
  38. fields: [{
  39. rule: 'required',
  40. type: 'string',
  41. name: 'cid',
  42. id: 1
  43. }, {
  44. rule: 'required',
  45. type: 'int32',
  46. name: 'unread',
  47. id: 2
  48. }, {
  49. rule: 'optional',
  50. type: 'string',
  51. name: 'mid',
  52. id: 3
  53. }, {
  54. rule: 'optional',
  55. type: 'int64',
  56. name: 'timestamp',
  57. id: 4
  58. }, {
  59. rule: 'optional',
  60. type: 'string',
  61. name: 'from',
  62. id: 5
  63. }, {
  64. rule: 'optional',
  65. type: 'string',
  66. name: 'data',
  67. id: 6
  68. }, {
  69. rule: 'optional',
  70. type: 'int64',
  71. name: 'patchTimestamp',
  72. id: 7
  73. }, {
  74. rule: 'optional',
  75. type: 'bool',
  76. name: 'mentioned',
  77. id: 8
  78. }, {
  79. rule: 'optional',
  80. type: 'bytes',
  81. name: 'binaryMsg',
  82. id: 9
  83. }, {
  84. rule: 'optional',
  85. type: 'int32',
  86. name: 'convType',
  87. id: 10
  88. }]
  89. }, {
  90. name: 'LogItem',
  91. syntax: 'proto2',
  92. fields: [{
  93. rule: 'optional',
  94. type: 'string',
  95. name: 'from',
  96. id: 1
  97. }, {
  98. rule: 'optional',
  99. type: 'string',
  100. name: 'data',
  101. id: 2
  102. }, {
  103. rule: 'optional',
  104. type: 'int64',
  105. name: 'timestamp',
  106. id: 3
  107. }, {
  108. rule: 'optional',
  109. type: 'string',
  110. name: 'msgId',
  111. id: 4
  112. }, {
  113. rule: 'optional',
  114. type: 'int64',
  115. name: 'ackAt',
  116. id: 5
  117. }, {
  118. rule: 'optional',
  119. type: 'int64',
  120. name: 'readAt',
  121. id: 6
  122. }, {
  123. rule: 'optional',
  124. type: 'int64',
  125. name: 'patchTimestamp',
  126. id: 7
  127. }, {
  128. rule: 'optional',
  129. type: 'bool',
  130. name: 'mentionAll',
  131. id: 8
  132. }, {
  133. rule: 'repeated',
  134. type: 'string',
  135. name: 'mentionPids',
  136. id: 9
  137. }, {
  138. rule: 'optional',
  139. type: 'bool',
  140. name: 'bin',
  141. id: 10
  142. }, {
  143. rule: 'optional',
  144. type: 'int32',
  145. name: 'convType',
  146. id: 11
  147. }]
  148. }, {
  149. name: 'ConvMemberInfo',
  150. syntax: 'proto2',
  151. fields: [{
  152. rule: 'optional',
  153. type: 'string',
  154. name: 'pid',
  155. id: 1
  156. }, {
  157. rule: 'optional',
  158. type: 'string',
  159. name: 'role',
  160. id: 2
  161. }, {
  162. rule: 'optional',
  163. type: 'string',
  164. name: 'infoId',
  165. id: 3
  166. }]
  167. }, {
  168. name: 'DataCommand',
  169. syntax: 'proto2',
  170. fields: [{
  171. rule: 'repeated',
  172. type: 'string',
  173. name: 'ids',
  174. id: 1
  175. }, {
  176. rule: 'repeated',
  177. type: 'JsonObjectMessage',
  178. name: 'msg',
  179. id: 2
  180. }, {
  181. rule: 'optional',
  182. type: 'bool',
  183. name: 'offline',
  184. id: 3
  185. }]
  186. }, {
  187. name: 'SessionCommand',
  188. syntax: 'proto2',
  189. fields: [{
  190. rule: 'optional',
  191. type: 'int64',
  192. name: 't',
  193. id: 1
  194. }, {
  195. rule: 'optional',
  196. type: 'string',
  197. name: 'n',
  198. id: 2
  199. }, {
  200. rule: 'optional',
  201. type: 'string',
  202. name: 's',
  203. id: 3
  204. }, {
  205. rule: 'optional',
  206. type: 'string',
  207. name: 'ua',
  208. id: 4
  209. }, {
  210. rule: 'optional',
  211. type: 'bool',
  212. name: 'r',
  213. id: 5
  214. }, {
  215. rule: 'optional',
  216. type: 'string',
  217. name: 'tag',
  218. id: 6
  219. }, {
  220. rule: 'optional',
  221. type: 'string',
  222. name: 'deviceId',
  223. id: 7
  224. }, {
  225. rule: 'repeated',
  226. type: 'string',
  227. name: 'sessionPeerIds',
  228. id: 8
  229. }, {
  230. rule: 'repeated',
  231. type: 'string',
  232. name: 'onlineSessionPeerIds',
  233. id: 9
  234. }, {
  235. rule: 'optional',
  236. type: 'string',
  237. name: 'st',
  238. id: 10
  239. }, {
  240. rule: 'optional',
  241. type: 'int32',
  242. name: 'stTtl',
  243. id: 11
  244. }, {
  245. rule: 'optional',
  246. type: 'int32',
  247. name: 'code',
  248. id: 12
  249. }, {
  250. rule: 'optional',
  251. type: 'string',
  252. name: 'reason',
  253. id: 13
  254. }, {
  255. rule: 'optional',
  256. type: 'string',
  257. name: 'deviceToken',
  258. id: 14
  259. }, {
  260. rule: 'optional',
  261. type: 'bool',
  262. name: 'sp',
  263. id: 15
  264. }, {
  265. rule: 'optional',
  266. type: 'string',
  267. name: 'detail',
  268. id: 16
  269. }, {
  270. rule: 'optional',
  271. type: 'int64',
  272. name: 'lastUnreadNotifTime',
  273. id: 17
  274. }, {
  275. rule: 'optional',
  276. type: 'int64',
  277. name: 'lastPatchTime',
  278. id: 18
  279. }, {
  280. rule: 'optional',
  281. type: 'int64',
  282. name: 'configBitmap',
  283. id: 19
  284. }]
  285. }, {
  286. name: 'ErrorCommand',
  287. syntax: 'proto2',
  288. fields: [{
  289. rule: 'required',
  290. type: 'int32',
  291. name: 'code',
  292. id: 1
  293. }, {
  294. rule: 'required',
  295. type: 'string',
  296. name: 'reason',
  297. id: 2
  298. }, {
  299. rule: 'optional',
  300. type: 'int32',
  301. name: 'appCode',
  302. id: 3
  303. }, {
  304. rule: 'optional',
  305. type: 'string',
  306. name: 'detail',
  307. id: 4
  308. }, {
  309. rule: 'repeated',
  310. type: 'string',
  311. name: 'pids',
  312. id: 5
  313. }, {
  314. rule: 'optional',
  315. type: 'string',
  316. name: 'appMsg',
  317. id: 6
  318. }]
  319. }, {
  320. name: 'DirectCommand',
  321. syntax: 'proto2',
  322. fields: [{
  323. rule: 'optional',
  324. type: 'string',
  325. name: 'msg',
  326. id: 1
  327. }, {
  328. rule: 'optional',
  329. type: 'string',
  330. name: 'uid',
  331. id: 2
  332. }, {
  333. rule: 'optional',
  334. type: 'string',
  335. name: 'fromPeerId',
  336. id: 3
  337. }, {
  338. rule: 'optional',
  339. type: 'int64',
  340. name: 'timestamp',
  341. id: 4
  342. }, {
  343. rule: 'optional',
  344. type: 'bool',
  345. name: 'offline',
  346. id: 5
  347. }, {
  348. rule: 'optional',
  349. type: 'bool',
  350. name: 'hasMore',
  351. id: 6
  352. }, {
  353. rule: 'repeated',
  354. type: 'string',
  355. name: 'toPeerIds',
  356. id: 7
  357. }, {
  358. rule: 'optional',
  359. type: 'bool',
  360. name: 'r',
  361. id: 10
  362. }, {
  363. rule: 'optional',
  364. type: 'string',
  365. name: 'cid',
  366. id: 11
  367. }, {
  368. rule: 'optional',
  369. type: 'string',
  370. name: 'id',
  371. id: 12
  372. }, {
  373. rule: 'optional',
  374. type: 'bool',
  375. name: 'transient',
  376. id: 13
  377. }, {
  378. rule: 'optional',
  379. type: 'string',
  380. name: 'dt',
  381. id: 14
  382. }, {
  383. rule: 'optional',
  384. type: 'string',
  385. name: 'roomId',
  386. id: 15
  387. }, {
  388. rule: 'optional',
  389. type: 'string',
  390. name: 'pushData',
  391. id: 16
  392. }, {
  393. rule: 'optional',
  394. type: 'bool',
  395. name: 'will',
  396. id: 17
  397. }, {
  398. rule: 'optional',
  399. type: 'int64',
  400. name: 'patchTimestamp',
  401. id: 18
  402. }, {
  403. rule: 'optional',
  404. type: 'bytes',
  405. name: 'binaryMsg',
  406. id: 19
  407. }, {
  408. rule: 'repeated',
  409. type: 'string',
  410. name: 'mentionPids',
  411. id: 20
  412. }, {
  413. rule: 'optional',
  414. type: 'bool',
  415. name: 'mentionAll',
  416. id: 21
  417. }, {
  418. rule: 'optional',
  419. type: 'int32',
  420. name: 'convType',
  421. id: 22
  422. }]
  423. }, {
  424. name: 'AckCommand',
  425. syntax: 'proto2',
  426. fields: [{
  427. rule: 'optional',
  428. type: 'int32',
  429. name: 'code',
  430. id: 1
  431. }, {
  432. rule: 'optional',
  433. type: 'string',
  434. name: 'reason',
  435. id: 2
  436. }, {
  437. rule: 'optional',
  438. type: 'string',
  439. name: 'mid',
  440. id: 3
  441. }, {
  442. rule: 'optional',
  443. type: 'string',
  444. name: 'cid',
  445. id: 4
  446. }, {
  447. rule: 'optional',
  448. type: 'int64',
  449. name: 't',
  450. id: 5
  451. }, {
  452. rule: 'optional',
  453. type: 'string',
  454. name: 'uid',
  455. id: 6
  456. }, {
  457. rule: 'optional',
  458. type: 'int64',
  459. name: 'fromts',
  460. id: 7
  461. }, {
  462. rule: 'optional',
  463. type: 'int64',
  464. name: 'tots',
  465. id: 8
  466. }, {
  467. rule: 'optional',
  468. type: 'string',
  469. name: 'type',
  470. id: 9
  471. }, {
  472. rule: 'repeated',
  473. type: 'string',
  474. name: 'ids',
  475. id: 10
  476. }, {
  477. rule: 'optional',
  478. type: 'int32',
  479. name: 'appCode',
  480. id: 11
  481. }, {
  482. rule: 'optional',
  483. type: 'string',
  484. name: 'appMsg',
  485. id: 12
  486. }]
  487. }, {
  488. name: 'UnreadCommand',
  489. syntax: 'proto2',
  490. fields: [{
  491. rule: 'repeated',
  492. type: 'UnreadTuple',
  493. name: 'convs',
  494. id: 1
  495. }, {
  496. rule: 'optional',
  497. type: 'int64',
  498. name: 'notifTime',
  499. id: 2
  500. }]
  501. }, {
  502. name: 'ConvCommand',
  503. syntax: 'proto2',
  504. fields: [{
  505. rule: 'repeated',
  506. type: 'string',
  507. name: 'm',
  508. id: 1
  509. }, {
  510. rule: 'optional',
  511. type: 'bool',
  512. name: 'transient',
  513. id: 2
  514. }, {
  515. rule: 'optional',
  516. type: 'bool',
  517. name: 'unique',
  518. id: 3
  519. }, {
  520. rule: 'optional',
  521. type: 'string',
  522. name: 'cid',
  523. id: 4
  524. }, {
  525. rule: 'optional',
  526. type: 'string',
  527. name: 'cdate',
  528. id: 5
  529. }, {
  530. rule: 'optional',
  531. type: 'string',
  532. name: 'initBy',
  533. id: 6
  534. }, {
  535. rule: 'optional',
  536. type: 'string',
  537. name: 'sort',
  538. id: 7
  539. }, {
  540. rule: 'optional',
  541. type: 'int32',
  542. name: 'limit',
  543. id: 8
  544. }, {
  545. rule: 'optional',
  546. type: 'int32',
  547. name: 'skip',
  548. id: 9
  549. }, {
  550. rule: 'optional',
  551. type: 'int32',
  552. name: 'flag',
  553. id: 10
  554. }, {
  555. rule: 'optional',
  556. type: 'int32',
  557. name: 'count',
  558. id: 11
  559. }, {
  560. rule: 'optional',
  561. type: 'string',
  562. name: 'udate',
  563. id: 12
  564. }, {
  565. rule: 'optional',
  566. type: 'int64',
  567. name: 't',
  568. id: 13
  569. }, {
  570. rule: 'optional',
  571. type: 'string',
  572. name: 'n',
  573. id: 14
  574. }, {
  575. rule: 'optional',
  576. type: 'string',
  577. name: 's',
  578. id: 15
  579. }, {
  580. rule: 'optional',
  581. type: 'bool',
  582. name: 'statusSub',
  583. id: 16
  584. }, {
  585. rule: 'optional',
  586. type: 'bool',
  587. name: 'statusPub',
  588. id: 17
  589. }, {
  590. rule: 'optional',
  591. type: 'int32',
  592. name: 'statusTTL',
  593. id: 18
  594. }, {
  595. rule: 'optional',
  596. type: 'string',
  597. name: 'uniqueId',
  598. id: 19
  599. }, {
  600. rule: 'optional',
  601. type: 'string',
  602. name: 'targetClientId',
  603. id: 20
  604. }, {
  605. rule: 'optional',
  606. type: 'int64',
  607. name: 'maxReadTimestamp',
  608. id: 21
  609. }, {
  610. rule: 'optional',
  611. type: 'int64',
  612. name: 'maxAckTimestamp',
  613. id: 22
  614. }, {
  615. rule: 'optional',
  616. type: 'bool',
  617. name: 'queryAllMembers',
  618. id: 23
  619. }, {
  620. rule: 'repeated',
  621. type: 'MaxReadTuple',
  622. name: 'maxReadTuples',
  623. id: 24
  624. }, {
  625. rule: 'repeated',
  626. type: 'string',
  627. name: 'cids',
  628. id: 25
  629. }, {
  630. rule: 'optional',
  631. type: 'ConvMemberInfo',
  632. name: 'info',
  633. id: 26
  634. }, {
  635. rule: 'optional',
  636. type: 'bool',
  637. name: 'tempConv',
  638. id: 27
  639. }, {
  640. rule: 'optional',
  641. type: 'int32',
  642. name: 'tempConvTTL',
  643. id: 28
  644. }, {
  645. rule: 'repeated',
  646. type: 'string',
  647. name: 'tempConvIds',
  648. id: 29
  649. }, {
  650. rule: 'repeated',
  651. type: 'string',
  652. name: 'allowedPids',
  653. id: 30
  654. }, {
  655. rule: 'repeated',
  656. type: 'ErrorCommand',
  657. name: 'failedPids',
  658. id: 31
  659. }, {
  660. rule: 'optional',
  661. type: 'string',
  662. name: 'next',
  663. id: 40
  664. }, {
  665. rule: 'optional',
  666. type: 'JsonObjectMessage',
  667. name: 'results',
  668. id: 100
  669. }, {
  670. rule: 'optional',
  671. type: 'JsonObjectMessage',
  672. name: 'where',
  673. id: 101
  674. }, {
  675. rule: 'optional',
  676. type: 'JsonObjectMessage',
  677. name: 'attr',
  678. id: 103
  679. }, {
  680. rule: 'optional',
  681. type: 'JsonObjectMessage',
  682. name: 'attrModified',
  683. id: 104
  684. }]
  685. }, {
  686. name: 'RoomCommand',
  687. syntax: 'proto2',
  688. fields: [{
  689. rule: 'optional',
  690. type: 'string',
  691. name: 'roomId',
  692. id: 1
  693. }, {
  694. rule: 'optional',
  695. type: 'string',
  696. name: 's',
  697. id: 2
  698. }, {
  699. rule: 'optional',
  700. type: 'int64',
  701. name: 't',
  702. id: 3
  703. }, {
  704. rule: 'optional',
  705. type: 'string',
  706. name: 'n',
  707. id: 4
  708. }, {
  709. rule: 'optional',
  710. type: 'bool',
  711. name: 'transient',
  712. id: 5
  713. }, {
  714. rule: 'repeated',
  715. type: 'string',
  716. name: 'roomPeerIds',
  717. id: 6
  718. }, {
  719. rule: 'optional',
  720. type: 'string',
  721. name: 'byPeerId',
  722. id: 7
  723. }]
  724. }, {
  725. name: 'LogsCommand',
  726. syntax: 'proto2',
  727. fields: [{
  728. rule: 'optional',
  729. type: 'string',
  730. name: 'cid',
  731. id: 1
  732. }, {
  733. rule: 'optional',
  734. type: 'int32',
  735. name: 'l',
  736. id: 2
  737. }, {
  738. rule: 'optional',
  739. type: 'int32',
  740. name: 'limit',
  741. id: 3
  742. }, {
  743. rule: 'optional',
  744. type: 'int64',
  745. name: 't',
  746. id: 4
  747. }, {
  748. rule: 'optional',
  749. type: 'int64',
  750. name: 'tt',
  751. id: 5
  752. }, {
  753. rule: 'optional',
  754. type: 'string',
  755. name: 'tmid',
  756. id: 6
  757. }, {
  758. rule: 'optional',
  759. type: 'string',
  760. name: 'mid',
  761. id: 7
  762. }, {
  763. rule: 'optional',
  764. type: 'string',
  765. name: 'checksum',
  766. id: 8
  767. }, {
  768. rule: 'optional',
  769. type: 'bool',
  770. name: 'stored',
  771. id: 9
  772. }, {
  773. rule: 'optional',
  774. type: 'QueryDirection',
  775. name: 'direction',
  776. id: 10,
  777. options: {
  778. default: 'OLD'
  779. }
  780. }, {
  781. rule: 'optional',
  782. type: 'bool',
  783. name: 'tIncluded',
  784. id: 11
  785. }, {
  786. rule: 'optional',
  787. type: 'bool',
  788. name: 'ttIncluded',
  789. id: 12
  790. }, {
  791. rule: 'optional',
  792. type: 'int32',
  793. name: 'lctype',
  794. id: 13
  795. }, {
  796. rule: 'repeated',
  797. type: 'LogItem',
  798. name: 'logs',
  799. id: 105
  800. }],
  801. enums: [{
  802. name: 'QueryDirection',
  803. syntax: 'proto2',
  804. values: [{
  805. name: 'OLD',
  806. id: 1
  807. }, {
  808. name: 'NEW',
  809. id: 2
  810. }]
  811. }]
  812. }, {
  813. name: 'RcpCommand',
  814. syntax: 'proto2',
  815. fields: [{
  816. rule: 'optional',
  817. type: 'string',
  818. name: 'id',
  819. id: 1
  820. }, {
  821. rule: 'optional',
  822. type: 'string',
  823. name: 'cid',
  824. id: 2
  825. }, {
  826. rule: 'optional',
  827. type: 'int64',
  828. name: 't',
  829. id: 3
  830. }, {
  831. rule: 'optional',
  832. type: 'bool',
  833. name: 'read',
  834. id: 4
  835. }, {
  836. rule: 'optional',
  837. type: 'string',
  838. name: 'from',
  839. id: 5
  840. }]
  841. }, {
  842. name: 'ReadTuple',
  843. syntax: 'proto2',
  844. fields: [{
  845. rule: 'required',
  846. type: 'string',
  847. name: 'cid',
  848. id: 1
  849. }, {
  850. rule: 'optional',
  851. type: 'int64',
  852. name: 'timestamp',
  853. id: 2
  854. }, {
  855. rule: 'optional',
  856. type: 'string',
  857. name: 'mid',
  858. id: 3
  859. }]
  860. }, {
  861. name: 'MaxReadTuple',
  862. syntax: 'proto2',
  863. fields: [{
  864. rule: 'optional',
  865. type: 'string',
  866. name: 'pid',
  867. id: 1
  868. }, {
  869. rule: 'optional',
  870. type: 'int64',
  871. name: 'maxAckTimestamp',
  872. id: 2
  873. }, {
  874. rule: 'optional',
  875. type: 'int64',
  876. name: 'maxReadTimestamp',
  877. id: 3
  878. }]
  879. }, {
  880. name: 'ReadCommand',
  881. syntax: 'proto2',
  882. fields: [{
  883. rule: 'optional',
  884. type: 'string',
  885. name: 'cid',
  886. id: 1
  887. }, {
  888. rule: 'repeated',
  889. type: 'string',
  890. name: 'cids',
  891. id: 2
  892. }, {
  893. rule: 'repeated',
  894. type: 'ReadTuple',
  895. name: 'convs',
  896. id: 3
  897. }]
  898. }, {
  899. name: 'PresenceCommand',
  900. syntax: 'proto2',
  901. fields: [{
  902. rule: 'optional',
  903. type: 'StatusType',
  904. name: 'status',
  905. id: 1
  906. }, {
  907. rule: 'repeated',
  908. type: 'string',
  909. name: 'sessionPeerIds',
  910. id: 2
  911. }, {
  912. rule: 'optional',
  913. type: 'string',
  914. name: 'cid',
  915. id: 3
  916. }]
  917. }, {
  918. name: 'ReportCommand',
  919. syntax: 'proto2',
  920. fields: [{
  921. rule: 'optional',
  922. type: 'bool',
  923. name: 'initiative',
  924. id: 1
  925. }, {
  926. rule: 'optional',
  927. type: 'string',
  928. name: 'type',
  929. id: 2
  930. }, {
  931. rule: 'optional',
  932. type: 'string',
  933. name: 'data',
  934. id: 3
  935. }]
  936. }, {
  937. name: 'PatchItem',
  938. syntax: 'proto2',
  939. fields: [{
  940. rule: 'optional',
  941. type: 'string',
  942. name: 'cid',
  943. id: 1
  944. }, {
  945. rule: 'optional',
  946. type: 'string',
  947. name: 'mid',
  948. id: 2
  949. }, {
  950. rule: 'optional',
  951. type: 'int64',
  952. name: 'timestamp',
  953. id: 3
  954. }, {
  955. rule: 'optional',
  956. type: 'bool',
  957. name: 'recall',
  958. id: 4
  959. }, {
  960. rule: 'optional',
  961. type: 'string',
  962. name: 'data',
  963. id: 5
  964. }, {
  965. rule: 'optional',
  966. type: 'int64',
  967. name: 'patchTimestamp',
  968. id: 6
  969. }, {
  970. rule: 'optional',
  971. type: 'string',
  972. name: 'from',
  973. id: 7
  974. }, {
  975. rule: 'optional',
  976. type: 'bytes',
  977. name: 'binaryMsg',
  978. id: 8
  979. }, {
  980. rule: 'optional',
  981. type: 'bool',
  982. name: 'mentionAll',
  983. id: 9
  984. }, {
  985. rule: 'repeated',
  986. type: 'string',
  987. name: 'mentionPids',
  988. id: 10
  989. }, {
  990. rule: 'optional',
  991. type: 'int64',
  992. name: 'patchCode',
  993. id: 11
  994. }, {
  995. rule: 'optional',
  996. type: 'string',
  997. name: 'patchReason',
  998. id: 12
  999. }]
  1000. }, {
  1001. name: 'PatchCommand',
  1002. syntax: 'proto2',
  1003. fields: [{
  1004. rule: 'repeated',
  1005. type: 'PatchItem',
  1006. name: 'patches',
  1007. id: 1
  1008. }, {
  1009. rule: 'optional',
  1010. type: 'int64',
  1011. name: 'lastPatchTime',
  1012. id: 2
  1013. }]
  1014. }, {
  1015. name: 'PubsubCommand',
  1016. syntax: 'proto2',
  1017. fields: [{
  1018. rule: 'optional',
  1019. type: 'string',
  1020. name: 'cid',
  1021. id: 1
  1022. }, {
  1023. rule: 'repeated',
  1024. type: 'string',
  1025. name: 'cids',
  1026. id: 2
  1027. }, {
  1028. rule: 'optional',
  1029. type: 'string',
  1030. name: 'topic',
  1031. id: 3
  1032. }, {
  1033. rule: 'optional',
  1034. type: 'string',
  1035. name: 'subtopic',
  1036. id: 4
  1037. }, {
  1038. rule: 'repeated',
  1039. type: 'string',
  1040. name: 'topics',
  1041. id: 5
  1042. }, {
  1043. rule: 'repeated',
  1044. type: 'string',
  1045. name: 'subtopics',
  1046. id: 6
  1047. }, {
  1048. rule: 'optional',
  1049. type: 'JsonObjectMessage',
  1050. name: 'results',
  1051. id: 7
  1052. }]
  1053. }, {
  1054. name: 'BlacklistCommand',
  1055. syntax: 'proto2',
  1056. fields: [{
  1057. rule: 'optional',
  1058. type: 'string',
  1059. name: 'srcCid',
  1060. id: 1
  1061. }, {
  1062. rule: 'repeated',
  1063. type: 'string',
  1064. name: 'toPids',
  1065. id: 2
  1066. }, {
  1067. rule: 'optional',
  1068. type: 'string',
  1069. name: 'srcPid',
  1070. id: 3
  1071. }, {
  1072. rule: 'repeated',
  1073. type: 'string',
  1074. name: 'toCids',
  1075. id: 4
  1076. }, {
  1077. rule: 'optional',
  1078. type: 'int32',
  1079. name: 'limit',
  1080. id: 5
  1081. }, {
  1082. rule: 'optional',
  1083. type: 'string',
  1084. name: 'next',
  1085. id: 6
  1086. }, {
  1087. rule: 'repeated',
  1088. type: 'string',
  1089. name: 'blockedPids',
  1090. id: 8
  1091. }, {
  1092. rule: 'repeated',
  1093. type: 'string',
  1094. name: 'blockedCids',
  1095. id: 9
  1096. }, {
  1097. rule: 'repeated',
  1098. type: 'string',
  1099. name: 'allowedPids',
  1100. id: 10
  1101. }, {
  1102. rule: 'repeated',
  1103. type: 'ErrorCommand',
  1104. name: 'failedPids',
  1105. id: 11
  1106. }, {
  1107. rule: 'optional',
  1108. type: 'int64',
  1109. name: 't',
  1110. id: 12
  1111. }, {
  1112. rule: 'optional',
  1113. type: 'string',
  1114. name: 'n',
  1115. id: 13
  1116. }, {
  1117. rule: 'optional',
  1118. type: 'string',
  1119. name: 's',
  1120. id: 14
  1121. }]
  1122. }, {
  1123. name: 'GenericCommand',
  1124. syntax: 'proto2',
  1125. fields: [{
  1126. rule: 'optional',
  1127. type: 'CommandType',
  1128. name: 'cmd',
  1129. id: 1
  1130. }, {
  1131. rule: 'optional',
  1132. type: 'OpType',
  1133. name: 'op',
  1134. id: 2
  1135. }, {
  1136. rule: 'optional',
  1137. type: 'string',
  1138. name: 'appId',
  1139. id: 3
  1140. }, {
  1141. rule: 'optional',
  1142. type: 'string',
  1143. name: 'peerId',
  1144. id: 4
  1145. }, {
  1146. rule: 'optional',
  1147. type: 'int32',
  1148. name: 'i',
  1149. id: 5
  1150. }, {
  1151. rule: 'optional',
  1152. type: 'string',
  1153. name: 'installationId',
  1154. id: 6
  1155. }, {
  1156. rule: 'optional',
  1157. type: 'int32',
  1158. name: 'priority',
  1159. id: 7
  1160. }, {
  1161. rule: 'optional',
  1162. type: 'int32',
  1163. name: 'service',
  1164. id: 8
  1165. }, {
  1166. rule: 'optional',
  1167. type: 'int64',
  1168. name: 'serverTs',
  1169. id: 9
  1170. }, {
  1171. rule: 'optional',
  1172. type: 'int64',
  1173. name: 'clientTs',
  1174. id: 10
  1175. }, {
  1176. rule: 'optional',
  1177. type: 'int32',
  1178. name: 'notificationType',
  1179. id: 11
  1180. }, {
  1181. rule: 'optional',
  1182. type: 'DataCommand',
  1183. name: 'dataMessage',
  1184. id: 101
  1185. }, {
  1186. rule: 'optional',
  1187. type: 'SessionCommand',
  1188. name: 'sessionMessage',
  1189. id: 102
  1190. }, {
  1191. rule: 'optional',
  1192. type: 'ErrorCommand',
  1193. name: 'errorMessage',
  1194. id: 103
  1195. }, {
  1196. rule: 'optional',
  1197. type: 'DirectCommand',
  1198. name: 'directMessage',
  1199. id: 104
  1200. }, {
  1201. rule: 'optional',
  1202. type: 'AckCommand',
  1203. name: 'ackMessage',
  1204. id: 105
  1205. }, {
  1206. rule: 'optional',
  1207. type: 'UnreadCommand',
  1208. name: 'unreadMessage',
  1209. id: 106
  1210. }, {
  1211. rule: 'optional',
  1212. type: 'ReadCommand',
  1213. name: 'readMessage',
  1214. id: 107
  1215. }, {
  1216. rule: 'optional',
  1217. type: 'RcpCommand',
  1218. name: 'rcpMessage',
  1219. id: 108
  1220. }, {
  1221. rule: 'optional',
  1222. type: 'LogsCommand',
  1223. name: 'logsMessage',
  1224. id: 109
  1225. }, {
  1226. rule: 'optional',
  1227. type: 'ConvCommand',
  1228. name: 'convMessage',
  1229. id: 110
  1230. }, {
  1231. rule: 'optional',
  1232. type: 'RoomCommand',
  1233. name: 'roomMessage',
  1234. id: 111
  1235. }, {
  1236. rule: 'optional',
  1237. type: 'PresenceCommand',
  1238. name: 'presenceMessage',
  1239. id: 112
  1240. }, {
  1241. rule: 'optional',
  1242. type: 'ReportCommand',
  1243. name: 'reportMessage',
  1244. id: 113
  1245. }, {
  1246. rule: 'optional',
  1247. type: 'PatchCommand',
  1248. name: 'patchMessage',
  1249. id: 114
  1250. }, {
  1251. rule: 'optional',
  1252. type: 'PubsubCommand',
  1253. name: 'pubsubMessage',
  1254. id: 115
  1255. }, {
  1256. rule: 'optional',
  1257. type: 'BlacklistCommand',
  1258. name: 'blacklistMessage',
  1259. id: 116
  1260. }]
  1261. }],
  1262. enums: [{
  1263. name: 'CommandType',
  1264. syntax: 'proto2',
  1265. values: [{
  1266. name: 'session',
  1267. id: 0
  1268. }, {
  1269. name: 'conv',
  1270. id: 1
  1271. }, {
  1272. name: 'direct',
  1273. id: 2
  1274. }, {
  1275. name: 'ack',
  1276. id: 3
  1277. }, {
  1278. name: 'rcp',
  1279. id: 4
  1280. }, {
  1281. name: 'unread',
  1282. id: 5
  1283. }, {
  1284. name: 'logs',
  1285. id: 6
  1286. }, {
  1287. name: 'error',
  1288. id: 7
  1289. }, {
  1290. name: 'login',
  1291. id: 8
  1292. }, {
  1293. name: 'data',
  1294. id: 9
  1295. }, {
  1296. name: 'room',
  1297. id: 10
  1298. }, {
  1299. name: 'read',
  1300. id: 11
  1301. }, {
  1302. name: 'presence',
  1303. id: 12
  1304. }, {
  1305. name: 'report',
  1306. id: 13
  1307. }, {
  1308. name: 'echo',
  1309. id: 14
  1310. }, {
  1311. name: 'loggedin',
  1312. id: 15
  1313. }, {
  1314. name: 'logout',
  1315. id: 16
  1316. }, {
  1317. name: 'loggedout',
  1318. id: 17
  1319. }, {
  1320. name: 'patch',
  1321. id: 18
  1322. }, {
  1323. name: 'pubsub',
  1324. id: 19
  1325. }, {
  1326. name: 'blacklist',
  1327. id: 20
  1328. }, {
  1329. name: 'goaway',
  1330. id: 21
  1331. }]
  1332. }, {
  1333. name: 'OpType',
  1334. syntax: 'proto2',
  1335. values: [{
  1336. name: 'open',
  1337. id: 1
  1338. }, {
  1339. name: 'add',
  1340. id: 2
  1341. }, {
  1342. name: 'remove',
  1343. id: 3
  1344. }, {
  1345. name: 'close',
  1346. id: 4
  1347. }, {
  1348. name: 'opened',
  1349. id: 5
  1350. }, {
  1351. name: 'closed',
  1352. id: 6
  1353. }, {
  1354. name: 'query',
  1355. id: 7
  1356. }, {
  1357. name: 'query_result',
  1358. id: 8
  1359. }, {
  1360. name: 'conflict',
  1361. id: 9
  1362. }, {
  1363. name: 'added',
  1364. id: 10
  1365. }, {
  1366. name: 'removed',
  1367. id: 11
  1368. }, {
  1369. name: 'refresh',
  1370. id: 12
  1371. }, {
  1372. name: 'refreshed',
  1373. id: 13
  1374. }, {
  1375. name: 'start',
  1376. id: 30
  1377. }, {
  1378. name: 'started',
  1379. id: 31
  1380. }, {
  1381. name: 'joined',
  1382. id: 32
  1383. }, {
  1384. name: 'members_joined',
  1385. id: 33
  1386. }, {
  1387. name: 'left',
  1388. id: 39
  1389. }, {
  1390. name: 'members_left',
  1391. id: 40
  1392. }, {
  1393. name: 'results',
  1394. id: 42
  1395. }, {
  1396. name: 'count',
  1397. id: 43
  1398. }, {
  1399. name: 'result',
  1400. id: 44
  1401. }, {
  1402. name: 'update',
  1403. id: 45
  1404. }, {
  1405. name: 'updated',
  1406. id: 46
  1407. }, {
  1408. name: 'mute',
  1409. id: 47
  1410. }, {
  1411. name: 'unmute',
  1412. id: 48
  1413. }, {
  1414. name: 'status',
  1415. id: 49
  1416. }, {
  1417. name: 'members',
  1418. id: 50
  1419. }, {
  1420. name: 'max_read',
  1421. id: 51
  1422. }, {
  1423. name: 'is_member',
  1424. id: 52
  1425. }, {
  1426. name: 'member_info_update',
  1427. id: 53
  1428. }, {
  1429. name: 'member_info_updated',
  1430. id: 54
  1431. }, {
  1432. name: 'member_info_changed',
  1433. id: 55
  1434. }, {
  1435. name: 'join',
  1436. id: 80
  1437. }, {
  1438. name: 'invite',
  1439. id: 81
  1440. }, {
  1441. name: 'leave',
  1442. id: 82
  1443. }, {
  1444. name: 'kick',
  1445. id: 83
  1446. }, {
  1447. name: 'reject',
  1448. id: 84
  1449. }, {
  1450. name: 'invited',
  1451. id: 85
  1452. }, {
  1453. name: 'kicked',
  1454. id: 86
  1455. }, {
  1456. name: 'upload',
  1457. id: 100
  1458. }, {
  1459. name: 'uploaded',
  1460. id: 101
  1461. }, {
  1462. name: 'subscribe',
  1463. id: 120
  1464. }, {
  1465. name: 'subscribed',
  1466. id: 121
  1467. }, {
  1468. name: 'unsubscribe',
  1469. id: 122
  1470. }, {
  1471. name: 'unsubscribed',
  1472. id: 123
  1473. }, {
  1474. name: 'is_subscribed',
  1475. id: 124
  1476. }, {
  1477. name: 'modify',
  1478. id: 150
  1479. }, {
  1480. name: 'modified',
  1481. id: 151
  1482. }, {
  1483. name: 'block',
  1484. id: 170
  1485. }, {
  1486. name: 'unblock',
  1487. id: 171
  1488. }, {
  1489. name: 'blocked',
  1490. id: 172
  1491. }, {
  1492. name: 'unblocked',
  1493. id: 173
  1494. }, {
  1495. name: 'members_blocked',
  1496. id: 174
  1497. }, {
  1498. name: 'members_unblocked',
  1499. id: 175
  1500. }, {
  1501. name: 'check_block',
  1502. id: 176
  1503. }, {
  1504. name: 'check_result',
  1505. id: 177
  1506. }, {
  1507. name: 'add_shutup',
  1508. id: 180
  1509. }, {
  1510. name: 'remove_shutup',
  1511. id: 181
  1512. }, {
  1513. name: 'query_shutup',
  1514. id: 182
  1515. }, {
  1516. name: 'shutup_added',
  1517. id: 183
  1518. }, {
  1519. name: 'shutup_removed',
  1520. id: 184
  1521. }, {
  1522. name: 'shutup_result',
  1523. id: 185
  1524. }, {
  1525. name: 'shutuped',
  1526. id: 186
  1527. }, {
  1528. name: 'unshutuped',
  1529. id: 187
  1530. }, {
  1531. name: 'members_shutuped',
  1532. id: 188
  1533. }, {
  1534. name: 'members_unshutuped',
  1535. id: 189
  1536. }, {
  1537. name: 'check_shutup',
  1538. id: 190
  1539. }]
  1540. }, {
  1541. name: 'StatusType',
  1542. syntax: 'proto2',
  1543. values: [{
  1544. name: 'on',
  1545. id: 1
  1546. }, {
  1547. name: 'off',
  1548. id: 2
  1549. }]
  1550. }],
  1551. isNamespace: true
  1552. }).build();
  1553. const {
  1554. JsonObjectMessage,
  1555. UnreadTuple,
  1556. LogItem,
  1557. DataCommand,
  1558. SessionCommand,
  1559. ErrorCommand,
  1560. DirectCommand,
  1561. AckCommand,
  1562. UnreadCommand,
  1563. ConvCommand,
  1564. RoomCommand,
  1565. LogsCommand,
  1566. RcpCommand,
  1567. ReadTuple,
  1568. MaxReadTuple,
  1569. ReadCommand,
  1570. PresenceCommand,
  1571. ReportCommand,
  1572. GenericCommand,
  1573. BlacklistCommand,
  1574. PatchCommand,
  1575. PatchItem,
  1576. ConvMemberInfo,
  1577. CommandType,
  1578. OpType,
  1579. StatusType
  1580. } = messageCompiled.push_server.messages2;
  1581. var message = /*#__PURE__*/Object.freeze({
  1582. __proto__: null,
  1583. JsonObjectMessage: JsonObjectMessage,
  1584. UnreadTuple: UnreadTuple,
  1585. LogItem: LogItem,
  1586. DataCommand: DataCommand,
  1587. SessionCommand: SessionCommand,
  1588. ErrorCommand: ErrorCommand,
  1589. DirectCommand: DirectCommand,
  1590. AckCommand: AckCommand,
  1591. UnreadCommand: UnreadCommand,
  1592. ConvCommand: ConvCommand,
  1593. RoomCommand: RoomCommand,
  1594. LogsCommand: LogsCommand,
  1595. RcpCommand: RcpCommand,
  1596. ReadTuple: ReadTuple,
  1597. MaxReadTuple: MaxReadTuple,
  1598. ReadCommand: ReadCommand,
  1599. PresenceCommand: PresenceCommand,
  1600. ReportCommand: ReportCommand,
  1601. GenericCommand: GenericCommand,
  1602. BlacklistCommand: BlacklistCommand,
  1603. PatchCommand: PatchCommand,
  1604. PatchItem: PatchItem,
  1605. ConvMemberInfo: ConvMemberInfo,
  1606. CommandType: CommandType,
  1607. OpType: OpType,
  1608. StatusType: StatusType
  1609. });
  1610. function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  1611. var desc = {};
  1612. Object.keys(descriptor).forEach(function (key) {
  1613. desc[key] = descriptor[key];
  1614. });
  1615. desc.enumerable = !!desc.enumerable;
  1616. desc.configurable = !!desc.configurable;
  1617. if ('value' in desc || desc.initializer) {
  1618. desc.writable = true;
  1619. }
  1620. desc = decorators.slice().reverse().reduce(function (desc, decorator) {
  1621. return decorator(target, property, desc) || desc;
  1622. }, desc);
  1623. if (context && desc.initializer !== void 0) {
  1624. desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
  1625. desc.initializer = undefined;
  1626. }
  1627. if (desc.initializer === void 0) {
  1628. Object.defineProperty(target, property, desc);
  1629. desc = null;
  1630. }
  1631. return desc;
  1632. }
  1633. const adapters = {};
  1634. const getAdapter = name => {
  1635. const adapter = adapters[name];
  1636. if (adapter === undefined) {
  1637. throw new Error(`${name} adapter is not configured`);
  1638. }
  1639. return adapter;
  1640. };
  1641. /**
  1642. * 指定 Adapters
  1643. * @function
  1644. * @memberof module:leancloud-realtime
  1645. * @param {Adapters} newAdapters Adapters 的类型请参考 {@link https://url.leanapp.cn/adapter-type-definitions @leancloud/adapter-types} 中的定义
  1646. */
  1647. const setAdapters = newAdapters => {
  1648. Object.assign(adapters, newAdapters);
  1649. };
  1650. /* eslint-disable */
  1651. var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
  1652. const EXPIRED = Symbol('expired');
  1653. const debug = d('LC:Expirable');
  1654. class Expirable {
  1655. constructor(value, ttl) {
  1656. this.originalValue = value;
  1657. if (typeof ttl === 'number') {
  1658. this.expiredAt = Date.now() + ttl;
  1659. }
  1660. }
  1661. get value() {
  1662. const expired = this.expiredAt && this.expiredAt <= Date.now();
  1663. if (expired) debug(`expired: ${this.originalValue}`);
  1664. return expired ? EXPIRED : this.originalValue;
  1665. }
  1666. }
  1667. Expirable.EXPIRED = EXPIRED;
  1668. const debug$1 = d('LC:Cache');
  1669. class Cache {
  1670. constructor(name = 'anonymous') {
  1671. this.name = name;
  1672. this._map = {};
  1673. }
  1674. get(key) {
  1675. const cache = this._map[key];
  1676. if (cache) {
  1677. const {
  1678. value
  1679. } = cache;
  1680. if (value !== Expirable.EXPIRED) {
  1681. debug$1('[%s] hit: %s', this.name, key);
  1682. return value;
  1683. }
  1684. delete this._map[key];
  1685. }
  1686. debug$1(`[${this.name}] missed: ${key}`);
  1687. return null;
  1688. }
  1689. set(key, value, ttl) {
  1690. debug$1('[%s] set: %s %d', this.name, key, ttl);
  1691. this._map[key] = new Expirable(value, ttl);
  1692. }
  1693. }
  1694. /**
  1695. * 调试日志控制器
  1696. * @const
  1697. * @memberof module:leancloud-realtime
  1698. * @example
  1699. * debug.enable(); // 启用调试日志
  1700. * debug.disable(); // 关闭调试日志
  1701. */
  1702. const debug$2 = {
  1703. enable: (namespaces = 'LC*') => d.enable(namespaces),
  1704. disable: d.disable
  1705. };
  1706. const tryAll = promiseConstructors => {
  1707. const promise = new Promise(promiseConstructors[0]);
  1708. if (promiseConstructors.length === 1) {
  1709. return promise;
  1710. }
  1711. return promise.catch(() => tryAll(promiseConstructors.slice(1)));
  1712. }; // eslint-disable-next-line no-sequences
  1713. const tap = interceptor => value => (interceptor(value), value);
  1714. const finalize = callback => [// eslint-disable-next-line no-sequences
  1715. value => (callback(), value), error => {
  1716. callback();
  1717. throw error;
  1718. }];
  1719. /**
  1720. * 将对象转换为 Date,支持 string、number、ProtoBuf Long 以及 LeanCloud 的 Date 类型,
  1721. * 其他情况下(包括对象为 falsy)返回原值。
  1722. * @private
  1723. */
  1724. const decodeDate = date => {
  1725. if (!date) return date;
  1726. if (typeof date === 'string' || typeof date === 'number') {
  1727. return new Date(date);
  1728. }
  1729. if (date.__type === 'Date' && date.iso) {
  1730. return new Date(date.iso);
  1731. } // Long
  1732. if (typeof date.toNumber === 'function') {
  1733. return new Date(date.toNumber());
  1734. }
  1735. return date;
  1736. };
  1737. /**
  1738. * 获取 Date 的毫秒数,如果不是一个 Date 返回 undefined。
  1739. * @private
  1740. */
  1741. const getTime = date => date && date.getTime ? date.getTime() : undefined;
  1742. /**
  1743. * 解码对象中的 LeanCloud 数据结构。
  1744. * 目前仅会处理 Date 类型。
  1745. * @private
  1746. */
  1747. const decode = value => {
  1748. if (!value) return value;
  1749. if (value.__type === 'Date' && value.iso) {
  1750. return new Date(value.iso);
  1751. }
  1752. if (Array.isArray(value)) {
  1753. return value.map(decode);
  1754. }
  1755. if (isPlainObject(value)) {
  1756. return Object.keys(value).reduce((result, key) => ({ ...result,
  1757. [key]: decode(value[key])
  1758. }), {});
  1759. }
  1760. return value;
  1761. };
  1762. /**
  1763. * 将对象中的特殊类型编码为 LeanCloud 数据结构。
  1764. * 目前仅会处理 Date 类型。
  1765. * @private
  1766. */
  1767. const encode = value => {
  1768. if (value instanceof Date) return {
  1769. __type: 'Date',
  1770. iso: value.toJSON()
  1771. };
  1772. if (Array.isArray(value)) {
  1773. return value.map(encode);
  1774. }
  1775. if (isPlainObject(value)) {
  1776. return Object.keys(value).reduce((result, key) => ({ ...result,
  1777. [key]: encode(value[key])
  1778. }), {});
  1779. }
  1780. return value;
  1781. };
  1782. const keyRemap = (keymap, obj) => Object.keys(obj).reduce((newObj, key) => {
  1783. const newKey = keymap[key] || key;
  1784. return Object.assign(newObj, {
  1785. [newKey]: obj[key]
  1786. });
  1787. }, {});
  1788. const isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
  1789. /* eslint-disable no-proto */
  1790. const getStaticProperty = (klass, property) => klass[property] || (klass.__proto__ ? getStaticProperty(klass.__proto__, property) : undefined);
  1791. /* eslint-enable no-proto */
  1792. const union = (a, b) => Array.from(new Set([...a, ...b]));
  1793. const difference = (a, b) => Array.from((bSet => new Set(a.filter(x => !bSet.has(x))))(new Set(b)));
  1794. const map = new WeakMap(); // protected property helper
  1795. const internal = object => {
  1796. if (!map.has(object)) {
  1797. map.set(object, {});
  1798. }
  1799. return map.get(object);
  1800. };
  1801. const compact = (obj, filter) => {
  1802. if (!isPlainObject(obj)) return obj;
  1803. const object = { ...obj
  1804. };
  1805. Object.keys(object).forEach(prop => {
  1806. const value = object[prop];
  1807. if (value === filter) {
  1808. delete object[prop];
  1809. } else {
  1810. object[prop] = compact(value, filter);
  1811. }
  1812. });
  1813. return object;
  1814. }; // debug utility
  1815. const removeNull = obj => compact(obj, null);
  1816. const trim = message => removeNull(JSON.parse(JSON.stringify(message)));
  1817. const ensureArray = target => {
  1818. if (Array.isArray(target)) {
  1819. return target;
  1820. }
  1821. if (target === undefined || target === null) {
  1822. return [];
  1823. }
  1824. return [target];
  1825. };
  1826. const setValue = (target, key, value) => {
  1827. // '.' is not allowed in Class keys, escaping is not in concern now.
  1828. const segs = key.split('.');
  1829. const lastSeg = segs.pop();
  1830. let currentTarget = target;
  1831. segs.forEach(seg => {
  1832. if (currentTarget[seg] === undefined) currentTarget[seg] = {};
  1833. currentTarget = currentTarget[seg];
  1834. });
  1835. currentTarget[lastSeg] = value;
  1836. return target;
  1837. };
  1838. const isWeapp = // eslint-disable-next-line no-undef
  1839. typeof wx === 'object' && typeof wx.connectSocket === 'function'; // throttle decorator
  1840. const throttle = wait => (target, property, descriptor) => {
  1841. const callback = descriptor.value; // very naive, internal use only
  1842. if (callback.length) {
  1843. throw new Error('throttled function should not accept any arguments');
  1844. }
  1845. return { ...descriptor,
  1846. value() {
  1847. let {
  1848. throttleMeta
  1849. } = internal(this);
  1850. if (!throttleMeta) {
  1851. throttleMeta = {};
  1852. internal(this).throttleMeta = throttleMeta;
  1853. }
  1854. let {
  1855. [property]: propertyMeta
  1856. } = throttleMeta;
  1857. if (!propertyMeta) {
  1858. propertyMeta = {};
  1859. throttleMeta[property] = propertyMeta;
  1860. }
  1861. const {
  1862. previouseTimestamp = 0,
  1863. timeout
  1864. } = propertyMeta;
  1865. const now = Date.now();
  1866. const remainingTime = wait - (now - previouseTimestamp);
  1867. if (remainingTime <= 0) {
  1868. throttleMeta[property].previouseTimestamp = now;
  1869. callback.apply(this);
  1870. } else if (!timeout) {
  1871. propertyMeta.timeout = setTimeout(() => {
  1872. propertyMeta.previouseTimestamp = Date.now();
  1873. delete propertyMeta.timeout;
  1874. callback.apply(this);
  1875. }, remainingTime);
  1876. }
  1877. }
  1878. };
  1879. };
  1880. const isCNApp = appId => appId.slice(-9) !== '-MdYXbMMI';
  1881. const equalBuffer = (buffer1, buffer2) => {
  1882. if (!buffer1 || !buffer2) return false;
  1883. if (buffer1.byteLength !== buffer2.byteLength) return false;
  1884. const a = new Uint8Array(buffer1);
  1885. const b = new Uint8Array(buffer2);
  1886. return !a.some((value, index) => value !== b[index]);
  1887. };
  1888. var _class;
  1889. const debug$3 = d('LC:WebSocketPlus');
  1890. const OPEN = 'open';
  1891. const DISCONNECT = 'disconnect';
  1892. const RECONNECT = 'reconnect';
  1893. const RETRY = 'retry';
  1894. const SCHEDULE = 'schedule';
  1895. const OFFLINE = 'offline';
  1896. const ONLINE = 'online';
  1897. const ERROR = 'error';
  1898. const MESSAGE = 'message';
  1899. const HEARTBEAT_TIME = 180000;
  1900. const TIMEOUT_TIME = 380000;
  1901. const DEFAULT_RETRY_STRATEGY = attempt => Math.min(1000 * 2 ** attempt, 300000);
  1902. const requireConnected = (target, name, descriptor) => ({ ...descriptor,
  1903. value: function requireConnectedWrapper(...args) {
  1904. this.checkConnectionAvailability(name);
  1905. return descriptor.value.call(this, ...args);
  1906. }
  1907. });
  1908. let WebSocketPlus = (_class = class WebSocketPlus extends EventEmitter {
  1909. get urls() {
  1910. return this._urls;
  1911. }
  1912. set urls(urls) {
  1913. this._urls = ensureArray(urls);
  1914. }
  1915. constructor(getUrls, protocol) {
  1916. super();
  1917. this.init();
  1918. this._protocol = protocol;
  1919. Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(urls => {
  1920. this._urls = urls;
  1921. return this._open();
  1922. }).then(() => {
  1923. this.__postponeTimeoutTimer = this._postponeTimeoutTimer.bind(this);
  1924. if (global$1.addEventListener) {
  1925. this.__pause = () => {
  1926. if (this.can('pause')) this.pause();
  1927. };
  1928. this.__resume = () => {
  1929. if (this.can('resume')) this.resume();
  1930. };
  1931. global$1.addEventListener('offline', this.__pause);
  1932. global$1.addEventListener('online', this.__resume);
  1933. }
  1934. this.open();
  1935. }).catch(this.throw.bind(this));
  1936. }
  1937. _open() {
  1938. return this._createWs(this._urls, this._protocol).then(ws => {
  1939. const [first, ...reset] = this._urls;
  1940. this._urls = [...reset, first];
  1941. return ws;
  1942. });
  1943. }
  1944. _createWs(urls, protocol) {
  1945. return tryAll(urls.map(url => (resolve, reject) => {
  1946. debug$3(`connect [${url}] ${protocol}`);
  1947. const WebSocket = getAdapter('WebSocket');
  1948. const ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
  1949. ws.binaryType = this.binaryType || 'arraybuffer';
  1950. ws.onopen = () => resolve(ws);
  1951. ws.onclose = error => {
  1952. if (error instanceof Error) {
  1953. return reject(error);
  1954. } // in browser, error event is useless
  1955. return reject(new Error(`Failed to connect [${url}]`));
  1956. };
  1957. ws.onerror = ws.onclose;
  1958. })).then(ws => {
  1959. this._ws = ws;
  1960. this._ws.onclose = this._handleClose.bind(this);
  1961. this._ws.onmessage = this._handleMessage.bind(this);
  1962. return ws;
  1963. });
  1964. }
  1965. _destroyWs() {
  1966. const ws = this._ws;
  1967. if (!ws) return;
  1968. ws.onopen = null;
  1969. ws.onclose = null;
  1970. ws.onerror = null;
  1971. ws.onmessage = null;
  1972. this._ws = null;
  1973. ws.close();
  1974. } // eslint-disable-next-line class-methods-use-this
  1975. onbeforeevent(event, from, to, ...payload) {
  1976. debug$3(`${event}: ${from} -> ${to} %o`, payload);
  1977. }
  1978. onopen() {
  1979. this.emit(OPEN);
  1980. }
  1981. onconnected() {
  1982. this._startConnectionKeeper();
  1983. }
  1984. onleaveconnected(event, from, to) {
  1985. this._stopConnectionKeeper();
  1986. this._destroyWs();
  1987. if (to === 'offline' || to === 'disconnected') {
  1988. this.emit(DISCONNECT);
  1989. }
  1990. }
  1991. onpause() {
  1992. this.emit(OFFLINE);
  1993. }
  1994. onbeforeresume() {
  1995. this.emit(ONLINE);
  1996. }
  1997. onreconnect() {
  1998. this.emit(RECONNECT);
  1999. }
  2000. ondisconnected(event, from, to, attempt = 0) {
  2001. const delay = from === OFFLINE ? 0 : DEFAULT_RETRY_STRATEGY.call(null, attempt);
  2002. debug$3(`schedule attempt=${attempt} delay=${delay}`);
  2003. this.emit(SCHEDULE, attempt, delay);
  2004. if (this.__scheduledRetry) {
  2005. clearTimeout(this.__scheduledRetry);
  2006. }
  2007. this.__scheduledRetry = setTimeout(() => {
  2008. if (this.is('disconnected')) {
  2009. this.retry(attempt);
  2010. }
  2011. }, delay);
  2012. }
  2013. onretry(event, from, to, attempt = 0) {
  2014. this.emit(RETRY, attempt);
  2015. this._open().then(() => this.can('reconnect') && this.reconnect(), () => this.can('fail') && this.fail(attempt + 1));
  2016. }
  2017. onerror(event, from, to, error) {
  2018. this.emit(ERROR, error);
  2019. }
  2020. onclose() {
  2021. if (global$1.removeEventListener) {
  2022. if (this.__pause) global$1.removeEventListener('offline', this.__pause);
  2023. if (this.__resume) global$1.removeEventListener('online', this.__resume);
  2024. }
  2025. }
  2026. checkConnectionAvailability(name = 'API') {
  2027. if (!this.is('connected')) {
  2028. const currentState = this.current;
  2029. console.warn(`${name} should not be called when the connection is ${currentState}`);
  2030. if (this.is('disconnected') || this.is('reconnecting')) {
  2031. console.warn('disconnect and reconnect event should be handled to avoid such calls.');
  2032. }
  2033. throw new Error('Connection unavailable');
  2034. }
  2035. } // jsdoc-ignore-start
  2036. // jsdoc-ignore-end
  2037. _ping() {
  2038. debug$3('ping');
  2039. try {
  2040. this.ping();
  2041. } catch (error) {
  2042. console.warn(`websocket ping error: ${error.message}`);
  2043. }
  2044. }
  2045. ping() {
  2046. if (this._ws.ping) {
  2047. this._ws.ping();
  2048. } else {
  2049. console.warn(`The WebSocket implement does not support sending ping frame.
  2050. Override ping method to use application defined ping/pong mechanism.`);
  2051. }
  2052. }
  2053. _postponeTimeoutTimer() {
  2054. debug$3('_postponeTimeoutTimer');
  2055. this._clearTimeoutTimers();
  2056. this._timeoutTimer = setTimeout(() => {
  2057. debug$3('timeout');
  2058. this.disconnect();
  2059. }, TIMEOUT_TIME);
  2060. }
  2061. _clearTimeoutTimers() {
  2062. if (this._timeoutTimer) {
  2063. clearTimeout(this._timeoutTimer);
  2064. }
  2065. }
  2066. _startConnectionKeeper() {
  2067. debug$3('start connection keeper');
  2068. this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
  2069. const addListener = this._ws.addListener || this._ws.addEventListener;
  2070. if (!addListener) {
  2071. debug$3('connection keeper disabled due to the lack of #addEventListener.');
  2072. return;
  2073. }
  2074. addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
  2075. addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
  2076. this._postponeTimeoutTimer();
  2077. }
  2078. _stopConnectionKeeper() {
  2079. debug$3('stop connection keeper'); // websockets/ws#489
  2080. const removeListener = this._ws.removeListener || this._ws.removeEventListener;
  2081. if (removeListener) {
  2082. removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
  2083. removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
  2084. this._clearTimeoutTimers();
  2085. }
  2086. if (this._heartbeatTimer) {
  2087. clearInterval(this._heartbeatTimer);
  2088. }
  2089. }
  2090. _handleClose(event) {
  2091. debug$3(`ws closed [${event.code}] ${event.reason}`); // socket closed manually, ignore close event.
  2092. if (this.isFinished()) return;
  2093. this.handleClose(event);
  2094. }
  2095. handleClose() {
  2096. // reconnect
  2097. this.disconnect();
  2098. } // jsdoc-ignore-start
  2099. // jsdoc-ignore-end
  2100. send(data) {
  2101. debug$3('send', data);
  2102. this._ws.send(data);
  2103. }
  2104. _handleMessage(event) {
  2105. debug$3('message', event.data);
  2106. this.handleMessage(event.data);
  2107. }
  2108. handleMessage(message) {
  2109. this.emit(MESSAGE, message);
  2110. }
  2111. }, (_applyDecoratedDescriptor(_class.prototype, "_ping", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "_ping"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "send", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "send"), _class.prototype)), _class);
  2112. StateMachine.create({
  2113. target: WebSocketPlus.prototype,
  2114. initial: {
  2115. state: 'initialized',
  2116. event: 'init',
  2117. defer: true
  2118. },
  2119. terminal: 'closed',
  2120. events: [{
  2121. name: 'open',
  2122. from: 'initialized',
  2123. to: 'connected'
  2124. }, {
  2125. name: 'disconnect',
  2126. from: 'connected',
  2127. to: 'disconnected'
  2128. }, {
  2129. name: 'retry',
  2130. from: 'disconnected',
  2131. to: 'reconnecting'
  2132. }, {
  2133. name: 'fail',
  2134. from: 'reconnecting',
  2135. to: 'disconnected'
  2136. }, {
  2137. name: 'reconnect',
  2138. from: 'reconnecting',
  2139. to: 'connected'
  2140. }, {
  2141. name: 'pause',
  2142. from: ['connected', 'disconnected', 'reconnecting'],
  2143. to: 'offline'
  2144. }, {}, {
  2145. name: 'resume',
  2146. from: 'offline',
  2147. to: 'disconnected'
  2148. }, {
  2149. name: 'close',
  2150. from: ['connected', 'disconnected', 'reconnecting', 'offline'],
  2151. to: 'closed'
  2152. }, {
  2153. name: 'throw',
  2154. from: '*',
  2155. to: 'error'
  2156. }]
  2157. });
  2158. const error = Object.freeze({
  2159. 1000: {
  2160. name: 'CLOSE_NORMAL'
  2161. },
  2162. 1006: {
  2163. name: 'CLOSE_ABNORMAL'
  2164. },
  2165. 4100: {
  2166. name: 'APP_NOT_AVAILABLE',
  2167. message: 'App not exists or realtime message service is disabled.'
  2168. },
  2169. 4102: {
  2170. name: 'SIGNATURE_FAILED',
  2171. message: 'Login signature mismatch.'
  2172. },
  2173. 4103: {
  2174. name: 'INVALID_LOGIN',
  2175. message: 'Malformed clientId.'
  2176. },
  2177. 4105: {
  2178. name: 'SESSION_REQUIRED',
  2179. message: 'Message sent before session opened.'
  2180. },
  2181. 4107: {
  2182. name: 'READ_TIMEOUT'
  2183. },
  2184. 4108: {
  2185. name: 'LOGIN_TIMEOUT'
  2186. },
  2187. 4109: {
  2188. name: 'FRAME_TOO_LONG'
  2189. },
  2190. 4110: {
  2191. name: 'INVALID_ORIGIN',
  2192. message: 'Access denied by domain whitelist.'
  2193. },
  2194. 4111: {
  2195. name: 'SESSION_CONFLICT'
  2196. },
  2197. 4112: {
  2198. name: 'SESSION_TOKEN_EXPIRED'
  2199. },
  2200. 4113: {
  2201. name: 'APP_QUOTA_EXCEEDED',
  2202. message: 'The daily active users limit exceeded.'
  2203. },
  2204. 4116: {
  2205. name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
  2206. message: 'Command sent too fast.'
  2207. },
  2208. 4200: {
  2209. name: 'INTERNAL_ERROR',
  2210. message: 'Internal error, please contact LeanCloud for support.'
  2211. },
  2212. 4301: {
  2213. name: 'CONVERSATION_API_FAILED',
  2214. message: 'Upstream Conversatoin API failed, see error.detail for details.'
  2215. },
  2216. 4302: {
  2217. name: 'CONVERSATION_SIGNATURE_FAILED',
  2218. message: 'Conversation action signature mismatch.'
  2219. },
  2220. 4303: {
  2221. name: 'CONVERSATION_NOT_FOUND'
  2222. },
  2223. 4304: {
  2224. name: 'CONVERSATION_FULL'
  2225. },
  2226. 4305: {
  2227. name: 'CONVERSATION_REJECTED_BY_APP',
  2228. message: 'Conversation action rejected by hook.'
  2229. },
  2230. 4306: {
  2231. name: 'CONVERSATION_UPDATE_FAILED'
  2232. },
  2233. 4307: {
  2234. name: 'CONVERSATION_READ_ONLY'
  2235. },
  2236. 4308: {
  2237. name: 'CONVERSATION_NOT_ALLOWED'
  2238. },
  2239. 4309: {
  2240. name: 'CONVERSATION_UPDATE_REJECTED',
  2241. message: 'Conversation update rejected because the client is not a member.'
  2242. },
  2243. 4310: {
  2244. name: 'CONVERSATION_QUERY_FAILED',
  2245. message: 'Conversation query failed because it is too expansive.'
  2246. },
  2247. 4311: {
  2248. name: 'CONVERSATION_LOG_FAILED'
  2249. },
  2250. 4312: {
  2251. name: 'CONVERSATION_LOG_REJECTED',
  2252. message: 'Message query rejected because the client is not a member of the conversation.'
  2253. },
  2254. 4313: {
  2255. name: 'SYSTEM_CONVERSATION_REQUIRED'
  2256. },
  2257. 4314: {
  2258. name: 'NORMAL_CONVERSATION_REQUIRED'
  2259. },
  2260. 4315: {
  2261. name: 'CONVERSATION_BLACKLISTED',
  2262. message: 'Blacklisted in the conversation.'
  2263. },
  2264. 4316: {
  2265. name: 'TRANSIENT_CONVERSATION_REQUIRED'
  2266. },
  2267. 4317: {
  2268. name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
  2269. },
  2270. 4318: {
  2271. name: 'CONVERSATION_API_QUOTA_EXCEEDED',
  2272. message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
  2273. },
  2274. 4323: {
  2275. name: 'TEMPORARY_CONVERSATION_EXPIRED',
  2276. message: 'Temporary conversation expired or does not exist.'
  2277. },
  2278. 4401: {
  2279. name: 'INVALID_MESSAGING_TARGET',
  2280. message: 'Conversation does not exist or client is not a member.'
  2281. },
  2282. 4402: {
  2283. name: 'MESSAGE_REJECTED_BY_APP',
  2284. message: 'Message rejected by hook.'
  2285. },
  2286. 4403: {
  2287. name: 'MESSAGE_OWNERSHIP_REQUIRED'
  2288. },
  2289. 4404: {
  2290. name: 'MESSAGE_NOT_FOUND'
  2291. },
  2292. 4405: {
  2293. name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
  2294. message: 'Message update rejected by hook.'
  2295. },
  2296. 4406: {
  2297. name: 'MESSAGE_EDIT_DISABLED'
  2298. },
  2299. 4407: {
  2300. name: 'MESSAGE_RECALL_DISABLED'
  2301. },
  2302. 5130: {
  2303. name: 'OWNER_PROMOTION_NOT_ALLOWED',
  2304. message: "Updating a member's role to owner is not allowed."
  2305. }
  2306. });
  2307. const ErrorCode = Object.freeze(Object.keys(error).reduce((result, code) => Object.assign(result, {
  2308. [error[code].name]: Number(code)
  2309. }), {}));
  2310. const createError = ({
  2311. code,
  2312. reason,
  2313. appCode,
  2314. detail,
  2315. error: errorMessage
  2316. }) => {
  2317. let message = reason || detail || errorMessage;
  2318. let name = reason;
  2319. if (!message && error[code]) {
  2320. ({
  2321. name
  2322. } = error[code]);
  2323. message = error[code].message || name;
  2324. }
  2325. if (!message) {
  2326. message = `Unknow Error: ${code}`;
  2327. }
  2328. const err = new Error(message);
  2329. return Object.assign(err, {
  2330. code,
  2331. appCode,
  2332. detail,
  2333. name
  2334. });
  2335. };
  2336. const debug$4 = d('LC:Connection');
  2337. const COMMAND_TIMEOUT = 20000;
  2338. const EXPIRE = Symbol('expire');
  2339. const isIdempotentCommand = command => !(command.cmd === CommandType.direct || command.cmd === CommandType.session && command.op === OpType.open || command.cmd === CommandType.conv && (command.op === OpType.start || command.op === OpType.update || command.op === OpType.members));
  2340. class Connection extends WebSocketPlus {
  2341. constructor(getUrl, {
  2342. format,
  2343. version
  2344. }) {
  2345. debug$4('initializing Connection');
  2346. const protocolString = `lc.${format}.${version}`;
  2347. super(getUrl, protocolString);
  2348. this._protocolFormat = format;
  2349. this._commands = {};
  2350. this._serialId = 0;
  2351. }
  2352. async send(command, waitingForRespond = true) {
  2353. let buffer;
  2354. let serialId;
  2355. if (waitingForRespond) {
  2356. if (isIdempotentCommand(command)) {
  2357. buffer = command.toArrayBuffer();
  2358. const duplicatedCommand = values(this._commands).find(({
  2359. buffer: targetBuffer,
  2360. command: targetCommand
  2361. }) => targetCommand.cmd === command.cmd && targetCommand.op === command.op && equalBuffer(targetBuffer, buffer));
  2362. if (duplicatedCommand) {
  2363. console.warn(`Duplicated command [cmd:${command.cmd} op:${command.op}] is throttled.`);
  2364. return duplicatedCommand.promise;
  2365. }
  2366. }
  2367. this._serialId += 1;
  2368. serialId = this._serialId;
  2369. command.i = serialId; // eslint-disable-line no-param-reassign
  2370. }
  2371. if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
  2372. let message;
  2373. if (this._protocolFormat === 'proto2base64') {
  2374. message = command.toBase64();
  2375. } else if (command.toArrayBuffer) {
  2376. message = command.toArrayBuffer();
  2377. }
  2378. if (!message) {
  2379. throw new TypeError(`${command} is not a GenericCommand`);
  2380. }
  2381. super.send(message);
  2382. if (!waitingForRespond) return undefined;
  2383. const promise = new Promise((resolve, reject) => {
  2384. this._commands[serialId] = {
  2385. command,
  2386. buffer,
  2387. resolve,
  2388. reject,
  2389. timeout: setTimeout(() => {
  2390. if (this._commands[serialId]) {
  2391. if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
  2392. reject(createError({
  2393. error: `Command Timeout [cmd:${command.cmd} op:${command.op}]`,
  2394. name: 'COMMAND_TIMEOUT'
  2395. }));
  2396. delete this._commands[serialId];
  2397. }
  2398. }, COMMAND_TIMEOUT)
  2399. };
  2400. });
  2401. this._commands[serialId].promise = promise;
  2402. return promise;
  2403. }
  2404. handleMessage(msg) {
  2405. let message;
  2406. try {
  2407. message = GenericCommand.decode(msg);
  2408. if (debug$4.enabled) debug$4('↓ %O received', trim(message));
  2409. } catch (e) {
  2410. console.warn('Decode message failed:', e.message, msg);
  2411. return;
  2412. }
  2413. const serialId = message.i;
  2414. if (serialId) {
  2415. if (this._commands[serialId]) {
  2416. clearTimeout(this._commands[serialId].timeout);
  2417. if (message.cmd === CommandType.error) {
  2418. this._commands[serialId].reject(createError(message.errorMessage));
  2419. } else {
  2420. this._commands[serialId].resolve(message);
  2421. }
  2422. delete this._commands[serialId];
  2423. } else {
  2424. console.warn(`Unexpected command received with serialId [${serialId}],
  2425. which have timed out or never been requested.`);
  2426. }
  2427. } else {
  2428. switch (message.cmd) {
  2429. case CommandType.error:
  2430. {
  2431. this.emit(ERROR, createError(message.errorMessage));
  2432. return;
  2433. }
  2434. case CommandType.goaway:
  2435. {
  2436. this.emit(EXPIRE);
  2437. return;
  2438. }
  2439. default:
  2440. {
  2441. this.emit(MESSAGE, message);
  2442. }
  2443. }
  2444. }
  2445. }
  2446. ping() {
  2447. return this.send(new GenericCommand({
  2448. cmd: CommandType.echo
  2449. })).catch(error => debug$4('ping failed:', error));
  2450. }
  2451. }
  2452. const debug$5 = d('LC:request');
  2453. var request = (({
  2454. method = 'GET',
  2455. url: _url,
  2456. query,
  2457. headers,
  2458. data,
  2459. timeout: time
  2460. }) => {
  2461. let url = _url;
  2462. if (query) {
  2463. const queryString = Object.keys(query).map(key => {
  2464. const value = query[key];
  2465. if (value === undefined) return undefined;
  2466. const v = isPlainObject(value) ? JSON.stringify(value) : value;
  2467. return `${encodeURIComponent(key)}=${encodeURIComponent(v)}`;
  2468. }).filter(qs => qs).join('&');
  2469. url = `${url}?${queryString}`;
  2470. }
  2471. debug$5('Req: %O %O %O', method, url, {
  2472. headers,
  2473. data
  2474. });
  2475. const request = getAdapter('request');
  2476. const promise = request(url, {
  2477. method,
  2478. headers,
  2479. data
  2480. }).then(response => {
  2481. if (response.ok === false) {
  2482. const error = createError(response.data);
  2483. error.response = response;
  2484. throw error;
  2485. }
  2486. debug$5('Res: %O %O %O', url, response.status, response.data);
  2487. return response.data;
  2488. }).catch(error => {
  2489. if (error.response) {
  2490. debug$5('Error: %O %O %O', url, error.response.status, error.response.data);
  2491. }
  2492. throw error;
  2493. });
  2494. return time ? promiseTimeout.timeout(promise, time) : promise;
  2495. });
  2496. /* eslint-disable max-len */
  2497. const checkType = middleware => param => {
  2498. const {
  2499. constructor
  2500. } = param;
  2501. return Promise.resolve(param).then(middleware).then(tap(result => {
  2502. if (result === undefined || result === null) {
  2503. // eslint-disable-next-line max-len
  2504. return console.warn(`Middleware[${middleware._pluginName || 'anonymous plugin'}:${middleware.name || 'anonymous middleware'}] param/return types not match. It returns ${result} while a ${param.constructor.name} expected.`);
  2505. }
  2506. if (!(result instanceof constructor)) {
  2507. // eslint-disable-next-line max-len
  2508. return console.warn(`Middleware[${middleware._pluginName || 'anonymous plugin'}:${middleware.name || 'anonymous middleware'}] param/return types not match. It returns a ${result.constructor.name} while a ${param.constructor.name} expected.`);
  2509. }
  2510. return 0;
  2511. }));
  2512. };
  2513. const applyDecorators = (decorators, target) => {
  2514. if (decorators) {
  2515. decorators.forEach(decorator => {
  2516. try {
  2517. decorator(target);
  2518. } catch (error) {
  2519. if (decorator._pluginName) {
  2520. error.message += `[${decorator._pluginName}]`;
  2521. }
  2522. throw error;
  2523. }
  2524. });
  2525. }
  2526. };
  2527. const applyMiddlewares = middlewares => target => ensureArray(middlewares).reduce((previousPromise, middleware) => previousPromise.then(checkType(middleware)).catch(error => {
  2528. if (middleware._pluginName) {
  2529. // eslint-disable-next-line no-param-reassign
  2530. error.message += `[${middleware._pluginName}]`;
  2531. }
  2532. throw error;
  2533. }), Promise.resolve(target));
  2534. const applyDispatcher = (dispatchers, payload) => ensureArray(dispatchers).reduce((resultPromise, dispatcher) => resultPromise.then(shouldDispatch => shouldDispatch === false ? false : dispatcher(...payload)).catch(error => {
  2535. if (dispatcher._pluginName) {
  2536. // eslint-disable-next-line no-param-reassign
  2537. error.message += `[${dispatcher._pluginName}]`;
  2538. }
  2539. throw error;
  2540. }), Promise.resolve(true));
  2541. var version = "5.0.0-rc.7";
  2542. // eslint-disable-next-line max-classes-per-file
  2543. const debug$6 = d('LC:Realtime');
  2544. const routerCache = new Cache('push-router');
  2545. const initializedApp = {};
  2546. class Realtime extends EventEmitter {
  2547. /**
  2548. * @extends EventEmitter
  2549. * @param {Object} options
  2550. * @param {String} options.appId
  2551. * @param {String} options.appKey (since 4.0.0)
  2552. * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
  2553. * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
  2554. * 适用于 WebSocket 实现不支持二进制数据格式的情况
  2555. * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
  2556. * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
  2557. * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
  2558. */
  2559. constructor({
  2560. plugins,
  2561. ...options
  2562. }) {
  2563. debug$6('initializing Realtime %s %O', version, options);
  2564. super();
  2565. const {
  2566. appId
  2567. } = options;
  2568. if (typeof appId !== 'string') {
  2569. throw new TypeError(`appId [${appId}] is not a string`);
  2570. }
  2571. if (initializedApp[appId]) {
  2572. throw new Error(`App [${appId}] is already initialized.`);
  2573. }
  2574. initializedApp[appId] = true;
  2575. if (typeof options.appKey !== 'string') {
  2576. throw new TypeError(`appKey [${options.appKey}] is not a string`);
  2577. }
  2578. if (isCNApp(appId)) {
  2579. if (!options.server) {
  2580. throw new TypeError(`server option is required for apps from CN region`);
  2581. }
  2582. }
  2583. this._options = {
  2584. appId: undefined,
  2585. appKey: undefined,
  2586. noBinary: false,
  2587. ssl: true,
  2588. RTMServerName: typeof process !== 'undefined' ? process.env.RTM_SERVER_NAME : undefined,
  2589. // undocumented on purpose, internal use only
  2590. ...options
  2591. };
  2592. this._cache = new Cache('endpoints');
  2593. const _this = internal(this);
  2594. _this.clients = new Set();
  2595. _this.pendingClients = new Set();
  2596. const mergedPlugins = [...ensureArray(Realtime.__preRegisteredPlugins), ...ensureArray(plugins)];
  2597. debug$6('Using plugins %o', mergedPlugins.map(plugin => plugin.name));
  2598. this._plugins = mergedPlugins.reduce((result, plugin) => {
  2599. Object.keys(plugin).forEach(hook => {
  2600. if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
  2601. if (plugin.name) {
  2602. ensureArray(plugin[hook]).forEach(value => {
  2603. // eslint-disable-next-line no-param-reassign
  2604. value._pluginName = plugin.name;
  2605. });
  2606. } // eslint-disable-next-line no-param-reassign
  2607. result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
  2608. }
  2609. });
  2610. return result;
  2611. }, {}); // onRealtimeCreate hook
  2612. applyDecorators(this._plugins.onRealtimeCreate, this);
  2613. }
  2614. async _request({
  2615. method,
  2616. url: _url,
  2617. version = '1.1',
  2618. path,
  2619. query,
  2620. headers,
  2621. data
  2622. }) {
  2623. let url = _url;
  2624. if (!url) {
  2625. const {
  2626. appId,
  2627. server
  2628. } = this._options;
  2629. const {
  2630. api
  2631. } = await this.constructor._getServerUrls({
  2632. appId,
  2633. server
  2634. });
  2635. url = `${api}/${version}${path}`;
  2636. }
  2637. return request({
  2638. url,
  2639. method,
  2640. query,
  2641. headers: {
  2642. 'X-LC-Id': this._options.appId,
  2643. 'X-LC-Key': this._options.appKey,
  2644. ...headers
  2645. },
  2646. data
  2647. });
  2648. }
  2649. _open() {
  2650. if (this._openPromise) return this._openPromise;
  2651. let format = 'protobuf2';
  2652. if (this._options.noBinary) {
  2653. // 不发送 binary data,fallback to base64 string
  2654. format = 'proto2base64';
  2655. }
  2656. const version = 3;
  2657. const protocol = {
  2658. format,
  2659. version
  2660. };
  2661. this._openPromise = new Promise((resolve, reject) => {
  2662. debug$6('No connection established, create a new one.');
  2663. const connection = new Connection(() => this._getRTMServers(this._options), protocol);
  2664. connection.on(OPEN, () => resolve(connection)).on(ERROR, error => {
  2665. delete this._openPromise;
  2666. reject(error);
  2667. }).on(EXPIRE, async () => {
  2668. debug$6('Connection expired. Refresh endpoints.');
  2669. this._cache.set('endpoints', null, 0);
  2670. connection.urls = await this._getRTMServers(this._options);
  2671. connection.disconnect();
  2672. }).on(MESSAGE, this._dispatchCommand.bind(this));
  2673. /**
  2674. * 连接断开。
  2675. * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
  2676. * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
  2677. * @event Realtime#DISCONNECT
  2678. */
  2679. /**
  2680. * 计划在一段时间后尝试重新连接
  2681. * @event Realtime#SCHEDULE
  2682. * @param {Number} attempt 尝试重连的次数
  2683. * @param {Number} delay 延迟的毫秒数
  2684. */
  2685. /**
  2686. * 正在尝试重新连接
  2687. * @event Realtime#RETRY
  2688. * @param {Number} attempt 尝试重连的次数
  2689. */
  2690. /**
  2691. * 连接恢复正常。
  2692. * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
  2693. * @event Realtime#RECONNECT
  2694. */
  2695. /**
  2696. * 客户端连接断开
  2697. * @event IMClient#DISCONNECT
  2698. * @see Realtime#event:DISCONNECT
  2699. * @since 3.2.0
  2700. */
  2701. /**
  2702. * 计划在一段时间后尝试重新连接
  2703. * @event IMClient#SCHEDULE
  2704. * @param {Number} attempt 尝试重连的次数
  2705. * @param {Number} delay 延迟的毫秒数
  2706. * @since 3.2.0
  2707. */
  2708. /**
  2709. * 正在尝试重新连接
  2710. * @event IMClient#RETRY
  2711. * @param {Number} attempt 尝试重连的次数
  2712. * @since 3.2.0
  2713. */
  2714. /**
  2715. * 客户端进入离线状态。
  2716. * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
  2717. * @event Realtime#OFFLINE
  2718. * @since 3.4.0
  2719. */
  2720. /**
  2721. * 客户端恢复在线状态
  2722. * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
  2723. * @event Realtime#ONLINE
  2724. * @since 3.4.0
  2725. */
  2726. /**
  2727. * 进入离线状态。
  2728. * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
  2729. * @event IMClient#OFFLINE
  2730. * @since 3.4.0
  2731. */
  2732. /**
  2733. * 恢复在线状态
  2734. * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
  2735. * @event IMClient#ONLINE
  2736. * @since 3.4.0
  2737. */
  2738. // event proxy
  2739. [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(event => connection.on(event, (...payload) => {
  2740. debug$6(`${event} event emitted. %o`, payload);
  2741. this.emit(event, ...payload);
  2742. if (event !== RECONNECT) {
  2743. internal(this).clients.forEach(client => {
  2744. client.emit(event, ...payload);
  2745. });
  2746. }
  2747. })); // override handleClose
  2748. connection.handleClose = function handleClose(event) {
  2749. const isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(errorCode => errorCode === event.code);
  2750. if (isFatal) {
  2751. // in these cases, SDK should throw.
  2752. this.throw(createError(event));
  2753. } else {
  2754. // reconnect
  2755. this.disconnect();
  2756. }
  2757. };
  2758. internal(this).connection = connection;
  2759. });
  2760. return this._openPromise;
  2761. }
  2762. async _getRTMServers(options) {
  2763. if (options.RTMServers) return shuffle(ensureArray(options.RTMServers));
  2764. let info;
  2765. const cachedEndPoints = this._cache.get('endpoints');
  2766. if (cachedEndPoints) {
  2767. info = cachedEndPoints;
  2768. } else {
  2769. info = await this.constructor._fetchRTMServers(options);
  2770. const {
  2771. server,
  2772. secondary,
  2773. ttl
  2774. } = info;
  2775. if (typeof server !== 'string' && typeof secondary !== 'string' && typeof ttl !== 'number') {
  2776. throw new Error(`malformed RTM route response: ${JSON.stringify(info)}`);
  2777. }
  2778. this._cache.set('endpoints', info, info.ttl * 1000);
  2779. }
  2780. debug$6('endpoint info: %O', info);
  2781. return [info.server, info.secondary];
  2782. }
  2783. static async _getServerUrls({
  2784. appId,
  2785. server
  2786. }) {
  2787. debug$6('fetch server urls');
  2788. if (server) {
  2789. if (typeof server !== 'string') return server;
  2790. return {
  2791. RTMRouter: server,
  2792. api: server
  2793. };
  2794. }
  2795. const cachedRouter = routerCache.get(appId);
  2796. if (cachedRouter) return cachedRouter;
  2797. const defaultProtocol = 'https://';
  2798. return request({
  2799. url: 'https://app-router.com/2/route',
  2800. query: {
  2801. appId
  2802. },
  2803. timeout: 20000
  2804. }).then(tap(debug$6)).then(({
  2805. rtm_router_server: RTMRouterServer,
  2806. api_server: APIServer,
  2807. ttl = 3600
  2808. }) => {
  2809. if (!RTMRouterServer) {
  2810. throw new Error('rtm router not exists');
  2811. }
  2812. const serverUrls = {
  2813. RTMRouter: `${defaultProtocol}${RTMRouterServer}`,
  2814. api: `${defaultProtocol}${APIServer}`
  2815. };
  2816. routerCache.set(appId, serverUrls, ttl * 1000);
  2817. return serverUrls;
  2818. }).catch(() => {
  2819. const id = appId.slice(0, 8).toLowerCase();
  2820. const domain = 'lncldglobal.com';
  2821. return {
  2822. RTMRouter: `${defaultProtocol}${id}.rtm.${domain}`,
  2823. api: `${defaultProtocol}${id}.api.${domain}`
  2824. };
  2825. });
  2826. }
  2827. static _fetchRTMServers({
  2828. appId,
  2829. ssl,
  2830. server,
  2831. RTMServerName
  2832. }) {
  2833. debug$6('fetch endpoint info');
  2834. return this._getServerUrls({
  2835. appId,
  2836. server
  2837. }).then(tap(debug$6)).then(({
  2838. RTMRouter
  2839. }) => request({
  2840. url: `${RTMRouter}/v1/route`,
  2841. query: {
  2842. appId,
  2843. secure: ssl,
  2844. features: isWeapp ? 'wechat' : undefined,
  2845. server: RTMServerName,
  2846. _t: Date.now()
  2847. },
  2848. timeout: 20000
  2849. }).then(tap(debug$6)));
  2850. }
  2851. _close() {
  2852. if (this._openPromise) {
  2853. this._openPromise.then(connection => connection.close());
  2854. }
  2855. delete this._openPromise;
  2856. }
  2857. /**
  2858. * 手动进行重连。
  2859. * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
  2860. * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
  2861. */
  2862. retry() {
  2863. const {
  2864. connection
  2865. } = internal(this);
  2866. if (!connection) {
  2867. throw new Error('no connection established');
  2868. }
  2869. if (connection.cannot('retry')) {
  2870. throw new Error(`retrying not allowed when not disconnected. the connection is now ${connection.current}`);
  2871. }
  2872. return connection.retry();
  2873. }
  2874. /**
  2875. * 暂停,使 SDK 进入离线状态。
  2876. * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
  2877. * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
  2878. *
  2879. * @since 3.4.0
  2880. * @see Realtime#event:OFFLINE
  2881. */
  2882. pause() {
  2883. // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
  2884. // 因此不像 retry,这个方法应该尽可能 loose
  2885. const {
  2886. connection
  2887. } = internal(this);
  2888. if (!connection) return;
  2889. if (connection.can('pause')) connection.pause();
  2890. }
  2891. /**
  2892. * 恢复在线状态。
  2893. * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
  2894. *
  2895. * @since 3.4.0
  2896. * @see Realtime#event:ONLINE
  2897. */
  2898. resume() {
  2899. // 与 pause 一样,这个方法应该尽可能 loose
  2900. const {
  2901. connection
  2902. } = internal(this);
  2903. if (!connection) return;
  2904. if (connection.can('resume')) connection.resume();
  2905. }
  2906. _registerPending(value) {
  2907. internal(this).pendingClients.add(value);
  2908. }
  2909. _deregisterPending(client) {
  2910. internal(this).pendingClients.delete(client);
  2911. }
  2912. _register(client) {
  2913. internal(this).clients.add(client);
  2914. }
  2915. _deregister(client) {
  2916. const _this = internal(this);
  2917. _this.clients.delete(client);
  2918. if (_this.clients.size + _this.pendingClients.size === 0) {
  2919. this._close();
  2920. }
  2921. }
  2922. _dispatchCommand(command) {
  2923. return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(shouldDispatch => {
  2924. // no plugin handled this command
  2925. if (shouldDispatch) return debug$6('[WARN] Unexpected message received: %O', trim(command));
  2926. return false;
  2927. });
  2928. }
  2929. } // For test purpose only
  2930. const polyfilledPromise = Promise;
  2931. // IMClient
  2932. const UNREAD_MESSAGES_COUNT_UPDATE = 'unreadmessagescountupdate';
  2933. const CLOSE = 'close';
  2934. const CONFLICT = 'conflict';
  2935. const CONVERSATION_INFO_UPDATED = 'conversationinfoupdated';
  2936. const UNHANDLED_MESSAGE = 'unhandledmessage'; // shared
  2937. const INVITED = 'invited';
  2938. const KICKED = 'kicked';
  2939. const MEMBERS_JOINED = 'membersjoined';
  2940. const MEMBERS_LEFT = 'membersleft';
  2941. const MEMBER_INFO_UPDATED = 'memberinfoupdated';
  2942. const BLOCKED = 'blocked';
  2943. const UNBLOCKED = 'unblocked';
  2944. const MEMBERS_BLOCKED = 'membersblocked';
  2945. const MEMBERS_UNBLOCKED = 'membersunblocked';
  2946. const MUTED = 'muted';
  2947. const UNMUTED = 'unmuted';
  2948. const MEMBERS_MUTED = 'membersmuted';
  2949. const MEMBERS_UNMUTED = 'membersunmuted';
  2950. const MESSAGE$1 = 'message';
  2951. const MESSAGE_RECALL = 'messagerecall';
  2952. const MESSAGE_UPDATE = 'messageupdate'; // Conversation
  2953. const LAST_DELIVERED_AT_UPDATE = 'lastdeliveredatupdate';
  2954. const LAST_READ_AT_UPDATE = 'lastreadatupdate';
  2955. const INFO_UPDATED = 'infoupdated';
  2956. var IMEvent = /*#__PURE__*/Object.freeze({
  2957. __proto__: null,
  2958. UNREAD_MESSAGES_COUNT_UPDATE: UNREAD_MESSAGES_COUNT_UPDATE,
  2959. CLOSE: CLOSE,
  2960. CONFLICT: CONFLICT,
  2961. CONVERSATION_INFO_UPDATED: CONVERSATION_INFO_UPDATED,
  2962. UNHANDLED_MESSAGE: UNHANDLED_MESSAGE,
  2963. INVITED: INVITED,
  2964. KICKED: KICKED,
  2965. MEMBERS_JOINED: MEMBERS_JOINED,
  2966. MEMBERS_LEFT: MEMBERS_LEFT,
  2967. MEMBER_INFO_UPDATED: MEMBER_INFO_UPDATED,
  2968. BLOCKED: BLOCKED,
  2969. UNBLOCKED: UNBLOCKED,
  2970. MEMBERS_BLOCKED: MEMBERS_BLOCKED,
  2971. MEMBERS_UNBLOCKED: MEMBERS_UNBLOCKED,
  2972. MUTED: MUTED,
  2973. UNMUTED: UNMUTED,
  2974. MEMBERS_MUTED: MEMBERS_MUTED,
  2975. MEMBERS_UNMUTED: MEMBERS_UNMUTED,
  2976. MESSAGE: MESSAGE$1,
  2977. MESSAGE_RECALL: MESSAGE_RECALL,
  2978. MESSAGE_UPDATE: MESSAGE_UPDATE,
  2979. LAST_DELIVERED_AT_UPDATE: LAST_DELIVERED_AT_UPDATE,
  2980. LAST_READ_AT_UPDATE: LAST_READ_AT_UPDATE,
  2981. INFO_UPDATED: INFO_UPDATED
  2982. });
  2983. /**
  2984. * 消息状态枚举
  2985. * @enum {Symbol}
  2986. * @since 3.2.0
  2987. * @memberof module:leancloud-realtime
  2988. */
  2989. const MessageStatus = {
  2990. /** 初始状态、未知状态 */
  2991. NONE: Symbol('none'),
  2992. /** 正在发送 */
  2993. SENDING: Symbol('sending'),
  2994. /** 已发送 */
  2995. SENT: Symbol('sent'),
  2996. /** 已送达 */
  2997. DELIVERED: Symbol('delivered'),
  2998. /** 发送失败 */
  2999. FAILED: Symbol('failed')
  3000. };
  3001. Object.freeze(MessageStatus);
  3002. const rMessageStatus = {
  3003. [MessageStatus.NONE]: true,
  3004. [MessageStatus.SENDING]: true,
  3005. [MessageStatus.SENT]: true,
  3006. [MessageStatus.DELIVERED]: true,
  3007. [MessageStatus.READ]: true,
  3008. [MessageStatus.FAILED]: true
  3009. };
  3010. class Message {
  3011. /**
  3012. * @implements AVMessage
  3013. * @param {Object|String|ArrayBuffer} content 消息内容
  3014. */
  3015. constructor(content) {
  3016. Object.assign(this, {
  3017. content
  3018. }, {
  3019. /**
  3020. * @type {String}
  3021. * @memberof Message#
  3022. */
  3023. id: uuid(),
  3024. /**
  3025. * 消息所在的 conversation id
  3026. * @memberof Message#
  3027. * @type {String?}
  3028. */
  3029. cid: null,
  3030. /**
  3031. * 消息发送时间
  3032. * @memberof Message#
  3033. * @type {Date}
  3034. */
  3035. timestamp: new Date(),
  3036. /**
  3037. * 消息发送者
  3038. * @memberof Message#
  3039. * @type {String}
  3040. */
  3041. from: undefined,
  3042. /**
  3043. * 消息提及的用户
  3044. * @since 4.0.0
  3045. * @memberof Message#
  3046. * @type {String[]}
  3047. */
  3048. mentionList: [],
  3049. /**
  3050. * 消息是否提及了所有人
  3051. * @since 4.0.0
  3052. * @memberof Message#
  3053. * @type {Boolean}
  3054. */
  3055. mentionedAll: false,
  3056. _mentioned: false
  3057. });
  3058. this._setStatus(MessageStatus.NONE);
  3059. }
  3060. /**
  3061. * 将当前消息的内容序列化为 JSON 对象
  3062. * @private
  3063. * @return {Object}
  3064. */
  3065. getPayload() {
  3066. return this.content;
  3067. }
  3068. _toJSON() {
  3069. const {
  3070. id,
  3071. cid,
  3072. from,
  3073. timestamp,
  3074. deliveredAt,
  3075. updatedAt,
  3076. mentionList,
  3077. mentionedAll,
  3078. mentioned
  3079. } = this;
  3080. return {
  3081. id,
  3082. cid,
  3083. from,
  3084. timestamp,
  3085. deliveredAt,
  3086. updatedAt,
  3087. mentionList,
  3088. mentionedAll,
  3089. mentioned
  3090. };
  3091. }
  3092. /**
  3093. * 返回 JSON 格式的消息
  3094. * @return {Object} 返回值是一个 plain Object
  3095. */
  3096. toJSON() {
  3097. return { ...this._toJSON(),
  3098. data: this.content
  3099. };
  3100. }
  3101. /**
  3102. * 返回 JSON 格式的消息,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseMessage} 反序列化。
  3103. * @return {Object} 返回值是一个 plain Object
  3104. * @since 4.0.0
  3105. */
  3106. toFullJSON() {
  3107. const {
  3108. content,
  3109. id,
  3110. cid,
  3111. from,
  3112. timestamp,
  3113. deliveredAt,
  3114. _updatedAt,
  3115. mentionList,
  3116. mentionedAll
  3117. } = this;
  3118. return {
  3119. data: content,
  3120. id,
  3121. cid,
  3122. from,
  3123. timestamp: getTime(timestamp),
  3124. deliveredAt: getTime(deliveredAt),
  3125. updatedAt: getTime(_updatedAt),
  3126. mentionList,
  3127. mentionedAll
  3128. };
  3129. }
  3130. /**
  3131. * 消息状态,值为 {@link module:leancloud-realtime.MessageStatus} 之一
  3132. * @type {Symbol}
  3133. * @readonly
  3134. * @since 3.2.0
  3135. */
  3136. get status() {
  3137. return this._status;
  3138. }
  3139. _setStatus(status) {
  3140. if (!rMessageStatus[status]) {
  3141. throw new Error('Invalid message status');
  3142. }
  3143. this._status = status;
  3144. }
  3145. get timestamp() {
  3146. return this._timestamp;
  3147. }
  3148. set timestamp(value) {
  3149. this._timestamp = decodeDate(value);
  3150. }
  3151. /**
  3152. * 消息送达时间
  3153. * @type {?Date}
  3154. */
  3155. get deliveredAt() {
  3156. return this._deliveredAt;
  3157. }
  3158. set deliveredAt(value) {
  3159. this._deliveredAt = decodeDate(value);
  3160. }
  3161. /**
  3162. * 消息修改或撤回时间,可以通过比较其与消息的 timestamp 是否相等判断消息是否被修改过或撤回过。
  3163. * @type {Date}
  3164. * @since 3.5.0
  3165. */
  3166. get updatedAt() {
  3167. return this._updatedAt || this.timestamp;
  3168. }
  3169. set updatedAt(value) {
  3170. this._updatedAt = decodeDate(value);
  3171. }
  3172. /**
  3173. * 当前用户是否在该消息中被提及
  3174. * @type {Boolean}
  3175. * @readonly
  3176. * @since 4.0.0
  3177. */
  3178. get mentioned() {
  3179. return this._mentioned;
  3180. }
  3181. _updateMentioned(client) {
  3182. this._mentioned = this.from !== client && (this.mentionedAll || this.mentionList.indexOf(client) > -1);
  3183. }
  3184. /**
  3185. * 获取提及用户列表
  3186. * @since 4.0.0
  3187. * @return {String[]} 提及用户的 id 列表
  3188. */
  3189. getMentionList() {
  3190. return this.mentionList;
  3191. }
  3192. /**
  3193. * 设置提及用户列表
  3194. * @since 4.0.0
  3195. * @param {String[]} clients 提及用户的 id 列表
  3196. * @return {this} self
  3197. */
  3198. setMentionList(clients) {
  3199. this.mentionList = ensureArray(clients);
  3200. return this;
  3201. }
  3202. /**
  3203. * 设置是否提及所有人
  3204. * @since 4.0.0
  3205. * @param {Boolean} [value=true]
  3206. * @return {this} self
  3207. */
  3208. mentionAll(value = true) {
  3209. this.mentionedAll = Boolean(value);
  3210. return this;
  3211. }
  3212. /**
  3213. * 判断给定的内容是否是有效的 Message,
  3214. * 该方法始终返回 true
  3215. * @private
  3216. * @returns {Boolean}
  3217. * @implements AVMessage.validate
  3218. */
  3219. static validate() {
  3220. return true;
  3221. }
  3222. /**
  3223. * 解析处理消息内容
  3224. * <pre>
  3225. * 如果子类提供了 message,返回该 message
  3226. * 如果没有提供,将 json 作为 content 实例化一个 Message
  3227. * @private
  3228. * @param {Object} json json 格式的消息内容
  3229. * @param {Message} message 子类提供的 message
  3230. * @return {Message}
  3231. * @implements AVMessage.parse
  3232. */
  3233. static parse(json, message) {
  3234. return message || new this(json);
  3235. }
  3236. }
  3237. /* eslint-disable no-param-reassign */
  3238. const messageType = type => {
  3239. if (typeof type !== 'number') {
  3240. throw new TypeError(`${type} is not a Number`);
  3241. }
  3242. return target => {
  3243. target.TYPE = type;
  3244. target.validate = json => json._lctype === type;
  3245. target.prototype._getType = () => ({
  3246. _lctype: type
  3247. });
  3248. };
  3249. }; // documented in ../plugin-im.js
  3250. const messageField = fields => {
  3251. if (typeof fields !== 'string') {
  3252. if (!Array.isArray(fields)) {
  3253. throw new TypeError(`${fields} is not an Array`);
  3254. } else if (fields.some(value => typeof value !== 'string')) {
  3255. throw new TypeError('fields contains non-string typed member');
  3256. }
  3257. }
  3258. return target => {
  3259. // IE10 Hack:
  3260. // static properties in IE10 will not be inherited from super
  3261. // search for parse method and assign it manually
  3262. let originalCustomFields = isIE10 ? getStaticProperty(target, '_customFields') : target._customFields;
  3263. originalCustomFields = Array.isArray(originalCustomFields) ? originalCustomFields : [];
  3264. target._customFields = originalCustomFields.concat(fields);
  3265. };
  3266. }; // IE10 Hack:
  3267. // static properties in IE10 will not be inherited from super
  3268. // search for parse method and assign it manually
  3269. const IE10Compatible = target => {
  3270. if (isIE10) {
  3271. target.parse = getStaticProperty(target, 'parse');
  3272. }
  3273. };
  3274. var _dec, _class$1;
  3275. let // jsdoc-ignore-end
  3276. /**
  3277. * 所有内置的富媒体消息均继承自本类
  3278. * @extends Message
  3279. */
  3280. TypedMessage = (_dec = messageField(['_lctext', '_lcattrs']), _dec(_class$1 = class TypedMessage extends Message {
  3281. /**
  3282. * @type {Number}
  3283. * @readonly
  3284. */
  3285. get type() {
  3286. return this.constructor.TYPE;
  3287. }
  3288. /** @type {String} */
  3289. set text(text) {
  3290. return this.setText(text);
  3291. }
  3292. get text() {
  3293. return this.getText();
  3294. }
  3295. /** @type {Object} */
  3296. set attributes(attributes) {
  3297. return this.setAttributes(attributes);
  3298. }
  3299. get attributes() {
  3300. return this.getAttributes();
  3301. }
  3302. /**
  3303. * 在客户端需要以文本形式展示该消息时显示的文案,
  3304. * 如 <code>[红包] 新春快乐</code>。
  3305. * 默认值为消息的 text。
  3306. * @type {String}
  3307. * @readonly
  3308. */
  3309. get summary() {
  3310. return this.text;
  3311. }
  3312. /**
  3313. * @param {String} text
  3314. * @return {this} self
  3315. */
  3316. setText(text) {
  3317. this._lctext = text;
  3318. return this;
  3319. }
  3320. /**
  3321. * @return {String}
  3322. */
  3323. getText() {
  3324. return this._lctext;
  3325. }
  3326. /**
  3327. * @param {Object} attributes
  3328. * @return {this} self
  3329. */
  3330. setAttributes(attributes) {
  3331. this._lcattrs = attributes;
  3332. return this;
  3333. }
  3334. /**
  3335. * @return {Object}
  3336. */
  3337. getAttributes() {
  3338. return this._lcattrs;
  3339. }
  3340. _getCustomFields() {
  3341. const fields = Array.isArray(this.constructor._customFields) ? this.constructor._customFields : [];
  3342. return fields.reduce((result, field) => {
  3343. if (typeof field !== 'string') return result;
  3344. result[field] = this[field]; // eslint-disable-line no-param-reassign
  3345. return result;
  3346. }, {});
  3347. }
  3348. /* eslint-disable class-methods-use-this */
  3349. _getType() {
  3350. throw new Error('not implemented');
  3351. }
  3352. /* eslint-enable class-methods-use-this */
  3353. getPayload() {
  3354. return compact({
  3355. _lctext: this.getText(),
  3356. _lcattrs: this.getAttributes(),
  3357. ...this._getCustomFields(),
  3358. ...this._getType()
  3359. });
  3360. }
  3361. toJSON() {
  3362. const {
  3363. type,
  3364. text,
  3365. attributes,
  3366. summary
  3367. } = this;
  3368. return { ...super._toJSON(),
  3369. type,
  3370. text,
  3371. attributes,
  3372. summary
  3373. };
  3374. }
  3375. toFullJSON() {
  3376. return { ...super.toFullJSON(),
  3377. data: this.getPayload()
  3378. };
  3379. }
  3380. /**
  3381. * 解析处理消息内容
  3382. * <pre>
  3383. * 为给定的 message 设置 text 与 attributes 属性,返回该 message
  3384. * 如果子类没有提供 message,new this()
  3385. * @protected
  3386. * @param {Object} json json 格式的消息内容
  3387. * @param {TypedMessage} message 子类提供的 message
  3388. * @return {TypedMessage}
  3389. * @implements AVMessage.parse
  3390. */
  3391. static parse(json, message = new this()) {
  3392. message.content = json; // eslint-disable-line no-param-reassign
  3393. const customFields = isIE10 ? getStaticProperty(message.constructor, '_customFields') : message.constructor._customFields;
  3394. let fields = Array.isArray(customFields) ? customFields : [];
  3395. fields = fields.reduce((result, field) => {
  3396. if (typeof field !== 'string') return result;
  3397. result[field] = json[field]; // eslint-disable-line no-param-reassign
  3398. return result;
  3399. }, {});
  3400. Object.assign(message, fields);
  3401. return super.parse(json, message);
  3402. }
  3403. }) || _class$1);
  3404. var _dec$1, _class$2;
  3405. let // jsdoc-ignore-end
  3406. /**
  3407. * 已撤回类型消息,当消息被撤回时,SDK 会使用该类型的消息替代原始消息
  3408. * @extends TypedMessage
  3409. */
  3410. RecalledMessage = (_dec$1 = messageType(-127), _dec$1(_class$2 = IE10Compatible(_class$2 = class RecalledMessage extends TypedMessage {
  3411. /**
  3412. * 在客户端需要以文本形式展示该消息时显示的文案,值为 <code>[该消息已撤回]</code>
  3413. * @type {String}
  3414. * @readonly
  3415. */
  3416. // eslint-disable-next-line class-methods-use-this
  3417. get summary() {
  3418. return '[该消息已撤回]';
  3419. }
  3420. }) || _class$2) || _class$2);
  3421. /* eslint class-methods-use-this: ["error", { "exceptMethods": ["_addMembers", "_removeMembers"] }] */
  3422. const debug$7 = d('LC:Conversation');
  3423. const serializeMessage = message => {
  3424. const content = message.getPayload();
  3425. let msg;
  3426. let binaryMsg;
  3427. if (content instanceof ArrayBuffer) {
  3428. binaryMsg = content;
  3429. } else if (typeof content !== 'string') {
  3430. msg = JSON.stringify(content);
  3431. } else {
  3432. msg = content;
  3433. }
  3434. return {
  3435. msg,
  3436. binaryMsg
  3437. };
  3438. };
  3439. const {
  3440. NEW,
  3441. OLD
  3442. } = LogsCommand.QueryDirection;
  3443. /**
  3444. * 历史消息查询方向枚举
  3445. * @enum {Number}
  3446. * @since 4.0.0
  3447. * @memberof module:leancloud-realtime
  3448. */
  3449. const MessageQueryDirection = {
  3450. /** 从后向前 */
  3451. NEW_TO_OLD: OLD,
  3452. /** 从前向后 */
  3453. OLD_TO_NEW: NEW
  3454. };
  3455. Object.freeze(MessageQueryDirection);
  3456. class ConversationBase extends EventEmitter {
  3457. /**
  3458. * @extends EventEmitter
  3459. * @private
  3460. * @abstract
  3461. */
  3462. constructor({
  3463. id,
  3464. lastMessageAt,
  3465. lastMessage,
  3466. lastDeliveredAt,
  3467. lastReadAt,
  3468. unreadMessagesCount = 0,
  3469. members = [],
  3470. mentioned = false,
  3471. ...properties
  3472. }, client) {
  3473. super();
  3474. Object.assign(this, {
  3475. /**
  3476. * 对话 id,对应 _Conversation 表中的 objectId
  3477. * @memberof ConversationBase#
  3478. * @type {String}
  3479. */
  3480. id,
  3481. /**
  3482. * 最后一条消息时间
  3483. * @memberof ConversationBase#
  3484. * @type {?Date}
  3485. */
  3486. lastMessageAt,
  3487. /**
  3488. * 最后一条消息
  3489. * @memberof ConversationBase#
  3490. * @type {?Message}
  3491. */
  3492. lastMessage,
  3493. /**
  3494. * 参与该对话的用户列表
  3495. * @memberof ConversationBase#
  3496. * @type {String[]}
  3497. */
  3498. members,
  3499. // other properties provided by subclasses
  3500. ...properties
  3501. });
  3502. this.members = Array.from(new Set(this.members));
  3503. Object.assign(internal(this), {
  3504. messagesWaitingForReceipt: {},
  3505. lastDeliveredAt,
  3506. lastReadAt,
  3507. unreadMessagesCount,
  3508. mentioned
  3509. });
  3510. this._client = client;
  3511. if (debug$7.enabled) {
  3512. values(IMEvent).forEach(event => this.on(event, (...payload) => this._debug(`${event} event emitted. %o`, payload)));
  3513. } // onConversationCreate hook
  3514. applyDecorators(this._client._plugins.onConversationCreate, this);
  3515. }
  3516. /**
  3517. * 当前用户是否在该对话的未读消息中被提及
  3518. * @type {Boolean}
  3519. * @since 4.0.0
  3520. */
  3521. get unreadMessagesMentioned() {
  3522. return internal(this).unreadMessagesMentioned;
  3523. }
  3524. _setUnreadMessagesMentioned(value) {
  3525. internal(this).unreadMessagesMentioned = Boolean(value);
  3526. }
  3527. set unreadMessagesCount(value) {
  3528. if (value !== this.unreadMessagesCount) {
  3529. internal(this).unreadMessagesCount = value;
  3530. this._client.emit(UNREAD_MESSAGES_COUNT_UPDATE, [this]);
  3531. }
  3532. }
  3533. /**
  3534. * 当前用户在该对话的未读消息数
  3535. * @type {Number}
  3536. */
  3537. get unreadMessagesCount() {
  3538. return internal(this).unreadMessagesCount;
  3539. }
  3540. set lastMessageAt(value) {
  3541. const time = decodeDate(value);
  3542. if (time <= this._lastMessageAt) return;
  3543. this._lastMessageAt = time;
  3544. }
  3545. get lastMessageAt() {
  3546. return this._lastMessageAt;
  3547. }
  3548. /**
  3549. * 最后消息送达时间,常用来实现消息的「已送达」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
  3550. * @type {?Date}
  3551. * @since 3.4.0
  3552. */
  3553. get lastDeliveredAt() {
  3554. if (this.members.length !== 2) return null;
  3555. return internal(this).lastDeliveredAt;
  3556. }
  3557. _setLastDeliveredAt(value) {
  3558. const date = decodeDate(value);
  3559. if (!(date < internal(this).lastDeliveredAt)) {
  3560. internal(this).lastDeliveredAt = date;
  3561. /**
  3562. * 最后消息送达时间更新
  3563. * @event ConversationBase#LAST_DELIVERED_AT_UPDATE
  3564. * @since 3.4.0
  3565. */
  3566. this.emit(LAST_DELIVERED_AT_UPDATE);
  3567. }
  3568. }
  3569. /**
  3570. * 最后消息被阅读时间,常用来实现发送消息的「已读」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
  3571. * @type {?Date}
  3572. * @since 3.4.0
  3573. */
  3574. get lastReadAt() {
  3575. if (this.members.length !== 2) return null;
  3576. return internal(this).lastReadAt;
  3577. }
  3578. _setLastReadAt(value) {
  3579. const date = decodeDate(value);
  3580. if (!(date < internal(this).lastReadAt)) {
  3581. internal(this).lastReadAt = date;
  3582. /**
  3583. * 最后消息被阅读时间更新
  3584. * @event ConversationBase#LAST_READ_AT_UPDATE
  3585. * @since 3.4.0
  3586. */
  3587. this.emit(LAST_READ_AT_UPDATE);
  3588. }
  3589. }
  3590. /**
  3591. * 返回 JSON 格式的对话,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseConversation} 反序列化。
  3592. * @return {Object} 返回值是一个 plain Object
  3593. * @since 4.0.0
  3594. */
  3595. toFullJSON() {
  3596. const {
  3597. id,
  3598. members,
  3599. lastMessageAt,
  3600. lastDeliveredAt,
  3601. lastReadAt,
  3602. lastMessage,
  3603. unreadMessagesCount
  3604. } = this;
  3605. return {
  3606. id,
  3607. members,
  3608. lastMessageAt: getTime(lastMessageAt),
  3609. lastDeliveredAt: getTime(lastDeliveredAt),
  3610. lastReadAt: getTime(lastReadAt),
  3611. lastMessage: lastMessage ? lastMessage.toFullJSON() : undefined,
  3612. unreadMessagesCount
  3613. };
  3614. }
  3615. /**
  3616. * 返回 JSON 格式的对话
  3617. * @return {Object} 返回值是一个 plain Object
  3618. * @since 4.0.0
  3619. */
  3620. toJSON() {
  3621. const {
  3622. id,
  3623. members,
  3624. lastMessageAt,
  3625. lastDeliveredAt,
  3626. lastReadAt,
  3627. lastMessage,
  3628. unreadMessagesCount,
  3629. unreadMessagesMentioned
  3630. } = this;
  3631. return {
  3632. id,
  3633. members,
  3634. lastMessageAt,
  3635. lastDeliveredAt,
  3636. lastReadAt,
  3637. lastMessage: lastMessage ? lastMessage.toJSON() : undefined,
  3638. unreadMessagesCount,
  3639. unreadMessagesMentioned
  3640. };
  3641. }
  3642. _debug(...params) {
  3643. debug$7(...params, `[${this.id}]`);
  3644. }
  3645. _send(command, ...args) {
  3646. /* eslint-disable no-param-reassign */
  3647. if (command.cmd === null) {
  3648. command.cmd = 'conv';
  3649. }
  3650. if (command.cmd === 'conv' && command.convMessage === null) {
  3651. command.convMessage = new ConvCommand();
  3652. }
  3653. if (command.convMessage && command.convMessage.cid === null) {
  3654. command.convMessage.cid = this.id;
  3655. }
  3656. /* eslint-enable no-param-reassign */
  3657. return this._client._send(command, ...args);
  3658. }
  3659. /**
  3660. * 发送消息
  3661. * @param {Message} message 消息,Message 及其子类的实例
  3662. * @param {Object} [options] since v3.3.0,发送选项
  3663. * @param {Boolean} [options.transient] since v3.3.1,是否作为暂态消息发送
  3664. * @param {Boolean} [options.receipt] 是否需要回执,仅在普通对话中有效
  3665. * @param {Boolean} [options.will] since v3.4.0,是否指定该消息作为「掉线消息」发送,
  3666. * 「掉线消息」会延迟到当前用户掉线后发送,常用来实现「下线通知」功能
  3667. * @param {MessagePriority} [options.priority] 消息优先级,仅在暂态对话中有效,
  3668. * see: {@link module:leancloud-realtime.MessagePriority MessagePriority}
  3669. * @param {Object} [options.pushData] 消息对应的离线推送内容,如果消息接收方不在线,会推送指定的内容。其结构说明参见: {@link https://url.leanapp.cn/pushData 推送消息内容}
  3670. * @return {Promise.<Message>} 发送的消息
  3671. */
  3672. async send(message, options) {
  3673. this._debug(message, 'send');
  3674. if (!(message instanceof Message)) {
  3675. throw new TypeError(`${message} is not a Message`);
  3676. }
  3677. const {
  3678. transient,
  3679. receipt,
  3680. priority,
  3681. pushData,
  3682. will
  3683. } = { // support Message static property: sendOptions
  3684. ...message.constructor.sendOptions,
  3685. // support Message static property: getSendOptions
  3686. ...(typeof message.constructor.getSendOptions === 'function' ? message.constructor.getSendOptions(message) : {}),
  3687. ...options
  3688. };
  3689. if (receipt) {
  3690. if (this.transient) {
  3691. console.warn('receipt option is ignored as the conversation is transient.');
  3692. } else if (transient) {
  3693. console.warn('receipt option is ignored as the message is sent transiently.');
  3694. } else if (this.members.length > 2) {
  3695. console.warn('receipt option is recommended to be used in one-on-one conversation.'); // eslint-disable-line max-len
  3696. }
  3697. }
  3698. if (priority && !this.transient) {
  3699. console.warn('priority option is ignored as the conversation is not transient.');
  3700. }
  3701. Object.assign(message, {
  3702. cid: this.id,
  3703. from: this._client.id
  3704. });
  3705. message._setStatus(MessageStatus.SENDING);
  3706. const {
  3707. msg,
  3708. binaryMsg
  3709. } = serializeMessage(message);
  3710. const command = new GenericCommand({
  3711. cmd: 'direct',
  3712. directMessage: new DirectCommand({
  3713. msg,
  3714. binaryMsg,
  3715. cid: this.id,
  3716. r: receipt,
  3717. transient,
  3718. dt: message.id,
  3719. pushData: JSON.stringify(pushData),
  3720. will,
  3721. mentionPids: message.mentionList,
  3722. mentionAll: message.mentionedAll
  3723. }),
  3724. priority
  3725. });
  3726. try {
  3727. const resCommand = await this._send(command);
  3728. const {
  3729. ackMessage: {
  3730. uid,
  3731. t,
  3732. code,
  3733. reason,
  3734. appCode
  3735. }
  3736. } = resCommand;
  3737. if (code !== null) {
  3738. throw createError({
  3739. code,
  3740. reason,
  3741. appCode
  3742. });
  3743. }
  3744. Object.assign(message, {
  3745. id: uid,
  3746. timestamp: t
  3747. });
  3748. if (!transient) {
  3749. this.lastMessage = message;
  3750. this.lastMessageAt = message.timestamp;
  3751. }
  3752. message._setStatus(MessageStatus.SENT);
  3753. if (receipt) {
  3754. internal(this).messagesWaitingForReceipt[message.id] = message;
  3755. }
  3756. return message;
  3757. } catch (error) {
  3758. message._setStatus(MessageStatus.FAILED);
  3759. throw error;
  3760. }
  3761. }
  3762. async _update(message, newMessage, recall) {
  3763. this._debug('patch %O %O %O', message, newMessage, recall);
  3764. if (message instanceof Message) {
  3765. if (message.from !== this._client.id) {
  3766. throw new Error('Updating message from others is not allowed');
  3767. }
  3768. if (message.status !== MessageStatus.SENT && message.status !== MessageStatus.DELIVERED) {
  3769. throw new Error('Message is not sent');
  3770. }
  3771. } else if (!(message.id && message.timestamp)) {
  3772. throw new TypeError(`${message} is not a Message`);
  3773. }
  3774. let msg;
  3775. let binaryMsg;
  3776. if (!recall) {
  3777. const content = serializeMessage(newMessage);
  3778. ({
  3779. msg,
  3780. binaryMsg
  3781. } = content);
  3782. }
  3783. await this._send(new GenericCommand({
  3784. cmd: CommandType.patch,
  3785. op: OpType.modify,
  3786. patchMessage: new PatchCommand({
  3787. patches: [new PatchItem({
  3788. cid: this.id,
  3789. mid: message.id,
  3790. timestamp: Number(message.timestamp),
  3791. recall,
  3792. data: msg,
  3793. binaryMsg,
  3794. mentionPids: newMessage.mentionList,
  3795. mentionAll: newMessage.mentionedAll
  3796. })],
  3797. lastPatchTime: this._client._lastPatchTime
  3798. })
  3799. }));
  3800. const {
  3801. id,
  3802. cid,
  3803. timestamp,
  3804. from,
  3805. _status
  3806. } = message;
  3807. Object.assign(newMessage, {
  3808. id,
  3809. cid,
  3810. timestamp,
  3811. from,
  3812. _status
  3813. });
  3814. if (this.lastMessage && this.lastMessage.id === newMessage.id) {
  3815. this.lastMessage = newMessage;
  3816. }
  3817. return newMessage;
  3818. }
  3819. /**
  3820. * 获取对话人数,或暂态对话的在线人数
  3821. * @return {Promise.<Number>}
  3822. */
  3823. async count() {
  3824. this._debug('count');
  3825. const resCommand = await this._send(new GenericCommand({
  3826. op: 'count'
  3827. }));
  3828. return resCommand.convMessage.count;
  3829. }
  3830. /**
  3831. * 应用增加成员的操作,产生副作用
  3832. * @param {string[]} members
  3833. * @abstract
  3834. * @private
  3835. */
  3836. _addMembers() {}
  3837. /**
  3838. * 应用减少成员的操作,产生副作用
  3839. * @param {string[]} members
  3840. * @abstract
  3841. * @private
  3842. */
  3843. _removeMembers() {}
  3844. /**
  3845. * 修改已发送的消息
  3846. * @param {AVMessage} message 要修改的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
  3847. * @param {AVMessage} newMessage 新的消息
  3848. * @return {Promise.<AVMessage>} 更新后的消息
  3849. */
  3850. async update(message, newMessage) {
  3851. if (!(newMessage instanceof Message)) {
  3852. throw new TypeError(`${newMessage} is not a Message`);
  3853. }
  3854. return this._update(message, newMessage, false);
  3855. }
  3856. /**
  3857. * 撤回已发送的消息
  3858. * @param {AVMessage} message 要撤回的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
  3859. * @return {Promise.<RecalledMessage>} 一条已撤回的消息
  3860. */
  3861. async recall(message) {
  3862. return this._update(message, new RecalledMessage(), true);
  3863. }
  3864. /**
  3865. * 查询消息记录
  3866. * 如果仅需实现消息向前记录翻页查询需求,建议使用 {@link Conversation#createMessagesIterator}。
  3867. * 不论何种方向,获得的消息都是按照时间升序排列的。
  3868. * startClosed 与 endClosed 用于指定查询区间的开闭。
  3869. *
  3870. * @param {Object} [options]
  3871. * @param {Number} [options.limit] 限制查询结果的数量,目前服务端默认为 20
  3872. * @param {Number} [options.type] 指定查询的富媒体消息类型,不指定则查询所有消息。
  3873. * @param {MessageQueryDirection} [options.direction] 查询的方向。
  3874. * 在不指定的情况下如果 startTime 大于 endTime,则为从新到旧查询,可以实现加载聊天记录等场景。
  3875. * 如果 startTime 小于 endTime,则为从旧到新查询,可以实现弹幕等场景。
  3876. * @param {Date} [options.startTime] 从该时间开始查询,不传则从当前时间开始查询
  3877. * @param {String} [options.startMessageId] 从该消息之前开始查询,需要与 startTime 同时使用,为防止某时刻有重复消息
  3878. * @param {Boolean}[options.startClosed] 指定查询范围是否包括开始的时间点,默认不包括
  3879. * @param {Date} [options.endTime] 查询到该时间为止,不传则查询最早消息为止
  3880. * @param {String} [options.endMessageId] 查询到该消息为止,需要与 endTime 同时使用,为防止某时刻有重复消息
  3881. * @param {Boolean}[options.endClosed] 指定查询范围是否包括结束的时间点,默认不包括
  3882. *
  3883. * @param {Date} [options.beforeTime] DEPRECATED: 使用 startTime 代替。限制查询结果为小于该时间之前的消息,不传则为当前时间
  3884. * @param {String} [options.beforeMessageId] DEPRECATED: 使用 startMessageId 代替。
  3885. * 限制查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
  3886. * @param {Date} [options.afterTime] DEPRECATED: 使用 endTime 代替。限制查询结果为大于该时间之前的消息
  3887. * @param {String} [options.afterMessageId] DEPRECATED: 使用 endMessageId 代替。
  3888. * 限制查询结果为该消息之后的消息,需要与 afterTime 同时使用,为防止某时刻有重复消息
  3889. * @return {Promise.<Message[]>} 消息列表
  3890. */
  3891. async queryMessages(options = {}) {
  3892. this._debug('query messages %O', options);
  3893. const {
  3894. beforeTime,
  3895. beforeMessageId,
  3896. afterTime,
  3897. afterMessageId,
  3898. limit,
  3899. direction,
  3900. type,
  3901. startTime,
  3902. startMessageId,
  3903. startClosed,
  3904. endTime,
  3905. endMessageId,
  3906. endClosed
  3907. } = options;
  3908. if (beforeMessageId || beforeTime || afterMessageId || afterTime) {
  3909. console.warn('DEPRECATION: queryMessages options beforeTime, beforeMessageId, afterTime and afterMessageId are deprecated in favor of startTime, startMessageId, endTime and endMessageId.');
  3910. return this.queryMessages({
  3911. startTime: beforeTime,
  3912. startMessageId: beforeMessageId,
  3913. endTime: afterTime,
  3914. endMessageId: afterMessageId,
  3915. limit
  3916. });
  3917. }
  3918. if (startMessageId && !startTime) {
  3919. throw new Error('query option startMessageId must be used with option startTime');
  3920. }
  3921. if (endMessageId && !endTime) {
  3922. throw new Error('query option endMessageId must be used with option endTime');
  3923. }
  3924. const conditions = {
  3925. t: startTime,
  3926. mid: startMessageId,
  3927. tIncluded: startClosed,
  3928. tt: endTime,
  3929. tmid: endMessageId,
  3930. ttIncluded: endClosed,
  3931. l: limit,
  3932. lctype: type
  3933. };
  3934. if (conditions.t instanceof Date) {
  3935. conditions.t = conditions.t.getTime();
  3936. }
  3937. if (conditions.tt instanceof Date) {
  3938. conditions.tt = conditions.tt.getTime();
  3939. }
  3940. if (direction !== undefined) {
  3941. conditions.direction = direction;
  3942. } else if (conditions.tt > conditions.t) {
  3943. conditions.direction = MessageQueryDirection.OLD_TO_NEW;
  3944. }
  3945. const resCommand = await this._send(new GenericCommand({
  3946. cmd: 'logs',
  3947. logsMessage: new LogsCommand(Object.assign(conditions, {
  3948. cid: this.id
  3949. }))
  3950. }));
  3951. return Promise.all(resCommand.logsMessage.logs.map(async ({
  3952. msgId,
  3953. timestamp,
  3954. patchTimestamp,
  3955. from,
  3956. ackAt,
  3957. readAt,
  3958. data,
  3959. mentionAll,
  3960. mentionPids,
  3961. bin
  3962. }) => {
  3963. const messageData = {
  3964. data,
  3965. bin,
  3966. id: msgId,
  3967. cid: this.id,
  3968. timestamp,
  3969. from,
  3970. deliveredAt: ackAt,
  3971. updatedAt: patchTimestamp,
  3972. mentionList: mentionPids,
  3973. mentionedAll: mentionAll
  3974. };
  3975. const message = await this._client.parseMessage(messageData);
  3976. let status = MessageStatus.SENT;
  3977. if (this.members.length === 2) {
  3978. if (ackAt) status = MessageStatus.DELIVERED;
  3979. if (ackAt) this._setLastDeliveredAt(ackAt);
  3980. if (readAt) this._setLastReadAt(readAt);
  3981. }
  3982. message._setStatus(status);
  3983. return message;
  3984. }));
  3985. }
  3986. /**
  3987. * 获取消息翻页迭代器
  3988. * @param {Object} [options]
  3989. * @param {Date} [options.beforeTime] 限制起始查询结果为小于该时间之前的消息,不传则为当前时间
  3990. * @param {String} [options.beforeMessageId] 限制起始查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
  3991. * @param {Number} [options.limit] 限制每页查询结果的数量,目前服务端默认为 20
  3992. * @return {AsyncIterater.<Promise.<IteratorResult<Message[]>>>} [AsyncIterator]{@link https://github.com/tc39/proposal-async-iteration},调用其 next 方法返回获取下一页消息的 Promise
  3993. * @example
  3994. * var messageIterator = conversation.createMessagesIterator({ limit: 10 });
  3995. * messageIterator.next().then(function(result) {
  3996. * // result: {
  3997. * // value: [message1, ..., message10],
  3998. * // done: false,
  3999. * // }
  4000. * });
  4001. * messageIterator.next().then(function(result) {
  4002. * // result: {
  4003. * // value: [message11, ..., message20],
  4004. * // done: false,
  4005. * // }
  4006. * });
  4007. * messageIterator.next().then(function(result) {
  4008. * // No more messages
  4009. * // result: { value: [], done: true }
  4010. * });
  4011. */
  4012. createMessagesIterator({
  4013. beforeTime,
  4014. beforeMessageId,
  4015. limit
  4016. } = {}) {
  4017. let promise;
  4018. return {
  4019. next: () => {
  4020. if (promise === undefined) {
  4021. // first call
  4022. promise = this.queryMessages({
  4023. limit,
  4024. startTime: beforeTime,
  4025. startMessageId: beforeMessageId
  4026. });
  4027. } else {
  4028. promise = promise.then(prevMessages => {
  4029. if (prevMessages.length === 0 || prevMessages.length < limit) {
  4030. // no more messages
  4031. return [];
  4032. }
  4033. return this.queryMessages({
  4034. startTime: prevMessages[0].timestamp,
  4035. startMessageId: prevMessages[0].id,
  4036. limit
  4037. });
  4038. });
  4039. }
  4040. return promise.then(value => ({
  4041. value: Array.from(value),
  4042. done: value.length === 0 || value.length < limit
  4043. }));
  4044. }
  4045. };
  4046. }
  4047. /**
  4048. * 将该会话标记为已读
  4049. * @return {Promise.<this>} self
  4050. */
  4051. async read() {
  4052. this.unreadMessagesCount = 0;
  4053. this._setUnreadMessagesMentioned(false); // 跳过暂态会话
  4054. if (this.transient) return this;
  4055. const client = this._client;
  4056. if (!internal(client).readConversationsBuffer) {
  4057. internal(client).readConversationsBuffer = new Set();
  4058. }
  4059. internal(client).readConversationsBuffer.add(this);
  4060. client._doSendRead();
  4061. return this;
  4062. }
  4063. _handleReceipt({
  4064. messageId,
  4065. timestamp,
  4066. read
  4067. }) {
  4068. if (read) {
  4069. this._setLastReadAt(timestamp);
  4070. } else {
  4071. this._setLastDeliveredAt(timestamp);
  4072. }
  4073. const {
  4074. messagesWaitingForReceipt
  4075. } = internal(this);
  4076. const message = messagesWaitingForReceipt[messageId];
  4077. if (!message) return;
  4078. message._setStatus(MessageStatus.DELIVERED);
  4079. message.deliveredAt = timestamp;
  4080. delete messagesWaitingForReceipt[messageId];
  4081. }
  4082. /**
  4083. * 更新对话的最新回执时间戳(lastDeliveredAt、lastReadAt)
  4084. * @since 3.4.0
  4085. * @return {Promise.<this>} this
  4086. */
  4087. async fetchReceiptTimestamps() {
  4088. // 暂态/系统会话不支持回执
  4089. if (this.transient || this.system) return this;
  4090. const {
  4091. convMessage: {
  4092. maxReadTimestamp,
  4093. maxAckTimestamp
  4094. }
  4095. } = await this._send(new GenericCommand({
  4096. op: 'max_read'
  4097. }));
  4098. this._setLastDeliveredAt(maxAckTimestamp);
  4099. this._setLastReadAt(maxReadTimestamp);
  4100. return this;
  4101. }
  4102. _fetchAllReceiptTimestamps() {
  4103. // 暂态/系统会话不支持回执
  4104. if (this.transient || this.system) return this;
  4105. const convMessage = new ConvCommand({
  4106. queryAllMembers: true
  4107. });
  4108. return this._send(new GenericCommand({
  4109. op: 'max_read',
  4110. convMessage
  4111. })).then(({
  4112. convMessage: {
  4113. maxReadTuples
  4114. }
  4115. }) => maxReadTuples.filter(maxReadTuple => maxReadTuple.maxAckTimestamp || maxReadTuple.maxReadTimestamp).map(({
  4116. pid,
  4117. maxAckTimestamp,
  4118. maxReadTimestamp
  4119. }) => ({
  4120. pid,
  4121. lastDeliveredAt: decodeDate(maxAckTimestamp),
  4122. lastReadAt: decodeDate(maxReadTimestamp)
  4123. })));
  4124. }
  4125. }
  4126. const debug$8 = d('LC:SignatureFactoryRunner');
  4127. function _validateSignature(signatureResult = {}) {
  4128. const {
  4129. signature,
  4130. timestamp,
  4131. nonce
  4132. } = signatureResult;
  4133. if (typeof signature !== 'string' || typeof timestamp !== 'number' || typeof nonce !== 'string') {
  4134. throw new Error('malformed signature');
  4135. }
  4136. return {
  4137. signature,
  4138. timestamp,
  4139. nonce
  4140. };
  4141. }
  4142. var runSignatureFactory = ((signatureFactory, params) => Promise.resolve().then(() => {
  4143. debug$8('call signatureFactory with %O', params);
  4144. return signatureFactory(...params);
  4145. }).then(tap(signatureResult => debug$8('sign result %O', signatureResult)), error => {
  4146. // eslint-disable-next-line no-param-reassign
  4147. error.message = `sign error: ${error.message}`;
  4148. debug$8(error);
  4149. throw error;
  4150. }).then(_validateSignature));
  4151. /**
  4152. * 部分失败异常
  4153. * @typedef OperationFailureError
  4154. * @type {Error}
  4155. * @property {string} message 异常信息
  4156. * @property {string[]} clientIds 因为该原因失败的 client id 列表
  4157. * @property {number} [code] 错误码
  4158. * @property {string} [detail] 详细信息
  4159. */
  4160. /**
  4161. * 部分成功的结果
  4162. * @typedef PartiallySuccess
  4163. * @type {Object}
  4164. * @property {string[]} successfulClientIds 成功的 client id 列表
  4165. * @property {OperationFailureError[]} failures 失败的异常列表
  4166. */
  4167. /**
  4168. * 分页查询结果
  4169. * @typedef PagedResults
  4170. * @type {Object}
  4171. * @property {T[]} results 查询结果
  4172. * @property {string} [next] 存在表示还有更多结果,在下次查询中带上可实现翻页。
  4173. */
  4174. const createPartiallySuccess = ({
  4175. allowedPids,
  4176. failedPids
  4177. }) => ({
  4178. successfulClientIds: allowedPids,
  4179. failures: failedPids.map(({
  4180. pids,
  4181. ...error
  4182. }) => Object.assign(createError(error), {
  4183. clientIds: pids
  4184. }))
  4185. });
  4186. /**
  4187. * @extends ConversationBase
  4188. * @private
  4189. * @abstract
  4190. */
  4191. class PersistentConversation extends ConversationBase {
  4192. constructor(data, {
  4193. creator,
  4194. createdAt,
  4195. updatedAt,
  4196. transient = false,
  4197. system = false,
  4198. muted = false,
  4199. mutedMembers = [],
  4200. ...attributes
  4201. }, client) {
  4202. super({ ...data,
  4203. /**
  4204. * 对话创建者
  4205. * @memberof PersistentConversation#
  4206. * @type {String}
  4207. */
  4208. creator,
  4209. /**
  4210. * 对话创建时间
  4211. * @memberof PersistentConversation#
  4212. * @type {Date}
  4213. */
  4214. createdAt,
  4215. /**
  4216. * 对话更新时间
  4217. * @memberof PersistentConversation#
  4218. * @type {Date}
  4219. */
  4220. updatedAt,
  4221. /**
  4222. * 对该对话设置了静音的用户列表
  4223. * @memberof PersistentConversation#
  4224. * @type {?String[]}
  4225. */
  4226. mutedMembers,
  4227. /**
  4228. * 暂态对话标记
  4229. * @memberof PersistentConversation#
  4230. * @type {Boolean}
  4231. */
  4232. transient,
  4233. /**
  4234. * 系统对话标记
  4235. * @memberof PersistentConversation#
  4236. * @type {Boolean}
  4237. * @since 3.3.0
  4238. */
  4239. system,
  4240. /**
  4241. * 当前用户静音该对话标记
  4242. * @memberof PersistentConversation#
  4243. * @type {Boolean}
  4244. */
  4245. muted,
  4246. _attributes: attributes
  4247. }, client);
  4248. this._reset();
  4249. }
  4250. set createdAt(value) {
  4251. this._createdAt = decodeDate(value);
  4252. }
  4253. get createdAt() {
  4254. return this._createdAt;
  4255. }
  4256. set updatedAt(value) {
  4257. this._updatedAt = decodeDate(value);
  4258. }
  4259. get updatedAt() {
  4260. return this._updatedAt;
  4261. }
  4262. /**
  4263. * 对话名字,对应 _Conversation 表中的 name
  4264. * @type {String}
  4265. */
  4266. get name() {
  4267. return this.get('name');
  4268. }
  4269. set name(value) {
  4270. this.set('name', value);
  4271. }
  4272. /**
  4273. * 获取对话的自定义属性
  4274. * @since 3.2.0
  4275. * @param {String} key key 属性的键名,'x' 对应 Conversation 表中的 x 列
  4276. * @return {Any} 属性的值
  4277. */
  4278. get(key) {
  4279. return get(internal(this).currentAttributes, key);
  4280. }
  4281. /**
  4282. * 设置对话的自定义属性
  4283. * @since 3.2.0
  4284. * @param {String} key 属性的键名,'x' 对应 Conversation 表中的 x 列,支持使用 'x.y.z' 来修改对象的部分字段。
  4285. * @param {Any} value 属性的值
  4286. * @return {this} self
  4287. * @example
  4288. *
  4289. * // 设置对话的 color 属性
  4290. * conversation.set('color', {
  4291. * text: '#000',
  4292. * background: '#DDD',
  4293. * });
  4294. * // 设置对话的 color.text 属性
  4295. * conversation.set('color.text', '#333');
  4296. */
  4297. set(key, value) {
  4298. this._debug(`set [${key}]: ${value}`);
  4299. const {
  4300. pendingAttributes
  4301. } = internal(this);
  4302. const pendingKeys = Object.keys(pendingAttributes); // suppose pendingAttributes = { 'a.b': {} }
  4303. // set 'a' or 'a.b': delete 'a.b'
  4304. const re = new RegExp(`^${key}`);
  4305. const childKeys = pendingKeys.filter(re.test.bind(re));
  4306. childKeys.forEach(k => {
  4307. delete pendingAttributes[k];
  4308. });
  4309. if (childKeys.length) {
  4310. pendingAttributes[key] = value;
  4311. } else {
  4312. // set 'a.c': nothing to do
  4313. // set 'a.b.c.d': assign c: { d: {} } to 'a.b'
  4314. const parentKey = find(pendingKeys, k => key.indexOf(k) === 0); // 'a.b'
  4315. if (parentKey) {
  4316. setValue(pendingAttributes[parentKey], key.slice(parentKey.length + 1), value);
  4317. } else {
  4318. pendingAttributes[key] = value;
  4319. }
  4320. }
  4321. this._buildCurrentAttributes();
  4322. return this;
  4323. }
  4324. _buildCurrentAttributes() {
  4325. const {
  4326. pendingAttributes
  4327. } = internal(this);
  4328. internal(this).currentAttributes = Object.keys(pendingAttributes).reduce((target, k) => setValue(target, k, pendingAttributes[k]), cloneDeep(this._attributes));
  4329. }
  4330. _updateServerAttributes(attributes) {
  4331. Object.keys(attributes).forEach(key => setValue(this._attributes, key, attributes[key]));
  4332. this._buildCurrentAttributes();
  4333. }
  4334. _reset() {
  4335. Object.assign(internal(this), {
  4336. pendingAttributes: {},
  4337. currentAttributes: this._attributes
  4338. });
  4339. }
  4340. /**
  4341. * 保存当前对话的属性至服务器
  4342. * @return {Promise.<this>} self
  4343. */
  4344. async save() {
  4345. this._debug('save');
  4346. const attr = internal(this).pendingAttributes;
  4347. if (isEmpty(attr)) {
  4348. this._debug('nothing touched, resolve with self');
  4349. return this;
  4350. }
  4351. this._debug('attr: %O', attr);
  4352. const convMessage = new ConvCommand({
  4353. attr: new JsonObjectMessage({
  4354. data: JSON.stringify(encode(attr))
  4355. })
  4356. });
  4357. const resCommand = await this._send(new GenericCommand({
  4358. op: 'update',
  4359. convMessage
  4360. }));
  4361. this.updatedAt = resCommand.convMessage.udate;
  4362. this._attributes = internal(this).currentAttributes;
  4363. internal(this).pendingAttributes = {};
  4364. return this;
  4365. }
  4366. /**
  4367. * 从服务器更新对话的属性
  4368. * @return {Promise.<this>} self
  4369. */
  4370. async fetch() {
  4371. const query = this._client.getQuery().equalTo('objectId', this.id);
  4372. await query.find();
  4373. return this;
  4374. }
  4375. /**
  4376. * 静音,客户端拒绝收到服务器端的离线推送通知
  4377. * @return {Promise.<this>} self
  4378. */
  4379. async mute() {
  4380. this._debug('mute');
  4381. await this._send(new GenericCommand({
  4382. op: 'mute'
  4383. }));
  4384. if (!this.transient) {
  4385. this.muted = true;
  4386. this.mutedMembers = union(this.mutedMembers, [this._client.id]);
  4387. }
  4388. return this;
  4389. }
  4390. /**
  4391. * 取消静音
  4392. * @return {Promise.<this>} self
  4393. */
  4394. async unmute() {
  4395. this._debug('unmute');
  4396. await this._send(new GenericCommand({
  4397. op: 'unmute'
  4398. }));
  4399. if (!this.transient) {
  4400. this.muted = false;
  4401. this.mutedMembers = difference(this.mutedMembers, [this._client.id]);
  4402. }
  4403. return this;
  4404. }
  4405. async _appendConversationSignature(command, action, clientIds) {
  4406. if (this._client.options.conversationSignatureFactory) {
  4407. const params = [this.id, this._client.id, clientIds.sort(), action];
  4408. const signatureResult = await runSignatureFactory(this._client.options.conversationSignatureFactory, params);
  4409. Object.assign(command.convMessage, keyRemap({
  4410. signature: 's',
  4411. timestamp: 't',
  4412. nonce: 'n'
  4413. }, signatureResult));
  4414. }
  4415. }
  4416. async _appendBlacklistSignature(command, action, clientIds) {
  4417. if (this._client.options.blacklistSignatureFactory) {
  4418. const params = [this.id, this._client.id, clientIds.sort(), action];
  4419. const signatureResult = await runSignatureFactory(this._client.options.blacklistSignatureFactory, params);
  4420. Object.assign(command.blacklistMessage, keyRemap({
  4421. signature: 's',
  4422. timestamp: 't',
  4423. nonce: 'n'
  4424. }, signatureResult));
  4425. }
  4426. }
  4427. /**
  4428. * 增加成员
  4429. * @param {String|String[]} clientIds 新增成员 client id
  4430. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  4431. */
  4432. async add(clientIds) {
  4433. this._debug('add', clientIds);
  4434. if (typeof clientIds === 'string') {
  4435. clientIds = [clientIds]; // eslint-disable-line no-param-reassign
  4436. }
  4437. const command = new GenericCommand({
  4438. op: 'add',
  4439. convMessage: new ConvCommand({
  4440. m: clientIds
  4441. })
  4442. });
  4443. await this._appendConversationSignature(command, 'invite', clientIds);
  4444. const {
  4445. convMessage,
  4446. convMessage: {
  4447. allowedPids
  4448. }
  4449. } = await this._send(command);
  4450. this._addMembers(allowedPids);
  4451. return createPartiallySuccess(convMessage);
  4452. }
  4453. /**
  4454. * 剔除成员
  4455. * @param {String|String[]} clientIds 成员 client id
  4456. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  4457. */
  4458. async remove(clientIds) {
  4459. this._debug('remove', clientIds);
  4460. if (typeof clientIds === 'string') {
  4461. clientIds = [clientIds]; // eslint-disable-line no-param-reassign
  4462. }
  4463. const command = new GenericCommand({
  4464. op: 'remove',
  4465. convMessage: new ConvCommand({
  4466. m: clientIds
  4467. })
  4468. });
  4469. await this._appendConversationSignature(command, 'kick', clientIds);
  4470. const {
  4471. convMessage,
  4472. convMessage: {
  4473. allowedPids
  4474. }
  4475. } = await this._send(command);
  4476. this._removeMembers(allowedPids);
  4477. return createPartiallySuccess(convMessage);
  4478. }
  4479. /**
  4480. * (当前用户)加入该对话
  4481. * @return {Promise.<this>} self
  4482. */
  4483. async join() {
  4484. this._debug('join');
  4485. return this.add(this._client.id).then(({
  4486. failures
  4487. }) => {
  4488. if (failures[0]) throw failures[0];
  4489. return this;
  4490. });
  4491. }
  4492. /**
  4493. * (当前用户)退出该对话
  4494. * @return {Promise.<this>} self
  4495. */
  4496. async quit() {
  4497. this._debug('quit');
  4498. return this.remove(this._client.id).then(({
  4499. failures
  4500. }) => {
  4501. if (failures[0]) throw failures[0];
  4502. return this;
  4503. });
  4504. }
  4505. /**
  4506. * 在该对话中禁言成员
  4507. * @param {String|String[]} clientIds 成员 client id
  4508. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  4509. */
  4510. async muteMembers(clientIds) {
  4511. this._debug('mute', clientIds);
  4512. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  4513. const command = new GenericCommand({
  4514. op: OpType.add_shutup,
  4515. convMessage: new ConvCommand({
  4516. m: clientIds
  4517. })
  4518. });
  4519. const {
  4520. convMessage
  4521. } = await this._send(command);
  4522. return createPartiallySuccess(convMessage);
  4523. }
  4524. /**
  4525. * 在该对话中解除成员禁言
  4526. * @param {String|String[]} clientIds 成员 client id
  4527. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  4528. */
  4529. async unmuteMembers(clientIds) {
  4530. this._debug('unmute', clientIds);
  4531. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  4532. const command = new GenericCommand({
  4533. op: OpType.remove_shutup,
  4534. convMessage: new ConvCommand({
  4535. m: clientIds
  4536. })
  4537. });
  4538. const {
  4539. convMessage
  4540. } = await this._send(command);
  4541. return createPartiallySuccess(convMessage);
  4542. }
  4543. /**
  4544. * 查询该对话禁言成员列表
  4545. * @param {Object} [options]
  4546. * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
  4547. * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页。
  4548. * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
  4549. */
  4550. async queryMutedMembers({
  4551. limit,
  4552. next
  4553. } = {}) {
  4554. this._debug('query muted: limit %O, next: %O', limit, next);
  4555. const command = new GenericCommand({
  4556. op: OpType.query_shutup,
  4557. convMessage: new ConvCommand({
  4558. limit,
  4559. next
  4560. })
  4561. });
  4562. const {
  4563. convMessage: {
  4564. m,
  4565. next: newNext
  4566. }
  4567. } = await this._send(command);
  4568. return {
  4569. results: m,
  4570. next: newNext
  4571. };
  4572. }
  4573. /**
  4574. * 将用户加入该对话黑名单
  4575. * @param {String|String[]} clientIds 成员 client id
  4576. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  4577. */
  4578. async blockMembers(clientIds) {
  4579. this._debug('block', clientIds);
  4580. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  4581. const command = new GenericCommand({
  4582. cmd: 'blacklist',
  4583. op: OpType.block,
  4584. blacklistMessage: new BlacklistCommand({
  4585. srcCid: this.id,
  4586. toPids: clientIds
  4587. })
  4588. });
  4589. await this._appendBlacklistSignature(command, 'conversation-block-clients', clientIds);
  4590. const {
  4591. blacklistMessage
  4592. } = await this._send(command);
  4593. return createPartiallySuccess(blacklistMessage);
  4594. }
  4595. /**
  4596. * 将用户移出该对话黑名单
  4597. * @param {String|String[]} clientIds 成员 client id
  4598. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  4599. */
  4600. async unblockMembers(clientIds) {
  4601. this._debug('unblock', clientIds);
  4602. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  4603. const command = new GenericCommand({
  4604. cmd: 'blacklist',
  4605. op: OpType.unblock,
  4606. blacklistMessage: new BlacklistCommand({
  4607. srcCid: this.id,
  4608. toPids: clientIds
  4609. })
  4610. });
  4611. await this._appendBlacklistSignature(command, 'conversation-unblock-clients', clientIds);
  4612. const {
  4613. blacklistMessage
  4614. } = await this._send(command);
  4615. return createPartiallySuccess(blacklistMessage);
  4616. }
  4617. /**
  4618. * 查询该对话黑名单
  4619. * @param {Object} [options]
  4620. * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
  4621. * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页
  4622. * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
  4623. */
  4624. async queryBlockedMembers({
  4625. limit,
  4626. next
  4627. } = {}) {
  4628. this._debug('query blocked: limit %O, next: %O', limit, next);
  4629. const command = new GenericCommand({
  4630. cmd: 'blacklist',
  4631. op: OpType.query,
  4632. blacklistMessage: new BlacklistCommand({
  4633. srcCid: this.id,
  4634. limit,
  4635. next
  4636. })
  4637. });
  4638. const {
  4639. blacklistMessage: {
  4640. blockedPids,
  4641. next: newNext
  4642. }
  4643. } = await this._send(command);
  4644. return {
  4645. results: blockedPids,
  4646. next: newNext
  4647. };
  4648. }
  4649. toFullJSON() {
  4650. const {
  4651. creator,
  4652. system,
  4653. transient,
  4654. createdAt,
  4655. updatedAt,
  4656. _attributes
  4657. } = this;
  4658. return { ...super.toFullJSON(),
  4659. creator,
  4660. system,
  4661. transient,
  4662. createdAt: getTime(createdAt),
  4663. updatedAt: getTime(updatedAt),
  4664. ..._attributes
  4665. };
  4666. }
  4667. toJSON() {
  4668. const {
  4669. creator,
  4670. system,
  4671. transient,
  4672. muted,
  4673. mutedMembers,
  4674. createdAt,
  4675. updatedAt,
  4676. _attributes
  4677. } = this;
  4678. return { ...super.toJSON(),
  4679. creator,
  4680. system,
  4681. transient,
  4682. muted,
  4683. mutedMembers,
  4684. createdAt,
  4685. updatedAt,
  4686. ..._attributes
  4687. };
  4688. }
  4689. }
  4690. /**
  4691. * 对话成员角色枚举
  4692. * @enum {String}
  4693. * @since 4.0.0
  4694. * @memberof module:leancloud-realtime
  4695. */
  4696. const ConversationMemberRole = {
  4697. /** 所有者 */
  4698. OWNER: 'Owner',
  4699. /** 管理员 */
  4700. MANAGER: 'Manager',
  4701. /** 成员 */
  4702. MEMBER: 'Member'
  4703. };
  4704. Object.freeze(ConversationMemberRole);
  4705. class ConversationMemberInfo {
  4706. /**
  4707. * 对话成员属性,保存了成员与某个对话相关的属性,对应 _ConversationMemberInfo 表
  4708. * @since 4.0.0
  4709. */
  4710. constructor({
  4711. conversation,
  4712. memberId,
  4713. role
  4714. }) {
  4715. if (!conversation) throw new Error('conversation requried');
  4716. if (!memberId) throw new Error('memberId requried');
  4717. Object.assign(internal(this), {
  4718. conversation,
  4719. memberId,
  4720. role
  4721. });
  4722. }
  4723. /**
  4724. * 对话 Id
  4725. * @type {String}
  4726. * @readonly
  4727. */
  4728. get conversationId() {
  4729. return internal(this).conversation.id;
  4730. }
  4731. /**
  4732. * 成员 Id
  4733. * @type {String}
  4734. * @readonly
  4735. */
  4736. get memberId() {
  4737. return internal(this).memberId;
  4738. }
  4739. /**
  4740. * 角色
  4741. * @type {module:leancloud-realtime.ConversationMemberRole | String}
  4742. * @readonly
  4743. */
  4744. get role() {
  4745. if (this.isOwner) return ConversationMemberRole.OWNER;
  4746. return internal(this).role;
  4747. }
  4748. /**
  4749. * 是否是管理员
  4750. * @type {Boolean}
  4751. * @readonly
  4752. */
  4753. get isOwner() {
  4754. return this.memberId === internal(this).conversation.creator;
  4755. }
  4756. toJSON() {
  4757. const {
  4758. conversationId,
  4759. memberId,
  4760. role,
  4761. isOwner
  4762. } = this;
  4763. return {
  4764. conversationId,
  4765. memberId,
  4766. role,
  4767. isOwner
  4768. };
  4769. }
  4770. }
  4771. /**
  4772. * 普通对话
  4773. *
  4774. * 无法直接实例化,请使用 {@link IMClient#createConversation} 创建新的普通对话。
  4775. * @extends PersistentConversation
  4776. * @public
  4777. */
  4778. class Conversation extends PersistentConversation {
  4779. _addMembers(members) {
  4780. super._addMembers(members);
  4781. this.members = union(this.members, members);
  4782. const {
  4783. memberInfoMap
  4784. } = internal(this);
  4785. if (!memberInfoMap) return;
  4786. members.forEach(memberId => {
  4787. memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
  4788. conversation: this,
  4789. memberId,
  4790. role: ConversationMemberRole.MEMBER
  4791. });
  4792. });
  4793. }
  4794. _removeMembers(members) {
  4795. super._removeMembers(members);
  4796. this.members = difference(this.members, members);
  4797. const {
  4798. memberInfoMap
  4799. } = internal(this);
  4800. if (!memberInfoMap) return;
  4801. members.forEach(memberId => {
  4802. delete memberInfoMap[memberId];
  4803. });
  4804. }
  4805. async _fetchAllMemberInfo() {
  4806. const response = await this._client._requestWithSessionToken({
  4807. method: 'GET',
  4808. path: '/classes/_ConversationMemberInfo',
  4809. query: {
  4810. where: {
  4811. cid: this.id
  4812. }
  4813. }
  4814. });
  4815. const memberInfos = response.results.map(info => new ConversationMemberInfo({
  4816. conversation: this,
  4817. memberId: info.clientId,
  4818. role: info.role
  4819. }));
  4820. const memberInfoMap = {};
  4821. memberInfos.forEach(memberInfo => {
  4822. memberInfoMap[memberInfo.memberId] = memberInfo;
  4823. });
  4824. this.members.forEach(memberId => {
  4825. memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
  4826. conversation: this,
  4827. memberId,
  4828. role: ConversationMemberRole.MEMBER
  4829. });
  4830. });
  4831. internal(this).memberInfoMap = memberInfoMap;
  4832. return memberInfoMap;
  4833. }
  4834. /**
  4835. * 获取所有成员的对话属性
  4836. * @since 4.0.0
  4837. * @return {Promise.<ConversationMemberInfo[]>} 所有成员的对话属性列表
  4838. */
  4839. async getAllMemberInfo({
  4840. noCache = false
  4841. } = {}) {
  4842. let {
  4843. memberInfoMap
  4844. } = internal(this);
  4845. if (!memberInfoMap || noCache) {
  4846. memberInfoMap = await this._fetchAllMemberInfo();
  4847. }
  4848. return this.members.map(memberId => memberInfoMap[memberId]);
  4849. }
  4850. /**
  4851. * 获取指定成员的对话属性
  4852. * @since 4.0.0
  4853. * @param {String} memberId 成员 Id
  4854. * @return {Promise.<ConversationMemberInfo>} 指定成员的对话属性
  4855. */
  4856. async getMemberInfo(memberId) {
  4857. if (this.members.indexOf(memberId) === -1) throw new Error(`${memberId} is not the mumber of conversation[${this.id}]`);
  4858. const {
  4859. memberInfoMap
  4860. } = internal(this);
  4861. if (!(memberInfoMap && memberInfoMap[memberId])) await this.getAllMemberInfo();
  4862. return internal(this).memberInfoMap[memberId];
  4863. }
  4864. /**
  4865. * 更新指定用户的角色
  4866. * @since 4.0.0
  4867. * @param {String} memberId 成员 Id
  4868. * @param {module:leancloud-realtime.ConversationMemberRole | String} role 角色
  4869. * @return {Promise.<this>} self
  4870. */
  4871. async updateMemberRole(memberId, role) {
  4872. this._debug('update member role');
  4873. if (role === ConversationMemberRole.OWNER) throw createError({
  4874. code: ErrorCode.OWNER_PROMOTION_NOT_ALLOWED
  4875. });
  4876. await this._send(new GenericCommand({
  4877. op: OpType.member_info_update,
  4878. convMessage: new ConvCommand({
  4879. targetClientId: memberId,
  4880. info: new ConvMemberInfo({
  4881. pid: memberId,
  4882. role
  4883. })
  4884. })
  4885. }));
  4886. const {
  4887. memberInfos
  4888. } = internal(this);
  4889. if (memberInfos && memberInfos[memberId]) {
  4890. internal(memberInfos[memberId]).role = role;
  4891. }
  4892. return this;
  4893. }
  4894. }
  4895. /**
  4896. * 聊天室。
  4897. *
  4898. * 无法直接实例化,请使用 {@link IMClient#createChatRoom} 创建新的聊天室。
  4899. * @since 4.0.0
  4900. * @extends PersistentConversation
  4901. * @public
  4902. */
  4903. class ChatRoom extends PersistentConversation {}
  4904. /**
  4905. * 服务号。
  4906. *
  4907. * 服务号不支持在客户端创建。
  4908. * @since 4.0.0
  4909. * @extends PersistentConversation
  4910. * @public
  4911. */
  4912. class ServiceConversation extends PersistentConversation {
  4913. /**
  4914. * 订阅该服务号
  4915. * @return {Promise.<this>} self
  4916. */
  4917. async subscribe() {
  4918. return this.join();
  4919. }
  4920. /**
  4921. * 退订该服务号
  4922. * @return {Promise.<this>} self
  4923. */
  4924. async unsubscribe() {
  4925. return this.quit();
  4926. }
  4927. }
  4928. const transformNotFoundError = error => error.code === ErrorCode.CONVERSATION_NOT_FOUND ? createError({
  4929. code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
  4930. }) : error;
  4931. /**
  4932. * 临时对话
  4933. * @since 4.0.0
  4934. * @extends ConversationBase
  4935. * @public
  4936. */
  4937. class TemporaryConversation extends ConversationBase {
  4938. /**
  4939. * 无法直接实例化,请使用 {@link IMClient#createTemporaryConversation} 创建新的临时对话。
  4940. */
  4941. constructor(data, {
  4942. expiredAt
  4943. }, client) {
  4944. super({ ...data,
  4945. expiredAt
  4946. }, client);
  4947. }
  4948. /**
  4949. * 对话失效时间
  4950. * @type {Date}
  4951. */
  4952. set expiredAt(value) {
  4953. this._expiredAt = decodeDate(value);
  4954. }
  4955. get expiredAt() {
  4956. return this._expiredAt;
  4957. }
  4958. /**
  4959. * 对话是否已失效
  4960. * @type {Boolean}
  4961. */
  4962. get expired() {
  4963. return this.expiredAt < new Date();
  4964. }
  4965. async _send(...args) {
  4966. if (this.expired) throw createError({
  4967. code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
  4968. });
  4969. try {
  4970. return await super._send(...args);
  4971. } catch (error) {
  4972. throw transformNotFoundError(error);
  4973. }
  4974. }
  4975. async send(...args) {
  4976. try {
  4977. return await super.send(...args);
  4978. } catch (error) {
  4979. throw transformNotFoundError(error);
  4980. }
  4981. }
  4982. toFullJSON() {
  4983. const {
  4984. expiredAt
  4985. } = this;
  4986. return { ...super.toFullJSON(),
  4987. expiredAt: getTime(expiredAt)
  4988. };
  4989. }
  4990. toJSON() {
  4991. const {
  4992. expiredAt,
  4993. expired
  4994. } = this;
  4995. return { ...super.toJSON(),
  4996. expiredAt,
  4997. expired
  4998. };
  4999. }
  5000. }
  5001. const debug$9 = d('LC:ConversationQuery');
  5002. class ConversationQuery {
  5003. static _encode(value) {
  5004. if (value instanceof Date) {
  5005. return {
  5006. __type: 'Date',
  5007. iso: value.toJSON()
  5008. };
  5009. }
  5010. if (value instanceof RegExp) {
  5011. return value.source;
  5012. }
  5013. return value;
  5014. }
  5015. static _quote(s) {
  5016. return `\\Q${s.replace('\\E', '\\E\\\\E\\Q')}\\E`;
  5017. }
  5018. static _calculateFlag(options) {
  5019. return ['withLastMessagesRefreshed', 'compact'].reduce( // eslint-disable-next-line no-bitwise
  5020. (prev, key) => (prev << 1) + Boolean(options[key]), 0);
  5021. }
  5022. /**
  5023. * 构造一个用 AND 连接所有查询的 ConversationQuery
  5024. * @param {...ConversationQuery} queries
  5025. * @return {ConversationQuery}
  5026. */
  5027. static and(...queries) {
  5028. if (queries.length < 2) {
  5029. throw new Error('The queries must contain at least two elements');
  5030. }
  5031. if (!queries.every(q => q instanceof ConversationQuery)) {
  5032. throw new Error('The element of queries must be an instance of ConversationQuery');
  5033. }
  5034. const combined = new ConversationQuery(queries[0]._client);
  5035. combined._where.$and = queries.map(q => q._where);
  5036. return combined;
  5037. }
  5038. /**
  5039. * 构造一个用 OR 连接所有查询的 ConversationQuery
  5040. * @param {...ConversationQuery} queries
  5041. * @return {ConversationQuery}
  5042. */
  5043. static or(...queries) {
  5044. const combined = ConversationQuery.and(...queries);
  5045. combined._where.$or = combined._where.$and;
  5046. delete combined._where.$and;
  5047. return combined;
  5048. }
  5049. /**
  5050. * Create a ConversationQuery
  5051. * @param {IMClient} client
  5052. */
  5053. constructor(client) {
  5054. this._client = client;
  5055. this._where = {};
  5056. this._extraOptions = {};
  5057. }
  5058. _addCondition(key, condition, value) {
  5059. // Check if we already have a condition
  5060. if (!this._where[key]) {
  5061. this._where[key] = {};
  5062. }
  5063. this._where[key][condition] = this.constructor._encode(value);
  5064. return this;
  5065. }
  5066. toJSON() {
  5067. const json = {
  5068. where: this._where,
  5069. flag: this.constructor._calculateFlag(this._extraOptions)
  5070. };
  5071. if (typeof this._skip !== 'undefined') json.skip = this._skip;
  5072. if (typeof this._limit !== 'undefined') json.limit = this._limit;
  5073. if (typeof this._order !== 'undefined') json.sort = this._order;
  5074. debug$9(json);
  5075. return json;
  5076. }
  5077. /**
  5078. * 增加查询条件,指定聊天室的组员包含某些成员即可返回
  5079. * @param {string[]} peerIds - 成员 ID 列表
  5080. * @return {ConversationQuery} self
  5081. */
  5082. containsMembers(peerIds) {
  5083. return this.containsAll('m', peerIds);
  5084. }
  5085. /**
  5086. * 增加查询条件,指定聊天室的组员条件满足条件的才返回
  5087. *
  5088. * @param {string[]} - 成员 ID 列表
  5089. * @param {Boolean} includeSelf - 是否包含自己
  5090. * @return {ConversationQuery} self
  5091. */
  5092. withMembers(peerIds, includeSelf) {
  5093. const peerIdsSet = new Set(peerIds);
  5094. if (includeSelf) {
  5095. peerIdsSet.add(this._client.id);
  5096. }
  5097. this.sizeEqualTo('m', peerIdsSet.size);
  5098. return this.containsMembers(Array.from(peerIdsSet));
  5099. }
  5100. /**
  5101. * 增加查询条件,当 conversation 的属性中对应的字段满足等于条件时即可返回
  5102. *
  5103. * @param {string} key
  5104. * @param value
  5105. * @return {ConversationQuery} self
  5106. */
  5107. equalTo(key, value) {
  5108. this._where[key] = this.constructor._encode(value);
  5109. return this;
  5110. }
  5111. /**
  5112. * 增加查询条件,当 conversation 的属性中对应的字段满足小于条件时即可返回
  5113. * @param {string} key
  5114. * @param value
  5115. * @return {ConversationQuery} self
  5116. */
  5117. lessThan(key, value) {
  5118. return this._addCondition(key, '$lt', value);
  5119. }
  5120. /**
  5121. * 增加查询条件,当 conversation 的属性中对应的字段满足小于等于条件时即可返回
  5122. * @param {string} key
  5123. * @param value
  5124. * @return {ConversationQuery} self
  5125. */
  5126. lessThanOrEqualTo(key, value) {
  5127. return this._addCondition(key, '$lte', value);
  5128. }
  5129. /**
  5130. * 增加查询条件,当 conversation 的属性中对应的字段满足大于条件时即可返回
  5131. *
  5132. * @param {string} key
  5133. * @param value
  5134. * @return {ConversationQuery} self
  5135. */
  5136. greaterThan(key, value) {
  5137. return this._addCondition(key, '$gt', value);
  5138. }
  5139. /**
  5140. * 增加查询条件,当 conversation 的属性中对应的字段满足大于等于条件时即可返回
  5141. *
  5142. * @param {string} key
  5143. * @param value
  5144. * @return {ConversationQuery} self
  5145. */
  5146. greaterThanOrEqualTo(key, value) {
  5147. return this._addCondition(key, '$gte', value);
  5148. }
  5149. /**
  5150. * 增加查询条件,当 conversation 的属性中对应的字段满足不等于条件时即可返回
  5151. *
  5152. * @param {string} key
  5153. * @param value
  5154. * @return {ConversationQuery} self
  5155. */
  5156. notEqualTo(key, value) {
  5157. return this._addCondition(key, '$ne', value);
  5158. }
  5159. /**
  5160. * 增加查询条件,当 conversation 存在指定的字段时即可返回
  5161. *
  5162. * @since 3.5.0
  5163. * @param {string} key
  5164. * @return {ConversationQuery} self
  5165. */
  5166. exists(key) {
  5167. return this._addCondition(key, '$exists', true);
  5168. }
  5169. /**
  5170. * 增加查询条件,当 conversation 不存在指定的字段时即可返回
  5171. *
  5172. * @since 3.5.0
  5173. * @param {string} key
  5174. * @return {ConversationQuery} self
  5175. */
  5176. doesNotExist(key) {
  5177. return this._addCondition(key, '$exists', false);
  5178. }
  5179. /**
  5180. * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含在指定值中时即可返回
  5181. *
  5182. * @param {string} key
  5183. * @param values
  5184. * @return {ConversationQuery} self
  5185. */
  5186. containedIn(key, values) {
  5187. return this._addCondition(key, '$in', values);
  5188. }
  5189. /**
  5190. * 增加查询条件,当 conversation 的属性中对应的字段对应的值不包含在指定值中时即可返回
  5191. *
  5192. * @param {string} key
  5193. * @param values
  5194. * @return {ConversationQuery} self
  5195. */
  5196. notContainsIn(key, values) {
  5197. return this._addCondition(key, '$nin', values);
  5198. }
  5199. /**
  5200. * 增加查询条件,当conversation的属性中对应的字段中的元素包含所有的值才可返回
  5201. *
  5202. * @param {string} key
  5203. * @param values
  5204. * @return {ConversationQuery} self
  5205. */
  5206. containsAll(key, values) {
  5207. return this._addCondition(key, '$all', values);
  5208. }
  5209. /**
  5210. * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含此字符串即可返回
  5211. *
  5212. * @param {string} key
  5213. * @param {string} subString
  5214. * @return {ConversationQuery} self
  5215. */
  5216. contains(key, subString) {
  5217. return this._addCondition(key, '$regex', ConversationQuery._quote(subString));
  5218. }
  5219. /**
  5220. * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串起始即可返回
  5221. *
  5222. * @param {string} key
  5223. * @param {string} prefix
  5224. * @return {ConversationQuery} self
  5225. */
  5226. startsWith(key, prefix) {
  5227. return this._addCondition(key, '$regex', `^${ConversationQuery._quote(prefix)}`);
  5228. }
  5229. /**
  5230. * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串结束即可返回
  5231. *
  5232. * @param {string} key
  5233. * @param {string} suffix
  5234. * @return {ConversationQuery} self
  5235. */
  5236. endsWith(key, suffix) {
  5237. return this._addCondition(key, '$regex', `${ConversationQuery._quote(suffix)}$`);
  5238. }
  5239. /**
  5240. * 增加查询条件,当 conversation 的属性中对应的字段对应的值满足提供的正则表达式即可返回
  5241. *
  5242. * @param {string} key
  5243. * @param {RegExp} regex
  5244. * @return {ConversationQuery} self
  5245. */
  5246. matches(key, regex) {
  5247. this._addCondition(key, '$regex', regex); // Javascript regex options support mig as inline options but store them
  5248. // as properties of the object. We support mi & should migrate them to
  5249. // modifiers
  5250. let _modifiers = '';
  5251. if (regex.ignoreCase) {
  5252. _modifiers += 'i';
  5253. }
  5254. if (regex.multiline) {
  5255. _modifiers += 'm';
  5256. }
  5257. if (_modifiers && _modifiers.length) {
  5258. this._addCondition(key, '$options', _modifiers);
  5259. }
  5260. return this;
  5261. }
  5262. /**
  5263. * 添加查询约束条件,查找 key 类型是数组,该数组的长度匹配提供的数值
  5264. *
  5265. * @param {string} key
  5266. * @param {Number} length
  5267. * @return {ConversationQuery} self
  5268. */
  5269. sizeEqualTo(key, length) {
  5270. return this._addCondition(key, '$size', length);
  5271. }
  5272. /**
  5273. * 设置返回集合的大小上限
  5274. *
  5275. * @param {Number} limit - 上限
  5276. * @return {ConversationQuery} self
  5277. */
  5278. limit(limit) {
  5279. this._limit = limit;
  5280. return this;
  5281. }
  5282. /**
  5283. * 设置返回集合的起始位置,一般用于分页
  5284. *
  5285. * @param {Number} skip - 起始位置跳过几个对象
  5286. * @return {ConversationQuery} self
  5287. */
  5288. skip(skip) {
  5289. this._skip = skip;
  5290. return this;
  5291. }
  5292. /**
  5293. * 设置返回集合按照指定key进行增序排列
  5294. *
  5295. * @param {string} key
  5296. * @return {ConversationQuery} self
  5297. */
  5298. ascending(key) {
  5299. this._order = key;
  5300. return this;
  5301. }
  5302. /**
  5303. * 设置返回集合按照指定key进行增序排列,如果已设置其他排序,原排序的优先级较高
  5304. *
  5305. * @param {string} key
  5306. * @return {ConversationQuery} self
  5307. */
  5308. addAscending(key) {
  5309. if (this._order) {
  5310. this._order += `,${key}`;
  5311. } else {
  5312. this._order = key;
  5313. }
  5314. return this;
  5315. }
  5316. /**
  5317. * 设置返回集合按照指定 key 进行降序排列
  5318. *
  5319. * @param {string} key
  5320. * @return {ConversationQuery} self
  5321. */
  5322. descending(key) {
  5323. this._order = `-${key}`;
  5324. return this;
  5325. }
  5326. /**
  5327. * 设置返回集合按照指定 key 进行降序排列,如果已设置其他排序,原排序的优先级较高
  5328. *
  5329. * @param {string} key
  5330. * @return {ConversationQuery} self
  5331. */
  5332. addDescending(key) {
  5333. if (this._order) {
  5334. this._order += `,-${key}`;
  5335. } else {
  5336. this._order = `-${key}`;
  5337. }
  5338. return this;
  5339. }
  5340. /**
  5341. * 设置返回的 conversations 刷新最后一条消息
  5342. * @param {Boolean} [enabled=true]
  5343. * @return {ConversationQuery} self
  5344. */
  5345. withLastMessagesRefreshed(enabled = true) {
  5346. this._extraOptions.withLastMessagesRefreshed = enabled;
  5347. return this;
  5348. }
  5349. /**
  5350. * 设置返回的 conversations 为精简模式,即不含成员列表
  5351. * @param {Boolean} [enabled=true]
  5352. * @return {ConversationQuery} self
  5353. */
  5354. compact(enabled = true) {
  5355. this._extraOptions.compact = enabled;
  5356. return this;
  5357. }
  5358. /**
  5359. * 执行查询
  5360. * @return {Promise.<ConversationBase[]>}
  5361. */
  5362. async find() {
  5363. return this._client._executeQuery(this);
  5364. }
  5365. /**
  5366. * 返回符合条件的第一个结果
  5367. * @return {Promise.<ConversationBase>}
  5368. */
  5369. async first() {
  5370. return (await this.limit(1).find())[0];
  5371. }
  5372. }
  5373. const debug$a = d('LC:SessionManager');
  5374. class SessionManager {
  5375. constructor({
  5376. refresh,
  5377. onBeforeGetSessionToken
  5378. } = {}) {
  5379. this.refresh = refresh;
  5380. this._onBeforeGetSessionToken = onBeforeGetSessionToken;
  5381. this.setSessionToken(null, 0);
  5382. }
  5383. setSessionToken(token, ttl) {
  5384. debug$a('set session token', token, ttl);
  5385. const sessionToken = new Expirable(token, ttl * 1000);
  5386. this._sessionToken = sessionToken;
  5387. delete this._pendingSessionTokenPromise;
  5388. return sessionToken;
  5389. }
  5390. async setSessionTokenAsync(promise) {
  5391. const currentSessionToken = this._sessionToken;
  5392. this._pendingSessionTokenPromise = promise.catch(error => {
  5393. // revert, otherwise the following getSessionToken calls
  5394. // will all be rejected
  5395. this._sessionToken = currentSessionToken;
  5396. throw error;
  5397. });
  5398. return this.setSessionToken(...(await this._pendingSessionTokenPromise));
  5399. }
  5400. async getSessionToken({
  5401. autoRefresh = true
  5402. } = {}) {
  5403. debug$a('get session token');
  5404. if (this._onBeforeGetSessionToken) {
  5405. this._onBeforeGetSessionToken(this);
  5406. }
  5407. const {
  5408. value,
  5409. originalValue
  5410. } = this._sessionToken || (await this._pendingSessionTokenPromise);
  5411. if (value === Expirable.EXPIRED && autoRefresh && this.refresh) {
  5412. debug$a('refresh expired session token');
  5413. const {
  5414. value: newValue
  5415. } = await this.setSessionTokenAsync(this.refresh(this, originalValue));
  5416. debug$a('session token', newValue);
  5417. return newValue;
  5418. }
  5419. debug$a('session token', value);
  5420. return value;
  5421. }
  5422. revoke() {
  5423. if (this._sessionToken) this._sessionToken.expiredAt = -1;
  5424. }
  5425. }
  5426. var _dec$2, _dec2, _class$3;
  5427. const debug$b = d('LC:IMClient');
  5428. const {
  5429. INVITED: INVITED$1,
  5430. KICKED: KICKED$1,
  5431. MEMBERS_JOINED: MEMBERS_JOINED$1,
  5432. MEMBERS_LEFT: MEMBERS_LEFT$1,
  5433. MEMBER_INFO_UPDATED: MEMBER_INFO_UPDATED$1,
  5434. BLOCKED: BLOCKED$1,
  5435. UNBLOCKED: UNBLOCKED$1,
  5436. MEMBERS_BLOCKED: MEMBERS_BLOCKED$1,
  5437. MEMBERS_UNBLOCKED: MEMBERS_UNBLOCKED$1,
  5438. MUTED: MUTED$1,
  5439. UNMUTED: UNMUTED$1,
  5440. MEMBERS_MUTED: MEMBERS_MUTED$1,
  5441. MEMBERS_UNMUTED: MEMBERS_UNMUTED$1,
  5442. MESSAGE: MESSAGE$2,
  5443. UNREAD_MESSAGES_COUNT_UPDATE: UNREAD_MESSAGES_COUNT_UPDATE$1,
  5444. CLOSE: CLOSE$1,
  5445. CONFLICT: CONFLICT$1,
  5446. UNHANDLED_MESSAGE: UNHANDLED_MESSAGE$1,
  5447. CONVERSATION_INFO_UPDATED: CONVERSATION_INFO_UPDATED$1,
  5448. MESSAGE_RECALL: MESSAGE_RECALL$1,
  5449. MESSAGE_UPDATE: MESSAGE_UPDATE$1,
  5450. INFO_UPDATED: INFO_UPDATED$1
  5451. } = IMEvent;
  5452. const isTemporaryConversatrionId = id => /^_tmp:/.test(id);
  5453. /**
  5454. * 1 patch-msg
  5455. * 1 temp-conv-msg
  5456. * 0 auto-bind-deviceid-and-installation
  5457. * 1 transient-msg-ack
  5458. * 1 keep-notification
  5459. * 1 partial-failed-msg
  5460. * 0 group-chat-rcp
  5461. * 1 omit-peer-id
  5462. * @ignore
  5463. */
  5464. const configBitmap = 0b10111011;
  5465. let IMClient = (_dec$2 = throttle(1000), _dec2 = throttle(1000), (_class$3 = class IMClient extends EventEmitter {
  5466. /**
  5467. * 无法直接实例化,请使用 {@link Realtime#createIMClient} 创建新的 IMClient。
  5468. *
  5469. * @extends EventEmitter
  5470. */
  5471. constructor(id, options = {}, props) {
  5472. if (!(id === undefined || typeof id === 'string')) {
  5473. throw new TypeError(`Client id [${id}] is not a String`);
  5474. }
  5475. super();
  5476. Object.assign(this, {
  5477. /**
  5478. * @var id {String} 客户端 id
  5479. * @memberof IMClient#
  5480. */
  5481. id,
  5482. options
  5483. }, props);
  5484. if (!this._messageParser) {
  5485. throw new Error('IMClient must be initialized with a MessageParser');
  5486. }
  5487. this._conversationCache = new Cache(`client:${this.id}`);
  5488. this._ackMessageBuffer = {};
  5489. internal(this).lastPatchTime = Date.now();
  5490. internal(this).lastNotificationTime = undefined;
  5491. internal(this)._eventemitter = new EventEmitter();
  5492. if (debug$b.enabled) {
  5493. values(IMEvent).forEach(event => this.on(event, (...payload) => this._debug(`${event} event emitted. %o`, payload)));
  5494. } // onIMClientCreate hook
  5495. applyDecorators(this._plugins.onIMClientCreate, this);
  5496. }
  5497. _debug(...params) {
  5498. debug$b(...params, `[${this.id}]`);
  5499. }
  5500. /**
  5501. * @override
  5502. * @private
  5503. */
  5504. async _dispatchCommand(command) {
  5505. this._debug(trim(command), 'received');
  5506. if (command.serverTs && command.notificationType === 1) {
  5507. internal(this).lastNotificationTime = getTime(decodeDate(command.serverTs));
  5508. }
  5509. switch (command.cmd) {
  5510. case CommandType.conv:
  5511. return this._dispatchConvMessage(command);
  5512. case CommandType.direct:
  5513. return this._dispatchDirectMessage(command);
  5514. case CommandType.session:
  5515. return this._dispatchSessionMessage(command);
  5516. case CommandType.unread:
  5517. return this._dispatchUnreadMessage(command);
  5518. case CommandType.rcp:
  5519. return this._dispatchRcpMessage(command);
  5520. case CommandType.patch:
  5521. return this._dispatchPatchMessage(command);
  5522. default:
  5523. return this.emit(UNHANDLED_MESSAGE$1, command);
  5524. }
  5525. }
  5526. async _dispatchSessionMessage(message) {
  5527. const {
  5528. sessionMessage: {
  5529. code,
  5530. reason
  5531. }
  5532. } = message;
  5533. switch (message.op) {
  5534. case OpType.closed:
  5535. {
  5536. internal(this)._eventemitter.emit('close');
  5537. if (code === ErrorCode.SESSION_CONFLICT) {
  5538. /**
  5539. * 用户在其他客户端登录,当前客户端被服务端强行下线。详见文档「单点登录」章节。
  5540. * @event IMClient#CONFLICT
  5541. * @param {Object} payload
  5542. * @param {string} payload.reason 原因
  5543. */
  5544. return this.emit(CONFLICT$1, {
  5545. reason
  5546. });
  5547. }
  5548. /**
  5549. * 当前客户端被服务端强行下线
  5550. * @event IMClient#CLOSE
  5551. * @param {Object} payload
  5552. * @param {Number} payload.code 错误码
  5553. * @param {String} payload.reason 原因
  5554. */
  5555. return this.emit(CLOSE$1, {
  5556. code,
  5557. reason
  5558. });
  5559. }
  5560. default:
  5561. this.emit(UNHANDLED_MESSAGE$1, message);
  5562. throw new Error('Unrecognized session command');
  5563. }
  5564. }
  5565. _dispatchUnreadMessage({
  5566. unreadMessage: {
  5567. convs,
  5568. notifTime
  5569. }
  5570. }) {
  5571. internal(this).lastUnreadNotifTime = notifTime; // ensure all converstions are cached
  5572. return this.getConversations(convs.map(conv => conv.cid)).then(() => // update conversations data
  5573. Promise.all(convs.map(({
  5574. cid,
  5575. unread,
  5576. mid,
  5577. timestamp: ts,
  5578. from,
  5579. data,
  5580. binaryMsg,
  5581. patchTimestamp,
  5582. mentioned
  5583. }) => {
  5584. const conversation = this._conversationCache.get(cid); // deleted conversation
  5585. if (!conversation) return null;
  5586. let timestamp;
  5587. if (ts) {
  5588. timestamp = decodeDate(ts);
  5589. conversation.lastMessageAt = timestamp; // eslint-disable-line no-param-reassign
  5590. }
  5591. return (mid ? this._messageParser.parse(binaryMsg || data).then(message => {
  5592. const messageProps = {
  5593. id: mid,
  5594. cid,
  5595. timestamp,
  5596. updatedAt: patchTimestamp,
  5597. from
  5598. };
  5599. Object.assign(message, messageProps);
  5600. conversation.lastMessage = message; // eslint-disable-line no-param-reassign
  5601. }) : Promise.resolve()).then(() => {
  5602. conversation._setUnreadMessagesMentioned(mentioned);
  5603. const countNotUpdated = unread === internal(conversation).unreadMessagesCount;
  5604. if (countNotUpdated) return null; // to be filtered
  5605. // manipulate internal property directly to skip unreadmessagescountupdate event
  5606. internal(conversation).unreadMessagesCount = unread;
  5607. return conversation;
  5608. }); // filter conversations without unread count update
  5609. })).then(conversations => conversations.filter(conversation => conversation))).then(conversations => {
  5610. if (conversations.length) {
  5611. /**
  5612. * 未读消息数目更新
  5613. * @event IMClient#UNREAD_MESSAGES_COUNT_UPDATE
  5614. * @since 3.4.0
  5615. * @param {Conversation[]} conversations 未读消息数目有更新的对话列表
  5616. */
  5617. this.emit(UNREAD_MESSAGES_COUNT_UPDATE$1, conversations);
  5618. }
  5619. });
  5620. }
  5621. async _dispatchRcpMessage(message) {
  5622. const {
  5623. rcpMessage,
  5624. rcpMessage: {
  5625. read
  5626. }
  5627. } = message;
  5628. const conversationId = rcpMessage.cid;
  5629. const messageId = rcpMessage.id;
  5630. const timestamp = decodeDate(rcpMessage.t);
  5631. const conversation = this._conversationCache.get(conversationId); // conversation not cached means the client does not send the message
  5632. // during this session
  5633. if (!conversation) return;
  5634. conversation._handleReceipt({
  5635. messageId,
  5636. timestamp,
  5637. read
  5638. });
  5639. }
  5640. _dispatchPatchMessage({
  5641. patchMessage: {
  5642. patches
  5643. }
  5644. }) {
  5645. // ensure all converstions are cached
  5646. return this.getConversations(patches.map(patch => patch.cid)).then(() => Promise.all(patches.map(({
  5647. cid,
  5648. mid,
  5649. timestamp,
  5650. recall,
  5651. data,
  5652. patchTimestamp,
  5653. from,
  5654. binaryMsg,
  5655. mentionAll,
  5656. mentionPids,
  5657. patchCode,
  5658. patchReason
  5659. }) => {
  5660. const conversation = this._conversationCache.get(cid); // deleted conversation
  5661. if (!conversation) return null;
  5662. return this._messageParser.parse(binaryMsg || data).then(message => {
  5663. const patchTime = getTime(decodeDate(patchTimestamp));
  5664. const messageProps = {
  5665. id: mid,
  5666. cid,
  5667. timestamp,
  5668. updatedAt: patchTime,
  5669. from,
  5670. mentionList: mentionPids,
  5671. mentionedAll: mentionAll
  5672. };
  5673. Object.assign(message, messageProps);
  5674. message._setStatus(MessageStatus.SENT);
  5675. message._updateMentioned(this.id);
  5676. if (internal(this).lastPatchTime < patchTime) {
  5677. internal(this).lastPatchTime = patchTime;
  5678. } // update conversation lastMessage
  5679. if (conversation.lastMessage && conversation.lastMessage.id === mid) {
  5680. conversation.lastMessage = message; // eslint-disable-line no-param-reassign
  5681. }
  5682. let reason;
  5683. if (patchCode) {
  5684. reason = {
  5685. code: patchCode.toNumber(),
  5686. detail: patchReason
  5687. };
  5688. }
  5689. if (recall) {
  5690. /**
  5691. * 消息被撤回
  5692. * @event IMClient#MESSAGE_RECALL
  5693. * @param {AVMessage} message 被撤回的消息
  5694. * @param {ConversationBase} conversation 消息所在的会话
  5695. * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
  5696. */
  5697. this.emit(MESSAGE_RECALL$1, message, conversation, reason);
  5698. /**
  5699. * 消息被撤回
  5700. * @event ConversationBase#MESSAGE_RECALL
  5701. * @param {AVMessage} message 被撤回的消息
  5702. * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
  5703. */
  5704. conversation.emit(MESSAGE_RECALL$1, message, reason);
  5705. } else {
  5706. /**
  5707. * 消息被修改
  5708. * @event IMClient#MESSAGE_UPDATE
  5709. * @param {AVMessage} message 被修改的消息
  5710. * @param {ConversationBase} conversation 消息所在的会话
  5711. * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
  5712. */
  5713. this.emit(MESSAGE_UPDATE$1, message, conversation, reason);
  5714. /**
  5715. * 消息被修改
  5716. * @event ConversationBase#MESSAGE_UPDATE
  5717. * @param {AVMessage} message 被修改的消息
  5718. * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
  5719. */
  5720. conversation.emit(MESSAGE_UPDATE$1, message, reason);
  5721. }
  5722. });
  5723. })));
  5724. }
  5725. async _dispatchConvMessage(message) {
  5726. const {
  5727. convMessage,
  5728. convMessage: {
  5729. initBy,
  5730. m,
  5731. info,
  5732. attr
  5733. }
  5734. } = message;
  5735. const conversation = await this.getConversation(convMessage.cid);
  5736. switch (message.op) {
  5737. case OpType.joined:
  5738. {
  5739. conversation._addMembers([this.id]);
  5740. const payload = {
  5741. invitedBy: initBy
  5742. };
  5743. /**
  5744. * 当前用户被添加至某个对话
  5745. * @event IMClient#INVITED
  5746. * @param {Object} payload
  5747. * @param {String} payload.invitedBy 邀请者 id
  5748. * @param {ConversationBase} conversation
  5749. */
  5750. this.emit(INVITED$1, payload, conversation);
  5751. /**
  5752. * 当前用户被添加至当前对话
  5753. * @event ConversationBase#INVITED
  5754. * @param {Object} payload
  5755. * @param {String} payload.invitedBy 该移除操作的发起者 id
  5756. */
  5757. conversation.emit(INVITED$1, payload);
  5758. return;
  5759. }
  5760. case OpType.left:
  5761. {
  5762. conversation._removeMembers([this.id]);
  5763. const payload = {
  5764. kickedBy: initBy
  5765. };
  5766. /**
  5767. * 当前用户被从某个对话中移除
  5768. * @event IMClient#KICKED
  5769. * @param {Object} payload
  5770. * @param {String} payload.kickedBy 该移除操作的发起者 id
  5771. * @param {ConversationBase} conversation
  5772. */
  5773. this.emit(KICKED$1, payload, conversation);
  5774. /**
  5775. * 当前用户被从当前对话中移除
  5776. * @event ConversationBase#KICKED
  5777. * @param {Object} payload
  5778. * @param {String} payload.kickedBy 该移除操作的发起者 id
  5779. */
  5780. conversation.emit(KICKED$1, payload);
  5781. return;
  5782. }
  5783. case OpType.members_joined:
  5784. {
  5785. conversation._addMembers(m);
  5786. const payload = {
  5787. invitedBy: initBy,
  5788. members: m
  5789. };
  5790. /**
  5791. * 有用户被添加至某个对话
  5792. * @event IMClient#MEMBERS_JOINED
  5793. * @param {Object} payload
  5794. * @param {String[]} payload.members 被添加的用户 id 列表
  5795. * @param {String} payload.invitedBy 邀请者 id
  5796. * @param {ConversationBase} conversation
  5797. */
  5798. this.emit(MEMBERS_JOINED$1, payload, conversation);
  5799. /**
  5800. * 有成员被添加至当前对话
  5801. * @event ConversationBase#MEMBERS_JOINED
  5802. * @param {Object} payload
  5803. * @param {String[]} payload.members 被添加的成员 id 列表
  5804. * @param {String} payload.invitedBy 邀请者 id
  5805. */
  5806. conversation.emit(MEMBERS_JOINED$1, payload);
  5807. return;
  5808. }
  5809. case OpType.members_left:
  5810. {
  5811. conversation._removeMembers(m);
  5812. const payload = {
  5813. kickedBy: initBy,
  5814. members: m
  5815. };
  5816. /**
  5817. * 有成员被从某个对话中移除
  5818. * @event IMClient#MEMBERS_LEFT
  5819. * @param {Object} payload
  5820. * @param {String[]} payload.members 被移除的成员 id 列表
  5821. * @param {String} payload.kickedBy 该移除操作的发起者 id
  5822. * @param {ConversationBase} conversation
  5823. */
  5824. this.emit(MEMBERS_LEFT$1, payload, conversation);
  5825. /**
  5826. * 有成员被从当前对话中移除
  5827. * @event ConversationBase#MEMBERS_LEFT
  5828. * @param {Object} payload
  5829. * @param {String[]} payload.members 被移除的成员 id 列表
  5830. * @param {String} payload.kickedBy 该移除操作的发起者 id
  5831. */
  5832. conversation.emit(MEMBERS_LEFT$1, payload);
  5833. return;
  5834. }
  5835. case OpType.members_blocked:
  5836. {
  5837. const payload = {
  5838. blockedBy: initBy,
  5839. members: m
  5840. };
  5841. /**
  5842. * 有成员被加入某个对话的黑名单
  5843. * @event IMClient#MEMBERS_BLOCKED
  5844. * @param {Object} payload
  5845. * @param {String[]} payload.members 成员 id 列表
  5846. * @param {String} payload.blockedBy 该操作的发起者 id
  5847. * @param {ConversationBase} conversation
  5848. */
  5849. this.emit(MEMBERS_BLOCKED$1, payload, conversation);
  5850. /**
  5851. * 有成员被加入当前对话的黑名单
  5852. * @event ConversationBase#MEMBERS_BLOCKED
  5853. * @param {Object} payload
  5854. * @param {String[]} payload.members 成员 id 列表
  5855. * @param {String} payload.blockedBy 该操作的发起者 id
  5856. */
  5857. conversation.emit(MEMBERS_BLOCKED$1, payload);
  5858. return;
  5859. }
  5860. case OpType.members_unblocked:
  5861. {
  5862. const payload = {
  5863. unblockedBy: initBy,
  5864. members: m
  5865. };
  5866. /**
  5867. * 有成员被移出某个对话的黑名单
  5868. * @event IMClient#MEMBERS_UNBLOCKED
  5869. * @param {Object} payload
  5870. * @param {String[]} payload.members 成员 id 列表
  5871. * @param {String} payload.unblockedBy 该操作的发起者 id
  5872. * @param {ConversationBase} conversation
  5873. */
  5874. this.emit(MEMBERS_UNBLOCKED$1, payload, conversation);
  5875. /**
  5876. * 有成员被移出当前对话的黑名单
  5877. * @event ConversationBase#MEMBERS_UNBLOCKED
  5878. * @param {Object} payload
  5879. * @param {String[]} payload.members 成员 id 列表
  5880. * @param {String} payload.unblockedBy 该操作的发起者 id
  5881. */
  5882. conversation.emit(MEMBERS_UNBLOCKED$1, payload);
  5883. return;
  5884. }
  5885. case OpType.blocked:
  5886. {
  5887. const payload = {
  5888. blockedBy: initBy
  5889. };
  5890. /**
  5891. * 当前用户被加入某个对话的黑名单
  5892. * @event IMClient#BLOCKED
  5893. * @param {Object} payload
  5894. * @param {String} payload.blockedBy 该操作的发起者 id
  5895. * @param {ConversationBase} conversation
  5896. */
  5897. this.emit(BLOCKED$1, payload, conversation);
  5898. /**
  5899. * 当前用户被加入当前对话的黑名单
  5900. * @event ConversationBase#BLOCKED
  5901. * @param {Object} payload
  5902. * @param {String} payload.blockedBy 该操作的发起者 id
  5903. */
  5904. conversation.emit(BLOCKED$1, payload);
  5905. return;
  5906. }
  5907. case OpType.unblocked:
  5908. {
  5909. const payload = {
  5910. unblockedBy: initBy
  5911. };
  5912. /**
  5913. * 当前用户被移出某个对话的黑名单
  5914. * @event IMClient#UNBLOCKED
  5915. * @param {Object} payload
  5916. * @param {String} payload.unblockedBy 该操作的发起者 id
  5917. * @param {ConversationBase} conversation
  5918. */
  5919. this.emit(UNBLOCKED$1, payload, conversation);
  5920. /**
  5921. * 当前用户被移出当前对话的黑名单
  5922. * @event ConversationBase#UNBLOCKED
  5923. * @param {Object} payload
  5924. * @param {String} payload.unblockedBy 该操作的发起者 id
  5925. */
  5926. conversation.emit(UNBLOCKED$1, payload);
  5927. return;
  5928. }
  5929. case OpType.members_shutuped:
  5930. {
  5931. const payload = {
  5932. mutedBy: initBy,
  5933. members: m
  5934. };
  5935. /**
  5936. * 有成员在某个对话中被禁言
  5937. * @event IMClient#MEMBERS_MUTED
  5938. * @param {Object} payload
  5939. * @param {String[]} payload.members 成员 id 列表
  5940. * @param {String} payload.mutedBy 该操作的发起者 id
  5941. * @param {ConversationBase} conversation
  5942. */
  5943. this.emit(MEMBERS_MUTED$1, payload, conversation);
  5944. /**
  5945. * 有成员在当前对话中被禁言
  5946. * @event ConversationBase#MEMBERS_MUTED
  5947. * @param {Object} payload
  5948. * @param {String[]} payload.members 成员 id 列表
  5949. * @param {String} payload.mutedBy 该操作的发起者 id
  5950. */
  5951. conversation.emit(MEMBERS_MUTED$1, payload);
  5952. return;
  5953. }
  5954. case OpType.members_unshutuped:
  5955. {
  5956. const payload = {
  5957. unmutedBy: initBy,
  5958. members: m
  5959. };
  5960. /**
  5961. * 有成员在某个对话中被解除禁言
  5962. * @event IMClient#MEMBERS_UNMUTED
  5963. * @param {Object} payload
  5964. * @param {String[]} payload.members 成员 id 列表
  5965. * @param {String} payload.unmutedBy 该操作的发起者 id
  5966. * @param {ConversationBase} conversation
  5967. */
  5968. this.emit(MEMBERS_UNMUTED$1, payload, conversation);
  5969. /**
  5970. * 有成员在当前对话中被解除禁言
  5971. * @event ConversationBase#MEMBERS_UNMUTED
  5972. * @param {Object} payload
  5973. * @param {String[]} payload.members 成员 id 列表
  5974. * @param {String} payload.unmutedBy 该操作的发起者 id
  5975. */
  5976. conversation.emit(MEMBERS_UNMUTED$1, payload);
  5977. return;
  5978. }
  5979. case OpType.shutuped:
  5980. {
  5981. const payload = {
  5982. mutedBy: initBy
  5983. };
  5984. /**
  5985. * 有成员在某个对话中被禁言
  5986. * @event IMClient#MUTED
  5987. * @param {Object} payload
  5988. * @param {String} payload.mutedBy 该操作的发起者 id
  5989. * @param {ConversationBase} conversation
  5990. */
  5991. this.emit(MUTED$1, payload, conversation);
  5992. /**
  5993. * 有成员在当前对话中被禁言
  5994. * @event ConversationBase#MUTED
  5995. * @param {Object} payload
  5996. * @param {String} payload.mutedBy 该操作的发起者 id
  5997. */
  5998. conversation.emit(MUTED$1, payload);
  5999. return;
  6000. }
  6001. case OpType.unshutuped:
  6002. {
  6003. const payload = {
  6004. unmutedBy: initBy
  6005. };
  6006. /**
  6007. * 有成员在某个对话中被解除禁言
  6008. * @event IMClient#UNMUTED
  6009. * @param {Object} payload
  6010. * @param {String} payload.unmutedBy 该操作的发起者 id
  6011. * @param {ConversationBase} conversation
  6012. */
  6013. this.emit(UNMUTED$1, payload, conversation);
  6014. /**
  6015. * 有成员在当前对话中被解除禁言
  6016. * @event ConversationBase#UNMUTED
  6017. * @param {Object} payload
  6018. * @param {String} payload.unmutedBy 该操作的发起者 id
  6019. */
  6020. conversation.emit(UNMUTED$1, payload);
  6021. return;
  6022. }
  6023. case OpType.member_info_changed:
  6024. {
  6025. const {
  6026. pid,
  6027. role
  6028. } = info;
  6029. const {
  6030. memberInfoMap
  6031. } = internal(conversation); // 如果不存在缓存,且不是 role 的更新,则不通知
  6032. if (!memberInfoMap && !role) return;
  6033. const memberInfo = await conversation.getMemberInfo(pid);
  6034. internal(memberInfo).role = role;
  6035. const payload = {
  6036. member: pid,
  6037. memberInfo,
  6038. updatedBy: initBy
  6039. };
  6040. /**
  6041. * 有成员的对话信息被更新
  6042. * @event IMClient#MEMBER_INFO_UPDATED
  6043. * @param {Object} payload
  6044. * @param {String} payload.member 被更新对话信息的成员 id
  6045. * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
  6046. * @param {String} payload.updatedBy 该操作的发起者 id
  6047. * @param {ConversationBase} conversation
  6048. */
  6049. this.emit(MEMBER_INFO_UPDATED$1, payload, conversation);
  6050. /**
  6051. * 有成员的对话信息被更新
  6052. * @event ConversationBase#MEMBER_INFO_UPDATED
  6053. * @param {Object} payload
  6054. * @param {String} payload.member 被更新对话信息的成员 id
  6055. * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
  6056. * @param {String} payload.updatedBy 该操作的发起者 id
  6057. */
  6058. conversation.emit(MEMBER_INFO_UPDATED$1, payload);
  6059. return;
  6060. }
  6061. case OpType.updated:
  6062. {
  6063. const attributes = decode(JSON.parse(attr.data));
  6064. conversation._updateServerAttributes(attributes);
  6065. const payload = {
  6066. attributes,
  6067. updatedBy: initBy
  6068. };
  6069. /**
  6070. * 该对话信息被更新
  6071. * @event IMClient#CONVERSATION_INFO_UPDATED
  6072. * @param {Object} payload
  6073. * @param {Object} payload.attributes 被更新的属性
  6074. * @param {String} payload.updatedBy 该操作的发起者 id
  6075. * @param {ConversationBase} conversation
  6076. */
  6077. this.emit(CONVERSATION_INFO_UPDATED$1, payload, conversation);
  6078. /**
  6079. * 有对话信息被更新
  6080. * @event ConversationBase#INFO_UPDATED
  6081. * @param {Object} payload
  6082. * @param {Object} payload.attributes 被更新的属性
  6083. * @param {String} payload.updatedBy 该操作的发起者 id
  6084. */
  6085. conversation.emit(INFO_UPDATED$1, payload);
  6086. return;
  6087. }
  6088. default:
  6089. this.emit(UNHANDLED_MESSAGE$1, message);
  6090. throw new Error('Unrecognized conversation command');
  6091. }
  6092. }
  6093. _dispatchDirectMessage(originalMessage) {
  6094. const {
  6095. directMessage,
  6096. directMessage: {
  6097. id,
  6098. cid,
  6099. fromPeerId,
  6100. timestamp,
  6101. transient,
  6102. patchTimestamp,
  6103. mentionPids,
  6104. mentionAll,
  6105. binaryMsg,
  6106. msg
  6107. }
  6108. } = originalMessage;
  6109. const content = binaryMsg ? binaryMsg.toArrayBuffer() : msg;
  6110. return Promise.all([this.getConversation(directMessage.cid), this._messageParser.parse(content)]).then(([conversation, message]) => {
  6111. // deleted conversation
  6112. if (!conversation) return undefined;
  6113. const messageProps = {
  6114. id,
  6115. cid,
  6116. timestamp,
  6117. updatedAt: patchTimestamp,
  6118. from: fromPeerId,
  6119. mentionList: mentionPids,
  6120. mentionedAll: mentionAll
  6121. };
  6122. Object.assign(message, messageProps);
  6123. message._updateMentioned(this.id);
  6124. message._setStatus(MessageStatus.SENT); // filter outgoing message sent from another device
  6125. if (message.from !== this.id) {
  6126. if (!(transient || conversation.transient)) {
  6127. this._sendAck(message);
  6128. }
  6129. }
  6130. return this._dispatchParsedMessage(message, conversation);
  6131. });
  6132. }
  6133. _dispatchParsedMessage(message, conversation) {
  6134. // beforeMessageDispatch hook
  6135. return applyDispatcher(this._plugins.beforeMessageDispatch, [message, conversation]).then(shouldDispatch => {
  6136. if (shouldDispatch === false) return;
  6137. conversation.lastMessage = message; // eslint-disable-line no-param-reassign
  6138. conversation.lastMessageAt = message.timestamp; // eslint-disable-line no-param-reassign
  6139. // filter outgoing message sent from another device
  6140. if (message.from !== this.id) {
  6141. conversation.unreadMessagesCount += 1; // eslint-disable-line no-param-reassign
  6142. if (message.mentioned) conversation._setUnreadMessagesMentioned(true);
  6143. }
  6144. /**
  6145. * 当前用户收到消息
  6146. * @event IMClient#MESSAGE
  6147. * @param {Message} message
  6148. * @param {ConversationBase} conversation 收到消息的对话
  6149. */
  6150. this.emit(MESSAGE$2, message, conversation);
  6151. /**
  6152. * 当前对话收到消息
  6153. * @event ConversationBase#MESSAGE
  6154. * @param {Message} message
  6155. */
  6156. conversation.emit(MESSAGE$2, message);
  6157. });
  6158. }
  6159. _sendAck(message) {
  6160. this._debug('send ack for %O', message);
  6161. const {
  6162. cid
  6163. } = message;
  6164. if (!cid) {
  6165. throw new Error('missing cid');
  6166. }
  6167. if (!this._ackMessageBuffer[cid]) {
  6168. this._ackMessageBuffer[cid] = [];
  6169. }
  6170. this._ackMessageBuffer[cid].push(message);
  6171. return this._doSendAck();
  6172. } // jsdoc-ignore-start
  6173. // jsdoc-ignore-end
  6174. _doSendAck() {
  6175. // if not connected, just skip everything
  6176. if (!this._connection.is('connected')) return;
  6177. this._debug('do send ack %O', this._ackMessageBuffer);
  6178. Promise.all(Object.keys(this._ackMessageBuffer).map(cid => {
  6179. const convAckMessages = this._ackMessageBuffer[cid];
  6180. const timestamps = convAckMessages.map(message => message.timestamp);
  6181. const command = new GenericCommand({
  6182. cmd: 'ack',
  6183. ackMessage: new AckCommand({
  6184. cid,
  6185. fromts: Math.min.apply(null, timestamps),
  6186. tots: Math.max.apply(null, timestamps)
  6187. })
  6188. });
  6189. delete this._ackMessageBuffer[cid];
  6190. return this._send(command, false).catch(error => {
  6191. this._debug('send ack failed: %O', error);
  6192. this._ackMessageBuffer[cid] = convAckMessages;
  6193. });
  6194. }));
  6195. }
  6196. _omitPeerId(value) {
  6197. internal(this).peerIdOmittable = value;
  6198. }
  6199. _send(cmd, ...args) {
  6200. const command = cmd;
  6201. if (!internal(this).peerIdOmittable && this.id) {
  6202. command.peerId = this.id;
  6203. }
  6204. return this._connection.send(command, ...args);
  6205. }
  6206. async _open(appId, tag, deviceId, isReconnect = false) {
  6207. this._debug('open session');
  6208. const {
  6209. lastUnreadNotifTime,
  6210. lastPatchTime,
  6211. lastNotificationTime
  6212. } = internal(this);
  6213. const command = new GenericCommand({
  6214. cmd: 'session',
  6215. op: 'open',
  6216. appId,
  6217. peerId: this.id,
  6218. sessionMessage: new SessionCommand({
  6219. ua: `js/${version}`,
  6220. r: isReconnect,
  6221. lastUnreadNotifTime,
  6222. lastPatchTime,
  6223. configBitmap
  6224. })
  6225. });
  6226. if (!isReconnect) {
  6227. Object.assign(command.sessionMessage, trim({
  6228. tag,
  6229. deviceId
  6230. }));
  6231. if (this.options.signatureFactory) {
  6232. const signatureResult = await runSignatureFactory(this.options.signatureFactory, [this._identity]);
  6233. Object.assign(command.sessionMessage, keyRemap({
  6234. signature: 's',
  6235. timestamp: 't',
  6236. nonce: 'n'
  6237. }, signatureResult));
  6238. }
  6239. } else {
  6240. const sessionToken = await this._sessionManager.getSessionToken({
  6241. autoRefresh: false
  6242. });
  6243. if (sessionToken && sessionToken !== Expirable.EXPIRED) {
  6244. Object.assign(command.sessionMessage, {
  6245. st: sessionToken
  6246. });
  6247. }
  6248. }
  6249. let resCommand;
  6250. try {
  6251. resCommand = await this._send(command);
  6252. } catch (error) {
  6253. if (error.code === ErrorCode.SESSION_TOKEN_EXPIRED) {
  6254. if (!this._sessionManager) {
  6255. // let it fail if sessoinToken not cached but command rejected as token expired
  6256. // to prevent session openning flood
  6257. throw new Error('Unexpected session expiration');
  6258. }
  6259. debug$b('Session token expired, reopening');
  6260. this._sessionManager.revoke();
  6261. return this._open(appId, tag, deviceId, isReconnect);
  6262. }
  6263. throw error;
  6264. }
  6265. const {
  6266. peerId,
  6267. sessionMessage,
  6268. sessionMessage: {
  6269. st: token,
  6270. stTtl: tokenTTL,
  6271. code
  6272. },
  6273. serverTs
  6274. } = resCommand;
  6275. if (code) {
  6276. throw createError(sessionMessage);
  6277. }
  6278. if (peerId) {
  6279. this.id = peerId;
  6280. if (!this._identity) this._identity = peerId;
  6281. if (token) {
  6282. this._sessionManager = this._sessionManager || this._createSessionManager();
  6283. this._sessionManager.setSessionToken(token, tokenTTL);
  6284. }
  6285. const serverTime = getTime(decodeDate(serverTs));
  6286. if (serverTs) {
  6287. internal(this).lastPatchTime = serverTime;
  6288. }
  6289. if (lastNotificationTime) {
  6290. // Do not await for it as this is failable
  6291. this._syncNotifications(lastNotificationTime).catch(error => console.warn('Syncing notifications failed:', error));
  6292. } else {
  6293. // Set timestamp to now for next reconnection
  6294. internal(this).lastNotificationTime = serverTime;
  6295. }
  6296. } else {
  6297. console.warn('Unexpected session opened without peerId.');
  6298. }
  6299. return undefined;
  6300. }
  6301. async _syncNotifications(timestamp) {
  6302. const {
  6303. hasMore,
  6304. notifications
  6305. } = await this._fetchNotifications(timestamp);
  6306. notifications.forEach(notification => {
  6307. const {
  6308. cmd,
  6309. op,
  6310. serverTs,
  6311. notificationType,
  6312. ...payload
  6313. } = notification;
  6314. this._dispatchCommand({
  6315. cmd: CommandType[cmd],
  6316. op: OpType[op],
  6317. serverTs,
  6318. notificationType,
  6319. [`${cmd}Message`]: payload
  6320. });
  6321. });
  6322. if (hasMore) {
  6323. return this._syncNotifications(internal(this).lastNotificationTime);
  6324. }
  6325. return undefined;
  6326. }
  6327. async _fetchNotifications(timestamp) {
  6328. return this._requestWithSessionToken({
  6329. method: 'GET',
  6330. path: '/rtm/notifications',
  6331. query: {
  6332. start_ts: timestamp,
  6333. notification_type: 'permanent'
  6334. }
  6335. });
  6336. }
  6337. _createSessionManager() {
  6338. debug$b('create SessionManager');
  6339. return new SessionManager({
  6340. onBeforeGetSessionToken: this._connection.checkConnectionAvailability.bind(this._connection),
  6341. refresh: (manager, expiredSessionToken) => manager.setSessionTokenAsync(Promise.resolve(new GenericCommand({
  6342. cmd: 'session',
  6343. op: 'refresh',
  6344. sessionMessage: new SessionCommand({
  6345. ua: `js/${version}`,
  6346. st: expiredSessionToken
  6347. })
  6348. })).then(async command => {
  6349. if (this.options.signatureFactory) {
  6350. const signatureResult = await runSignatureFactory(this.options.signatureFactory, [this._identity]);
  6351. Object.assign(command.sessionMessage, keyRemap({
  6352. signature: 's',
  6353. timestamp: 't',
  6354. nonce: 'n'
  6355. }, signatureResult));
  6356. }
  6357. return command;
  6358. }).then(this._send.bind(this)).then(({
  6359. sessionMessage: {
  6360. st: token,
  6361. stTtl: ttl
  6362. }
  6363. }) => [token, ttl]))
  6364. });
  6365. }
  6366. async _requestWithSessionToken({
  6367. headers,
  6368. query,
  6369. ...params
  6370. }) {
  6371. const sessionToken = await this._sessionManager.getSessionToken();
  6372. return this._request({
  6373. headers: {
  6374. 'X-LC-IM-Session-Token': sessionToken,
  6375. ...headers
  6376. },
  6377. query: {
  6378. client_id: this.id,
  6379. ...query
  6380. },
  6381. ...params
  6382. });
  6383. }
  6384. /**
  6385. * 关闭客户端
  6386. * @return {Promise}
  6387. */
  6388. async close() {
  6389. this._debug('close session');
  6390. const _ee = internal(this)._eventemitter;
  6391. _ee.emit('beforeclose');
  6392. if (this._connection.is('connected')) {
  6393. const command = new GenericCommand({
  6394. cmd: 'session',
  6395. op: 'close'
  6396. });
  6397. await this._send(command);
  6398. }
  6399. _ee.emit('close');
  6400. this.emit(CLOSE$1, {
  6401. code: 0
  6402. });
  6403. }
  6404. /**
  6405. * 获取 client 列表中在线的 client,每次查询最多 20 个 clientId,超出部分会被忽略
  6406. * @param {String[]} clientIds 要查询的 client ids
  6407. * @return {Primse.<String[]>} 在线的 client ids
  6408. */
  6409. async ping(clientIds) {
  6410. this._debug('ping');
  6411. if (!(clientIds instanceof Array)) {
  6412. throw new TypeError(`clientIds ${clientIds} is not an Array`);
  6413. }
  6414. if (!clientIds.length) {
  6415. return Promise.resolve([]);
  6416. }
  6417. const command = new GenericCommand({
  6418. cmd: 'session',
  6419. op: 'query',
  6420. sessionMessage: new SessionCommand({
  6421. sessionPeerIds: clientIds
  6422. })
  6423. });
  6424. const resCommand = await this._send(command);
  6425. return resCommand.sessionMessage.onlineSessionPeerIds;
  6426. }
  6427. /**
  6428. * 获取某个特定的对话
  6429. * @param {String} id 对话 id,对应 _Conversation 表中的 objectId
  6430. * @param {Boolean} [noCache=false] 强制不从缓存中获取
  6431. * @return {Promise.<ConversationBase>} 如果 id 对应的对话不存在则返回 null
  6432. */
  6433. async getConversation(id, noCache = false) {
  6434. if (typeof id !== 'string') {
  6435. throw new TypeError(`${id} is not a String`);
  6436. }
  6437. if (!noCache) {
  6438. const cachedConversation = this._conversationCache.get(id);
  6439. if (cachedConversation) {
  6440. return cachedConversation;
  6441. }
  6442. }
  6443. if (isTemporaryConversatrionId(id)) {
  6444. return (await this._getTemporaryConversations([id]))[0] || null;
  6445. }
  6446. return this.getQuery().equalTo('objectId', id).find().then(conversations => conversations[0] || null);
  6447. }
  6448. /**
  6449. * 通过 id 批量获取某个特定的对话
  6450. * @since 3.4.0
  6451. * @param {String[]} ids 对话 id 列表,对应 _Conversation 表中的 objectId
  6452. * @param {Boolean} [noCache=false] 强制不从缓存中获取
  6453. * @return {Promise.<ConversationBase[]>} 如果 id 对应的对话不存在则返回 null
  6454. */
  6455. async getConversations(ids, noCache = false) {
  6456. const remoteConversationIds = noCache ? ids : ids.filter(id => this._conversationCache.get(id) === null);
  6457. if (remoteConversationIds.length) {
  6458. const remoteTemporaryConversationIds = remove(remoteConversationIds, isTemporaryConversatrionId);
  6459. const query = [];
  6460. if (remoteConversationIds.length) {
  6461. query.push(this.getQuery().containedIn('objectId', remoteConversationIds).limit(999).find());
  6462. }
  6463. if (remoteTemporaryConversationIds.length) {
  6464. const remoteTemporaryConversationsPromise = remoteTemporaryConversationIds.map(this._getTemporaryConversations.bind(this));
  6465. query.push(...remoteTemporaryConversationsPromise);
  6466. }
  6467. await Promise.all(query);
  6468. }
  6469. return ids.map(id => this._conversationCache.get(id));
  6470. }
  6471. async _getTemporaryConversations(ids) {
  6472. const command = new GenericCommand({
  6473. cmd: 'conv',
  6474. op: 'query',
  6475. convMessage: new ConvCommand({
  6476. tempConvIds: ids
  6477. })
  6478. });
  6479. const resCommand = await this._send(command);
  6480. return this._handleQueryResults(resCommand);
  6481. }
  6482. /**
  6483. * 构造一个 ConversationQuery 来查询对话
  6484. * @return {ConversationQuery.<PersistentConversation>}
  6485. */
  6486. getQuery() {
  6487. return new ConversationQuery(this);
  6488. }
  6489. /**
  6490. * 构造一个 ConversationQuery 来查询聊天室
  6491. * @return {ConversationQuery.<ChatRoom>}
  6492. */
  6493. getChatRoomQuery() {
  6494. return this.getQuery().equalTo('tr', true);
  6495. }
  6496. /**
  6497. * 构造一个 ConversationQuery 来查询服务号
  6498. * @return {ConversationQuery.<ServiceConversation>}
  6499. */
  6500. getServiceConversationQuery() {
  6501. return this.getQuery().equalTo('sys', true);
  6502. }
  6503. async _executeQuery(query) {
  6504. const queryJSON = query.toJSON();
  6505. queryJSON.where = new JsonObjectMessage({
  6506. data: JSON.stringify(encode(queryJSON.where))
  6507. });
  6508. const command = new GenericCommand({
  6509. cmd: 'conv',
  6510. op: 'query',
  6511. convMessage: new ConvCommand(queryJSON)
  6512. });
  6513. const resCommand = await this._send(command);
  6514. return this._handleQueryResults(resCommand);
  6515. }
  6516. async _handleQueryResults(resCommand) {
  6517. let conversations;
  6518. try {
  6519. conversations = decode(JSON.parse(resCommand.convMessage.results.data));
  6520. } catch (error) {
  6521. const commandString = JSON.stringify(trim(resCommand));
  6522. throw new Error(`Parse query result failed: ${error.message}. Command: ${commandString}`);
  6523. }
  6524. conversations = await Promise.all(conversations.map(this._parseConversationFromRawData.bind(this)));
  6525. return conversations.map(this._upsertConversationToCache.bind(this));
  6526. }
  6527. _upsertConversationToCache(fetchedConversation) {
  6528. let conversation = this._conversationCache.get(fetchedConversation.id);
  6529. if (!conversation) {
  6530. conversation = fetchedConversation;
  6531. this._debug('no match, set cache');
  6532. this._conversationCache.set(fetchedConversation.id, fetchedConversation);
  6533. } else {
  6534. this._debug('update cached conversation');
  6535. ['creator', 'createdAt', 'updatedAt', 'lastMessageAt', 'lastMessage', 'mutedMembers', 'members', '_attributes', 'transient', 'muted'].forEach(key => {
  6536. const value = fetchedConversation[key];
  6537. if (value !== undefined) conversation[key] = value;
  6538. });
  6539. if (conversation._reset) conversation._reset();
  6540. }
  6541. return conversation;
  6542. }
  6543. /**
  6544. * 反序列化消息,与 {@link Message#toFullJSON} 相对。
  6545. * @param {Object}
  6546. * @return {AVMessage} 解析后的消息
  6547. * @since 4.0.0
  6548. */
  6549. async parseMessage({
  6550. data,
  6551. bin = false,
  6552. ...properties
  6553. }) {
  6554. const content = bin ? base64Arraybuffer.decode(data) : data;
  6555. const message = await this._messageParser.parse(content);
  6556. Object.assign(message, properties);
  6557. message._updateMentioned(this.id);
  6558. return message;
  6559. }
  6560. /**
  6561. * 反序列化对话,与 {@link Conversation#toFullJSON} 相对。
  6562. * @param {Object}
  6563. * @return {ConversationBase} 解析后的对话
  6564. * @since 4.0.0
  6565. */
  6566. async parseConversation({
  6567. id,
  6568. lastMessageAt,
  6569. lastMessage,
  6570. lastDeliveredAt,
  6571. lastReadAt,
  6572. unreadMessagesCount,
  6573. members,
  6574. mentioned,
  6575. ...properties
  6576. }) {
  6577. const conversationData = {
  6578. id,
  6579. lastMessageAt,
  6580. lastMessage,
  6581. lastDeliveredAt,
  6582. lastReadAt,
  6583. unreadMessagesCount,
  6584. members,
  6585. mentioned
  6586. };
  6587. if (lastMessage) {
  6588. conversationData.lastMessage = await this.parseMessage(lastMessage);
  6589. conversationData.lastMessage._setStatus(MessageStatus.SENT);
  6590. }
  6591. const {
  6592. transient,
  6593. system,
  6594. expiredAt
  6595. } = properties;
  6596. if (transient) return new ChatRoom(conversationData, properties, this);
  6597. if (system) return new ServiceConversation(conversationData, properties, this);
  6598. if (expiredAt || isTemporaryConversatrionId(id)) {
  6599. return new TemporaryConversation(conversationData, {
  6600. expiredAt
  6601. }, this);
  6602. }
  6603. return new Conversation(conversationData, properties, this);
  6604. }
  6605. async _parseConversationFromRawData(rawData) {
  6606. const data = keyRemap({
  6607. objectId: 'id',
  6608. lm: 'lastMessageAt',
  6609. m: 'members',
  6610. tr: 'transient',
  6611. sys: 'system',
  6612. c: 'creator',
  6613. mu: 'mutedMembers'
  6614. }, rawData);
  6615. if (data.msg) {
  6616. data.lastMessage = {
  6617. data: data.msg,
  6618. bin: data.bin,
  6619. from: data.msg_from,
  6620. id: data.msg_mid,
  6621. timestamp: data.msg_timestamp,
  6622. updatedAt: data.patch_timestamp
  6623. };
  6624. delete data.lastMessageFrom;
  6625. delete data.lastMessageId;
  6626. delete data.lastMessageTimestamp;
  6627. delete data.lastMessagePatchTimestamp;
  6628. }
  6629. const {
  6630. ttl
  6631. } = data;
  6632. if (ttl) data.expiredAt = Date.now() + ttl * 1000;
  6633. return this.parseConversation(data);
  6634. }
  6635. /**
  6636. * 创建一个对话
  6637. * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
  6638. * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
  6639. * @param {String} [options.name] 对话的名字
  6640. * @param {Boolean} [options.unique=true] 唯一对话,当其为 true 时,如果当前已经有相同成员的对话存在则返回该对话,否则会创建新的对话
  6641. * @return {Promise.<Conversation>}
  6642. */
  6643. async createConversation({
  6644. members: m,
  6645. name,
  6646. transient,
  6647. unique = true,
  6648. _tempConv: tempConv,
  6649. _tempConvTTL: tempConvTTL,
  6650. ...properties
  6651. } = {}) {
  6652. if (!(transient || Array.isArray(m))) {
  6653. throw new TypeError(`conversation members ${m} is not an array`);
  6654. }
  6655. let members = new Set(m);
  6656. members.add(this.id);
  6657. members = Array.from(members).sort();
  6658. let attr = properties || {};
  6659. if (name) {
  6660. if (typeof name !== 'string') {
  6661. throw new TypeError(`conversation name ${name} is not a string`);
  6662. }
  6663. attr.name = name;
  6664. }
  6665. attr = new JsonObjectMessage({
  6666. data: JSON.stringify(encode(attr))
  6667. });
  6668. const startCommandJson = {
  6669. m: members,
  6670. attr,
  6671. transient,
  6672. unique,
  6673. tempConv,
  6674. tempConvTTL
  6675. };
  6676. const command = new GenericCommand({
  6677. cmd: 'conv',
  6678. op: 'start',
  6679. convMessage: new ConvCommand(startCommandJson)
  6680. });
  6681. if (this.options.conversationSignatureFactory) {
  6682. const params = [null, this._identity, members, 'create'];
  6683. const signatureResult = await runSignatureFactory(this.options.conversationSignatureFactory, params);
  6684. Object.assign(command.convMessage, keyRemap({
  6685. signature: 's',
  6686. timestamp: 't',
  6687. nonce: 'n'
  6688. }, signatureResult));
  6689. }
  6690. const {
  6691. convMessage: {
  6692. cid,
  6693. cdate,
  6694. tempConvTTL: ttl
  6695. }
  6696. } = await this._send(command);
  6697. const data = {
  6698. name,
  6699. transient,
  6700. unique,
  6701. id: cid,
  6702. createdAt: cdate,
  6703. updatedAt: cdate,
  6704. lastMessageAt: null,
  6705. creator: this.id,
  6706. members: transient ? [] : members,
  6707. ...properties
  6708. };
  6709. if (ttl) data.expiredAt = Date.now() + ttl * 1000;
  6710. const conversation = await this.parseConversation(data);
  6711. return this._upsertConversationToCache(conversation);
  6712. }
  6713. /**
  6714. * 创建一个聊天室
  6715. * @since 4.0.0
  6716. * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
  6717. * @param {String} [options.name] 对话的名字
  6718. * @return {Promise.<ChatRoom>}
  6719. */
  6720. async createChatRoom(param) {
  6721. return this.createConversation({ ...param,
  6722. transient: true,
  6723. members: null,
  6724. unique: false,
  6725. _tempConv: false
  6726. });
  6727. }
  6728. /**
  6729. * 创建一个临时对话
  6730. * @since 4.0.0
  6731. * @param {Object} options
  6732. * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
  6733. * @param {String} [options.ttl] 对话存在时间,单位为秒,最大值与默认值均为 86400(一天),过期后该对话不再可用。
  6734. * @return {Promise.<TemporaryConversation>}
  6735. */
  6736. async createTemporaryConversation({
  6737. ttl: _tempConvTTL,
  6738. ...param
  6739. }) {
  6740. return this.createConversation({ ...param,
  6741. _tempConv: true,
  6742. _tempConvTTL
  6743. });
  6744. } // jsdoc-ignore-start
  6745. // jsdoc-ignore-end
  6746. _doSendRead() {
  6747. // if not connected, just skip everything
  6748. if (!this._connection.is('connected')) return;
  6749. const buffer = internal(this).readConversationsBuffer;
  6750. const conversations = Array.from(buffer);
  6751. if (!conversations.length) return;
  6752. const ids = conversations.map(conversation => {
  6753. if (!(conversation instanceof ConversationBase)) {
  6754. throw new TypeError(`${conversation} is not a Conversation`);
  6755. }
  6756. return conversation.id;
  6757. });
  6758. this._debug(`mark [${ids}] as read`);
  6759. buffer.clear();
  6760. this._sendReadCommand(conversations).catch(error => {
  6761. this._debug('send read failed: %O', error);
  6762. conversations.forEach(buffer.add.bind(buffer));
  6763. });
  6764. }
  6765. _sendReadCommand(conversations) {
  6766. return this._send(new GenericCommand({
  6767. cmd: 'read',
  6768. readMessage: new ReadCommand({
  6769. convs: conversations.map(conversation => new ReadTuple({
  6770. cid: conversation.id,
  6771. mid: conversation.lastMessage && conversation.lastMessage.from !== this.id ? conversation.lastMessage.id : undefined,
  6772. timestamp: (conversation.lastMessageAt || new Date()).getTime()
  6773. }))
  6774. })
  6775. }), false);
  6776. }
  6777. }, (_applyDecoratedDescriptor(_class$3.prototype, "_doSendAck", [_dec$2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendAck"), _class$3.prototype), _applyDecoratedDescriptor(_class$3.prototype, "_doSendRead", [_dec2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendRead"), _class$3.prototype)), _class$3));
  6778. /**
  6779. * 修改、撤回消息的原因
  6780. * @typedef PatchReason
  6781. * @type {Object}
  6782. * @property {number} code 负数为内置 code,正数为开发者在 hook 中自定义的 code。比如因为敏感词过滤被修改的 code 为 -4408。
  6783. * @property {string} [detail] 具体的原因说明。
  6784. */
  6785. const RECONNECT_ERROR = 'reconnecterror';
  6786. var CoreEvent = /*#__PURE__*/Object.freeze({
  6787. __proto__: null,
  6788. RECONNECT_ERROR: RECONNECT_ERROR,
  6789. DISCONNECT: DISCONNECT,
  6790. RECONNECT: RECONNECT,
  6791. RETRY: RETRY,
  6792. SCHEDULE: SCHEDULE,
  6793. OFFLINE: OFFLINE,
  6794. ONLINE: ONLINE
  6795. });
  6796. var _class$4;
  6797. let // jsdoc-ignore-end
  6798. BinaryMessage = IE10Compatible(_class$4 = class BinaryMessage extends Message {
  6799. /**
  6800. * 二进制消息
  6801. * @extends Message
  6802. * @param {ArrayBuffer} buffer
  6803. * @since 4.0.0
  6804. */
  6805. constructor(buffer) {
  6806. if (!(buffer instanceof ArrayBuffer)) {
  6807. throw new TypeError(`${buffer} is not an ArrayBuffer`);
  6808. }
  6809. super(buffer);
  6810. }
  6811. /**
  6812. * @type ArrayBuffer
  6813. */
  6814. get buffer() {
  6815. return this.content;
  6816. }
  6817. set buffer(buffer) {
  6818. this.content = buffer;
  6819. }
  6820. static validate(target) {
  6821. return target instanceof ArrayBuffer;
  6822. }
  6823. toJSON() {
  6824. return { ...super._toJSON(),
  6825. data: base64Arraybuffer.encode(this.content)
  6826. };
  6827. }
  6828. toFullJSON() {
  6829. return { ...super.toFullJSON(),
  6830. bin: true,
  6831. data: base64Arraybuffer.encode(this.content)
  6832. };
  6833. }
  6834. }) || _class$4;
  6835. var _dec$3, _class$5;
  6836. let // jsdoc-ignore-end
  6837. TextMessage = (_dec$3 = messageType(-1), _dec$3(_class$5 = IE10Compatible(_class$5 = class TextMessage extends TypedMessage {
  6838. /**
  6839. * 文类类型消息
  6840. * @extends TypedMessage
  6841. * @param {String} [text='']
  6842. * @throws {TypeError} text 不是 String 类型
  6843. */
  6844. constructor(text = '') {
  6845. if (typeof text !== 'string') {
  6846. throw new TypeError(`${text} is not a string`);
  6847. }
  6848. super();
  6849. this.setText(text);
  6850. }
  6851. }) || _class$5) || _class$5);
  6852. /**
  6853. * @name TYPE
  6854. * @memberof TextMessage
  6855. * @type Number
  6856. * @static
  6857. * @const
  6858. */
  6859. var _class$6;
  6860. const debug$c = d('LC:MessageParser');
  6861. const tryParseJson = (target, key, descriptor) => {
  6862. const fn = descriptor.value; // eslint-disable-next-line no-param-reassign
  6863. descriptor.value = function wrapper(param) {
  6864. let content;
  6865. if (typeof param !== 'string') {
  6866. content = param;
  6867. } else {
  6868. try {
  6869. content = JSON.parse(param);
  6870. } catch (error) {
  6871. content = param;
  6872. }
  6873. }
  6874. return fn.call(this, content);
  6875. };
  6876. };
  6877. const applyPlugins = (target, key, descriptor) => {
  6878. const fn = descriptor.value; // eslint-disable-next-line no-param-reassign
  6879. descriptor.value = function wrapper(json) {
  6880. return Promise.resolve(json).then(applyMiddlewares(this._plugins.beforeMessageParse)).then(decoratedJson => fn.call(this, decoratedJson)).then(applyMiddlewares(this._plugins.afterMessageParse));
  6881. };
  6882. };
  6883. let MessageParser = (_class$6 = class MessageParser {
  6884. /**
  6885. * 消息解析器
  6886. * @param {Object} plugins 插件,插件的 messageClasses 会自动被注册,在解析时 beforeMessageParse 与 afterMessageParse Middleware 会被应用。
  6887. */
  6888. constructor(plugins = {}) {
  6889. this._plugins = plugins;
  6890. this._messageClasses = [];
  6891. this.register(plugins.messageClasses);
  6892. }
  6893. /**
  6894. * 注册消息类
  6895. *
  6896. * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
  6897. * 建议继承自 {@link TypedMessage},也可以传入一个消息类数组。
  6898. * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
  6899. */
  6900. register(messageClasses) {
  6901. ensureArray(messageClasses).map(klass => this._register(klass));
  6902. }
  6903. _register(messageClass) {
  6904. if (messageClass && messageClass.parse && messageClass.prototype && messageClass.prototype.getPayload) {
  6905. this._messageClasses.unshift(messageClass);
  6906. } else {
  6907. throw new TypeError('Invalid messageClass');
  6908. }
  6909. } // jsdoc-ignore-start
  6910. // jsdoc-ignore-end
  6911. /**
  6912. * 解析消息内容
  6913. * @param {Object | string | any} target 消息内容,如果是字符串会尝试 parse 为 JSON。
  6914. * @return {AVMessage} 解析后的消息
  6915. * @throws {Error} 如果不匹配任何注册的消息则抛出异常
  6916. */
  6917. parse(content) {
  6918. debug$c('parsing message: %O', content); // eslint-disable-next-line
  6919. for (const Klass of this._messageClasses) {
  6920. const contentCopy = isPlainObject(content) ? { ...content
  6921. } : content;
  6922. let valid;
  6923. let result;
  6924. try {
  6925. valid = Klass.validate(contentCopy);
  6926. } catch (error) {// eslint-disable-line no-empty
  6927. }
  6928. if (valid) {
  6929. try {
  6930. result = Klass.parse(contentCopy);
  6931. } catch (error) {
  6932. console.warn('parsing a valid message content error', {
  6933. error,
  6934. Klass,
  6935. content: contentCopy
  6936. });
  6937. }
  6938. if (result !== undefined) {
  6939. debug$c('parse result: %O', result);
  6940. return result;
  6941. }
  6942. }
  6943. }
  6944. throw new Error('No Message Class matched');
  6945. }
  6946. }, (_applyDecoratedDescriptor(_class$6.prototype, "parse", [tryParseJson, applyPlugins], Object.getOwnPropertyDescriptor(_class$6.prototype, "parse"), _class$6.prototype)), _class$6);
  6947. /** @module leancloud-realtime */
  6948. const debug$d = d('LC:IMPlugin');
  6949. /**
  6950. * 消息优先级枚举
  6951. * @enum {Number}
  6952. * @since 3.3.0
  6953. */
  6954. const MessagePriority = {
  6955. /** 高 */
  6956. HIGH: 1,
  6957. /** 普通 */
  6958. NORMAL: 2,
  6959. /** 低 */
  6960. LOW: 3
  6961. };
  6962. Object.freeze(MessagePriority);
  6963. /**
  6964. * 为 Conversation 定义一个新属性
  6965. * @param {String} prop 属性名
  6966. * @param {Object} [descriptor] 属性的描述符,参见 {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description getOwnPropertyDescriptor#Description - MDN},默认为该属性名对应的 Conversation 自定义属性的 getter/setter
  6967. * @returns void
  6968. * @example
  6969. *
  6970. * conversation.get('type');
  6971. * conversation.set('type', 1);
  6972. *
  6973. * // equals to
  6974. * defineConversationProperty('type');
  6975. * conversation.type;
  6976. * conversation.type = 1;
  6977. */
  6978. const defineConversationProperty = (prop, descriptor = {
  6979. get() {
  6980. return this.get(prop);
  6981. },
  6982. set(value) {
  6983. this.set(prop, value);
  6984. }
  6985. }) => {
  6986. Object.defineProperty(Conversation.prototype, prop, descriptor);
  6987. };
  6988. const onRealtimeCreate = realtime => {
  6989. /* eslint-disable no-param-reassign */
  6990. const deviceId = uuid();
  6991. realtime._IMClients = {};
  6992. realtime._IMClientsCreationCount = 0;
  6993. const messageParser = new MessageParser(realtime._plugins);
  6994. realtime._messageParser = messageParser;
  6995. const signAVUser = async user => realtime._request({
  6996. method: 'POST',
  6997. path: '/rtm/sign',
  6998. data: {
  6999. session_token: user.getSessionToken()
  7000. }
  7001. });
  7002. /**
  7003. * 注册消息类
  7004. *
  7005. * 在接收消息、查询消息时,会按照消息类注册顺序的逆序依次尝试解析消息内容
  7006. *
  7007. * @memberof Realtime
  7008. * @instance
  7009. * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
  7010. * 建议继承自 {@link TypedMessage}
  7011. * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
  7012. */
  7013. const register = messageParser.register.bind(messageParser);
  7014. /**
  7015. * 创建一个即时通讯客户端,多次创建相同 id 的客户端会返回同一个实例
  7016. * @memberof Realtime
  7017. * @instance
  7018. * @param {String|AV.User} [identity] 客户端 identity,如果不指定该参数,服务端会随机生成一个字符串作为 identity,
  7019. * 如果传入一个已登录的 AV.User,则会使用该用户的 id 作为客户端 identity 登录。
  7020. * @param {Object} [options]
  7021. * @param {Function} [options.signatureFactory] open session 时的签名方法 // TODO need details
  7022. * @param {Function} [options.conversationSignatureFactory] 对话创建、增减成员操作时的签名方法
  7023. * @param {Function} [options.blacklistSignatureFactory] 黑名单操作时的签名方法
  7024. * @param {String} [options.tag] 客户端类型标记,以支持单点登录功能
  7025. * @param {String} [options.isReconnect=false] 单点登录时标记该次登录是不是应用启动时自动重新登录
  7026. * @return {Promise.<IMClient>}
  7027. */
  7028. const createIMClient = async (identity, {
  7029. tag,
  7030. isReconnect,
  7031. ...clientOptions
  7032. } = {}, lagecyTag) => {
  7033. let id;
  7034. const buildinOptions = {};
  7035. if (identity) {
  7036. if (typeof identity === 'string') {
  7037. id = identity;
  7038. } else if (identity.id && identity.getSessionToken) {
  7039. ({
  7040. id
  7041. } = identity);
  7042. const sessionToken = identity.getSessionToken();
  7043. if (!sessionToken) {
  7044. throw new Error('User must be authenticated');
  7045. }
  7046. buildinOptions.signatureFactory = signAVUser;
  7047. } else {
  7048. throw new TypeError('Identity must be a String or an AV.User');
  7049. }
  7050. if (realtime._IMClients[id] !== undefined) {
  7051. return realtime._IMClients[id];
  7052. }
  7053. }
  7054. if (lagecyTag) {
  7055. console.warn('DEPRECATION createIMClient tag param: Use options.tag instead.');
  7056. }
  7057. const _tag = tag || lagecyTag;
  7058. const promise = realtime._open().then(connection => {
  7059. const client = new IMClient(id, { ...buildinOptions,
  7060. ...clientOptions
  7061. }, {
  7062. _connection: connection,
  7063. _request: realtime._request.bind(realtime),
  7064. _messageParser: messageParser,
  7065. _plugins: realtime._plugins,
  7066. _identity: identity
  7067. });
  7068. connection.on(RECONNECT, () => client._open(realtime._options.appId, _tag, deviceId, true)
  7069. /**
  7070. * 客户端连接恢复正常,该事件通常在 {@link Realtime#event:RECONNECT} 之后发生
  7071. * @event IMClient#RECONNECT
  7072. * @see Realtime#event:RECONNECT
  7073. * @since 3.2.0
  7074. */
  7075. /**
  7076. * 客户端重新登录发生错误(网络连接已恢复,但重新登录错误)
  7077. * @event IMClient#RECONNECT_ERROR
  7078. * @since 3.2.0
  7079. */
  7080. .then(() => client.emit(RECONNECT), error => client.emit(RECONNECT_ERROR, error)));
  7081. internal(client)._eventemitter.on('beforeclose', () => {
  7082. delete realtime._IMClients[client.id];
  7083. if (realtime._firstIMClient === client) {
  7084. delete realtime._firstIMClient;
  7085. }
  7086. }, realtime);
  7087. internal(client)._eventemitter.on('close', () => {
  7088. realtime._deregister(client);
  7089. }, realtime);
  7090. return client._open(realtime._options.appId, _tag, deviceId, isReconnect).then(() => {
  7091. realtime._IMClients[client.id] = client;
  7092. realtime._IMClientsCreationCount += 1;
  7093. if (realtime._IMClientsCreationCount === 1) {
  7094. client._omitPeerId(true);
  7095. realtime._firstIMClient = client;
  7096. } else if (realtime._IMClientsCreationCount > 1 && realtime._firstIMClient) {
  7097. realtime._firstIMClient._omitPeerId(false);
  7098. }
  7099. realtime._register(client);
  7100. return client;
  7101. }).catch(error => {
  7102. delete realtime._IMClients[client.id];
  7103. throw error;
  7104. });
  7105. }).then(...finalize(() => {
  7106. realtime._deregisterPending(promise);
  7107. })).catch(error => {
  7108. delete realtime._IMClients[id];
  7109. throw error;
  7110. });
  7111. if (identity) {
  7112. realtime._IMClients[id] = promise;
  7113. }
  7114. realtime._registerPending(promise);
  7115. return promise;
  7116. };
  7117. Object.assign(realtime, {
  7118. register,
  7119. createIMClient
  7120. });
  7121. /* eslint-enable no-param-reassign */
  7122. };
  7123. const beforeCommandDispatch = (command, realtime) => {
  7124. const isIMCommand = command.service === null || command.service === 2;
  7125. if (!isIMCommand) return true;
  7126. const targetClient = command.peerId ? realtime._IMClients[command.peerId] : realtime._firstIMClient;
  7127. if (targetClient) {
  7128. Promise.resolve(targetClient).then(client => client._dispatchCommand(command)).catch(debug$d);
  7129. } else {
  7130. debug$d('[WARN] Unexpected message received without any live client match: %O', trim(command));
  7131. }
  7132. return false;
  7133. };
  7134. const IMPlugin = {
  7135. name: 'leancloud-realtime-plugin-im',
  7136. onRealtimeCreate,
  7137. beforeCommandDispatch,
  7138. messageClasses: [Message, BinaryMessage, RecalledMessage, TextMessage]
  7139. };
  7140. /** @module leancloud-realtime */
  7141. Realtime.defineConversationProperty = defineConversationProperty;
  7142. Realtime.__preRegisteredPlugins = [IMPlugin];
  7143. const Event = { ...CoreEvent,
  7144. ...IMEvent
  7145. };
  7146. /** core + plugins + platform adapters */
  7147. setAdapters({
  7148. WebSocket: platformAdaptersNode.WebSocket,
  7149. request: platformAdaptersNode.request
  7150. });
  7151. exports.EventEmitter = EventEmitter;
  7152. exports.BinaryMessage = BinaryMessage;
  7153. exports.ChatRoom = ChatRoom;
  7154. exports.Conversation = Conversation;
  7155. exports.ConversationMemberRole = ConversationMemberRole;
  7156. exports.ConversationQuery = ConversationQuery;
  7157. exports.ErrorCode = ErrorCode;
  7158. exports.Event = Event;
  7159. exports.IE10Compatible = IE10Compatible;
  7160. exports.IMPlugin = IMPlugin;
  7161. exports.Message = Message;
  7162. exports.MessageParser = MessageParser;
  7163. exports.MessagePriority = MessagePriority;
  7164. exports.MessageQueryDirection = MessageQueryDirection;
  7165. exports.MessageStatus = MessageStatus;
  7166. exports.Promise = polyfilledPromise;
  7167. exports.Protocals = message;
  7168. exports.Protocols = message;
  7169. exports.Realtime = Realtime;
  7170. exports.RecalledMessage = RecalledMessage;
  7171. exports.ServiceConversation = ServiceConversation;
  7172. exports.TemporaryConversation = TemporaryConversation;
  7173. exports.TextMessage = TextMessage;
  7174. exports.TypedMessage = TypedMessage;
  7175. exports.debug = debug$2;
  7176. exports.defineConversationProperty = defineConversationProperty;
  7177. exports.getAdapter = getAdapter;
  7178. exports.messageField = messageField;
  7179. exports.messageType = messageType;
  7180. exports.setAdapters = setAdapters;
  7181. //# sourceMappingURL=im-node.js.map