@vkontakte/videoplayer-statistics 1.0.35 → 1.0.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/evergreen.esm.js +4 -4
- package/index.d.ts +399 -396
- package/package.json +3 -3
package/evergreen.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
* Mon,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.37
|
|
3
|
+
* Mon, 10 Jul 2023 15:30:39 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-37/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as H,safeStorage as w,getExponentialDelay as J,ErrorCategory as g,now as f,assertNever as X,Observable as Z,Subscription as $,merge as k,fromEvent as B,filterChanged as tt,map as et,filter as M,isNullable as F,Subject as st,once as it,combine as W,observableFrom as ot,isNonNullable as N}from"@vkontakte/videoplayer-shared/esnext.esm.js";import V from"lodash/debounce.js";import{Surface as v,VideoQuality as E,HttpConnectionType as L,VideoFormat as c,PlaybackState as K}from"@vkontakte/videoplayer-core/esnext.esm.js";function nt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let s=0,i,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(s<=2&&(s=33554432+Math.random()*16777216|0),i=s&15,s=s>>4,t[o]=e[o===19?i&3|8:i]);return t.join("")}var A;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(A||(A={}));var d;(function(e){e.Q144P="mobile",e.Q240P="lowest",e.Q360P="low",e.Q480P="medium",e.Q720P="high",e.Q1080P="fullhd",e.Q1440P="quadhd",e.Q2160P="ultrahd",e.UNKNOWN="unknown"})(d||(d={}));var l;(function(e){e.MP4="mp4",e.DASH="dash",e.DASH_SEP="dash_sep",e.ONDEMAND_DASH="ondemand_dash",e.HLS="hls",e.ONDEMAND_HLS="ondemand_hls",e.WEBM="webm",e.ONDEMAND_DASH_LIVE="ondemand_dash_live",e.ONDEMAND_HLS_LIVE="ondemand_hls_live",e.WEBRTC="webrtc",e.UNKNOWN="unknown",e.RTMP="rtmp"})(l||(l={}));var R;(function(e){e.AUTO="auto",e.MANUAL=""})(R||(R={}));var x;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})(x||(x={}));var _;(function(e){e[e.YES=1]="YES",e[e.NO=0]="NO"})(_||(_={}));var y;(function(e){e.EXCELLENT="excellent",e.GOOD="good",e.POOR="poor"})(y||(y={}));var P;(function(e){e.PIP="pip",e.FULLSCREEN="fullscreen",e.EXTERNAL="external",e.PREFETCH="prefetch"})(P||(P={}));var I;(function(e){e.SLIDER="slider",e.DOUBLE_TAP="double_tap",e.TIME_CODE="time_code",e.EPISODE="episode",e.REWIND="rewind",e.LIVE="live",e.UNKNOWN="unknown"})(I||(I={}));const q="1.0.35",rt="CIOPGQJGDIHBABABA",j={[A.PROD]:"https://api.ok.ru",[A.VK_ALIAS]:"https://api.mycdn.me",[A.VIDEOTEST]:"https://videotestapi.ok.ru/api",[A.TEST]:"https://apitest.ok.ru",[A.AUTO]:""},at="_one-stat_",z=`${at}uuid`,ht={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var T;(function(e){e[e.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",e[e.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",e[e.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",e[e.AUTH_LOGIN=401]="AUTH_LOGIN"})(T||(T={}));class ut{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new H(!1);backoffTimeoutId;constructor(t){this.params=t;const s=w.get(z);s?this.uuid=String(s):(this.uuid=nt(),w.set(z,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(s,i,o)||this.logRequest(t)}async logRequest(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const a=async(r,u=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,i,o)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:g.NETWORK,message:`Unknown ${s} error`,thrown:h});return}const m=h?.error_code;switch(m){case T.PARAM_SESSION_EXPIRED:case T.PARAM_SESSION_KEY:case T.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?a(r,u-1):void 0;case T.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?a(r,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${m}`,category:g.EXTERNAL_API,message:`${s} error`,data:h});return}}}};return a(t)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(t){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${q}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=J(this.consequentAuthErrors,ht);return new Promise(s=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(s).catch(i=>this.params.error$.next({id:"AuthorizeBackoff",category:g.NETWORK,message:"Otherwise unhandled error in authorization",thrown:i})).finally(()=>this.backoffTimeoutId=0)},t))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const t="auth.anonymLogin",s={session_data:{version:2,device_id:this.uuid,client_version:q.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(s.session_data.auth_token=this.authToken,s.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,s).then(i=>((!i||!i.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:g.EXTERNAL_API,message:"No session key",data:i}),this.sessionKey=i?.session_key??void 0,this.sessionKey)).catch(async i=>{this.sessionKey=void 0;const o=i?.error_code;switch(o){case T.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:g.EXTERNAL_API,message:"authorize error",data:i}):this.params.error$.next({id:"AuthorizeUnknown",category:g.NETWORK,message:"authorize error",thrown:i})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class ct{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.apiEnv,this.apiBaseUrl=t.apiBaseUrl,this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==A.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const t=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(t,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(t){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:g.NETWORK,message:"Unhandled resolve api base url error",thrown:t}),j[A.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,s,i){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:s,sessionKey:i}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(r){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:g.NETWORK,message:"Unhandled beacon error",thrown:r,data:{method:t,params:s}})}return!1}async sendRequest(t,s,i){const o=f(),a=r=>{if(r instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(r.message)){this.params.error$.next({id:"Network",category:g.NETWORK,message:"Request failed",thrown:r});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:g.NETWORK,message:"Unhandled request error",thrown:r,data:{method:t,params:s,sessionKey:i,time:f()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:s,sessionKey:i})}).then(r=>{const u=Number(r.headers.get("content-length"))===0,h=new Date(r.headers.get("date")??"").getTime(),m=f()-o;if(isFinite(h)&&this.timeSynchronisation.addServerTime(h,m),!u)return r.json().then(n=>Object.prototype.hasOwnProperty.call(n,"error_msg")?Promise.reject(n):n,a)},a)}_prepareQueryParams(t){const s=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&s.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([i,o])=>s.append(i,typeof o=="string"?o:JSON.stringify(o))),s}}const Q=5e3,dt=1e4,lt=6e4,O="onestat_events",ft=36*60*60*1e3,D=e=>e.timestamp+ft>=f();class pt{api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;constructor(t){this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:s,custom:{param:i}}=t;return["action_stop","close_at_empty_buffer"].includes(s)||s==="watch_coverage_record"&&i==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:g.WTF,message:String(t)??"Unknown logger error",thrown:t})}}firstFlush=V(()=>this.safeFlush(),Q,{maxWait:Q});debouncedFlush=V(()=>this.safeFlush(),dt,{maxWait:lt});readFromStorage(){const t=w.get(O);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const s=this.readFromStorage(),o=(s[this.userSalt]??[]).filter(D);w.set(O,JSON.stringify({...s,[this.userSalt]:[...o,t]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(D):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const t=this.readFromStorage();delete t[this.userSalt],w.set(O,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[s,i]of Object.entries(t)){const o=i.filter(D);o.length?t[s]=o:delete t[s]}w.set(O,JSON.stringify(t))}log(t){this.addToStorage(t),!this.isPaused&&(this.isUrgent(t)?this.flush():this.lastVsid!==t.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=t.custom.vsid)}flush(t=!1){const s=this.getFromStorage();s.length!==0&&(this.api.authorized$.getValue()?(t?this.api.logBeacon(s):this.api.logRequest(s),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const gt=()=>{let e,t;try{e=window.self!==window.top}catch(i){i instanceof DOMException&&i.name==="SecurityError"?e=!0:(e=!1,console.error(i))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(i){console.error(i)}try{!t&&document.referrer&&(t=document.referrer)}catch(i){console.error(i)}const s=t?new URL(t).hostname:void 0;return{isEmbed:e,host:s}},mt=e=>e&&{[E.INVARIANT]:d.UNKNOWN,[E.Q_144P]:d.Q144P,[E.Q_240P]:d.Q240P,[E.Q_360P]:d.Q360P,[E.Q_480P]:d.Q480P,[E.Q_720P]:d.Q720P,[E.Q_1080P]:d.Q1080P,[E.Q_1440P]:d.Q1440P,[E.Q_2160P]:d.Q2160P,[E.Q_4320P]:d.UNKNOWN}[e],G=e=>e&&{[L.HTTP1]:x.HTTP1,[L.HTTP2]:x.HTTP2,[L.QUIC]:x.HTTP3}[e],St=e=>{if(e!==void 0)switch(e){case c.MPEG:return l.MP4;case c.DASH:case c.DASH_LIVE:return l.DASH;case c.DASH_SEP:return l.DASH_SEP;case c.DASH_ONDEMAND:return l.ONDEMAND_DASH;case c.DASH_WEBM:case c.DASH_WEBM_AV1:case c.DASH_LIVE_WEBM:return l.WEBM;case c.DASH_LIVE_CMAF:return l.ONDEMAND_DASH_LIVE;case c.HLS:case c.HLS_LIVE:return l.HLS;case c.HLS_ONDEMAND:return l.ONDEMAND_HLS;case c.HLS_LIVE_CMAF:return l.ONDEMAND_HLS_LIVE;case c.WEB_RTC_LIVE:return l.WEBRTC;default:return X(e)}},U=e=>{if(e!==void 0)switch(e){case v.NONE:case v.INLINE:return;case v.FULLSCREEN:return P.FULLSCREEN;case v.SECOND_SCREEN:return P.EXTERNAL;case v.PIP:return P.PIP;default:return X(e)}},Et=e=>{switch(e){case"slow-2g":return y.POOR;case"2g":return y.POOR;case"3g":return y.GOOD;case"4g":return y.EXCELLENT}};class _t{offset=void 0;constructor(t){this.offset=t}getOffset(){return this.offset??0}setOffset(t){this.offset=t}now(){return Date.now()+(this.offset??0)}date(t=new Date){return t.setTime(t.getTime()+(this.offset??0)),t}addServerTime(t,s){const i=Date.now(),o=t-i-s/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const Y=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),At=e=>new Z(t=>{const s=new $,i=k(B(window,"beforeunload"),e.events.willDestruct$),o=new H(void 0);let a;e.info.isLive$.pipe(tt()).subscribe(b=>{a&&(a.unsubscribe(),o.next(void 0)),b?a=e.info.liveTime$.pipe(et(C=>C&&C/1e3)).subscribe(o):a=e.info.position$.subscribe(o),s.add(a)});const{playing$:r,paused$:u}=e.events,h=e.events.willSeek$.pipe(M(()=>e.info.playbackState$.getValue()===K.PLAYING)),m=e.events.seeked$.pipe(M(()=>e.info.playbackState$.getValue()===K.PLAYING)),n=k(r,m),p=k(u,h,i,e.events.looped$);let S;return s.add(n.subscribe(()=>S=o.getValue())),s.add(p.subscribe(()=>{const b=o.getValue();F(S)||S===b||F(b)||(t.next({from:S,to:b}),S=void 0)})),s});class wt{api;logger;config;subscription=new $;timeSynchronisation=new _t;experimental;statContext;vsid=Y();isEmbed;embedParent;uiEvents;player;seekAction$=new H(I.UNKNOWN);constructor(t,s){this.statContext=t,this.config={...s.config??{},requestRetryCount:1};const i=new st;this.experimental={error$:i};const o=new ct({apiKey:rt,apiBaseUrl:j[s.apiEnv],apiEnv:s.apiEnv,error$:i,timeSynchronisation:this.timeSynchronisation});this.api=new ut({apiTransport:o,refreshAuthToken:s.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,mobile:this.statContext.mobile??!1,error$:i}),this.logger=new pt({api:this.api,error$:i,userSalt:s.userSalt});const{isEmbed:a,host:r}=gt();this.isEmbed=a,this.embedParent=r,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const s=new $,i=(n,p)=>s.add(n.subscribe(p));i(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),i(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),i(t.events.willResume$,()=>{this.logPlay()}),i(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),i(At(t),n=>{const p=t.info.isLive$.getValue(),S={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};p?this.logWatchCoverageLive(S):this.logWatchCoverageRecord(S)});let o;i(t.info.isStalled$,n=>{n?o=f():(N(o)&&this.logEmptyBuffer({duration:f()-o}),o=void 0)});let a=!1;s.add(t.events.fatalError$.pipe(it()).subscribe(()=>a=!0)),i(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const p=N(o)?f()-o:void 0;this.logCloseAtEmptyBuffer({duration:p??0}),o=void 0}else a||this.logActionStop()}),i(t.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),i(t.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let r,u,h=!1;i(t.events.firstBytes$,n=>{r=f(),this.logFirstBytes({time:n})}),i(t.events.willStart$,()=>u=f()),i(t.info.currentBuffer$,n=>{!h&&n&&n.end-n.start>0&&N(r)&&(this.logPlayerReady({duration:f()-r}),h=!0)}),i(t.events.firstFrame$,()=>{N(r)&&!h&&(this.logPlayerReady({duration:f()-r}),h=!0),N(u)&&this.logFirstFrame({time:f()-u})}),i(t.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),i(W({muted:t.info.muted$,volume:t.info.volume$}),({muted:n,volume:p})=>this.updateContext({audible:!n&&p>0})),i(t.info.currentQuality$,n=>this.updateContext({quality:mt(n)})),i(t.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),i(t.info.currentFormat$,n=>this.updateContext({contentType:St(n)}));let m;return i(t.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:m!==void 0&&m!==n}),m=n}),i(t.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),i(t.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:G(n)}),this.updateContext({connectionType:G(n)})}),i(t.info.httpConnectionReused$,n=>{F(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),i(t.info.surface$,n=>this.updateContext({mode:U(n)})),i(W({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:n,available:p})=>{const S=p.find(({id:b})=>b===n);this.updateContext({subtitles:S?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.subscription.add(s),s}attachToUi(t){this.uiEvents=t;const s=new $;return this.player&&(s.add(t.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),s.add(t.actionSeek$.subscribe(this.seekAction$)),s.add(t.inPiP$.subscribe(i=>{const o=i?P.PIP:U(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.inFullscreen$.subscribe(i=>{const o=i?P.FULLSCREEN:U(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.actionSetSubtitle$.subscribe(i=>{this.updateContext({subtitles:i})})),this.subscription.add(s)),s}attachToAds(t){const s=new $;return s.add(t.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(t.started$.subscribe(i=>this.logAdStarted(i))).add(t.paused$.subscribe(()=>this.logAdPaused())).add(t.resumed$.subscribe(()=>this.logAdResumed())).add(t.ended$.subscribe(()=>this.logAdEnded())).add(t.skipped$.subscribe(()=>this.logAdSkipped())).add(t.clicked$.subscribe(()=>this.logAdClicked())),this.subscription.add(s),s}authorize(t){return this.api.authorize(t)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=Y()}setFieldBlacklist(){}logInited(){}logReady(t){this.log({operation:"player_ready",param:String(t.time)})}logStarted(...t){this.logActionPlay(...t)}logPlay(){this.log({operation:"play_toggle"})}logPause(t){this.log({operation:"pause",param:String(Math.round(t.position))})}logSeek(t){this.log({operation:"seek",param:t.action,time:t.time})}logFirstBytes(t){this.log({operation:"first_bytes",param:String(t.time)})}logFirstFrame(t){this.log({operation:"first_frame",param:String(t.time)})}logError(t){this.log({operation:"content_error",param:`${t.fatal?"fatal":"recoverable"}_${t.errorType}`})}logWatchCoverageRecord(t){this.log({operation:"watch_coverage_record",param:`${t.start}-${t.end}`})}logWatchCoverageLive(t){const s=t.start+this.timeSynchronisation.getOffset(),i=t.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${s}-${i}`})}logEmptyBuffer(t){this.log({operation:"empty_buffer",param:String(t.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(t){this.log({operation:"adv",param:t})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}subscribe(){this.subscription.add(B(window,"beforeunload").subscribe(()=>this.logger.flush(!0)));const t=window.navigator.connection;t&&"onchange"in t&&"effectiveType"in t&&this.subscription.add(k(B(t,"change"),ot(["init"])).subscribe(()=>this.updateContext({network:Et(t.effectiveType)})))}logPlayerReady(t){this.log({operation:"player_ready",param:String(Math.round(t.duration))})}logActionPlay(t){this.log({operation:"action_play",param:String(Math.round(t.position))})}logCloseAtEmptyBuffer(t){this.log({operation:"close_at_empty_buffer",param:String(Math.round(t.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(t){const s=this.createLogItem(t);this.logger.log(s)}createLogItem({operation:t,param:s,time:i}){const o=this.timeSynchronisation.now(),a=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,r=this.statContext.firstConnectionReused,u={vsid:this.vsid,vid:this.statContext.movieId,ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?R.AUTO:this.statContext.autoplay===!1?R.MANUAL:void 0,param:s,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:a,connection_reused:r===!0?_.YES:r===!1?_.NO:void 0,cached_data:this.statContext.cached===!0?_.YES:this.statContext.cached===!1?_.NO:void 0,live:this.statContext.liveEdge?_.YES:void 0,muted:this.statContext.audible===!1?_.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:_.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};return{operation:t,type:1,time:i,network:this.statContext.network,timestamp:o,custom:u}}}export{A as ApiEnv,x as ConnectionType,l as ContentType,wt as OneStat,d as Quality,I as SeekAction,q as VERSION};
|
|
6
|
+
import{ValueSubject as H,safeStorage as P,getExponentialDelay as J,ErrorCategory as g,now as f,assertNever as X,Observable as Z,Subscription as $,merge as k,fromEvent as B,filterChanged as tt,map as et,filter as M,isNullable as F,Subject as st,once as it,combine as W,observableFrom as ot,isNonNullable as v}from"@vkontakte/videoplayer-shared/esnext.esm.js";import V from"lodash/debounce.js";import{Surface as N,VideoQuality as b,HttpConnectionType as L,VideoFormat as c,PlaybackState as K}from"@vkontakte/videoplayer-core/esnext.esm.js";function rt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let s=0,i,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(s<=2&&(s=33554432+Math.random()*16777216|0),i=s&15,s=s>>4,t[o]=e[o===19?i&3|8:i]);return t.join("")}var _;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(_||(_={}));var l;(function(e){e.Q144P="mobile",e.Q240P="lowest",e.Q360P="low",e.Q480P="medium",e.Q720P="high",e.Q1080P="fullhd",e.Q1440P="quadhd",e.Q2160P="ultrahd",e.UNKNOWN="unknown"})(l||(l={}));var d;(function(e){e.MP4="mp4",e.DASH="dash",e.DASH_SEP="dash_sep",e.ONDEMAND_DASH="ondemand_dash",e.HLS="hls",e.ONDEMAND_HLS="ondemand_hls",e.WEBM="webm",e.AV1="av1",e.ONDEMAND_DASH_LIVE="ondemand_dash_live",e.ONDEMAND_HLS_LIVE="ondemand_hls_live",e.WEBRTC="webrtc",e.UNKNOWN="unknown",e.RTMP="rtmp"})(d||(d={}));var R;(function(e){e.AUTO="auto",e.MANUAL=""})(R||(R={}));var x;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})(x||(x={}));var E;(function(e){e[e.YES=1]="YES",e[e.NO=0]="NO"})(E||(E={}));var y;(function(e){e.EXCELLENT="excellent",e.GOOD="good",e.POOR="poor"})(y||(y={}));var w;(function(e){e.PIP="pip",e.FULLSCREEN="fullscreen",e.EXTERNAL="external",e.PREFETCH="prefetch"})(w||(w={}));var I;(function(e){e.SLIDER="slider",e.DOUBLE_TAP="double_tap",e.TIME_CODE="time_code",e.EPISODE="episode",e.REWIND="rewind",e.LIVE="live",e.UNKNOWN="unknown"})(I||(I={}));const q="1.0.37",nt="CIOPGQJGDIHBABABA",j={[_.PROD]:"https://api.ok.ru",[_.VK_ALIAS]:"https://api.mycdn.me",[_.VIDEOTEST]:"https://videotestapi.ok.ru/api",[_.TEST]:"https://apitest.ok.ru",[_.AUTO]:""},at="_one-stat_",z=`${at}uuid`,ut={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var T;(function(e){e[e.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",e[e.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",e[e.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",e[e.AUTH_LOGIN=401]="AUTH_LOGIN"})(T||(T={}));class ht{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new H(!1);backoffTimeoutId;constructor(t){this.params=t;const s=P.get(z);s?this.uuid=String(s):(this.uuid=rt(),P.set(z,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(s,i,o)||this.logRequest(t)}async logRequest(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const a=async(n,h=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,i,o)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:g.NETWORK,message:`Unknown ${s} error`,thrown:u});return}const m=u?.error_code;switch(m){case T.PARAM_SESSION_EXPIRED:case T.PARAM_SESSION_KEY:case T.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),h>0?a(n,h-1):void 0;case T.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),h>0?a(n,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${m}`,category:g.EXTERNAL_API,message:`${s} error`,data:u});return}}}};return a(t)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(t){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${q}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=J(this.consequentAuthErrors,ut);return new Promise(s=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(s).catch(i=>this.params.error$.next({id:"AuthorizeBackoff",category:g.NETWORK,message:"Otherwise unhandled error in authorization",thrown:i})).finally(()=>this.backoffTimeoutId=0)},t))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const t="auth.anonymLogin",s={session_data:{version:2,device_id:this.uuid,client_version:q.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(s.session_data.auth_token=this.authToken,s.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,s).then(i=>((!i||!i.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:g.EXTERNAL_API,message:"No session key",data:i}),this.sessionKey=i?.session_key??void 0,this.sessionKey)).catch(async i=>{this.sessionKey=void 0;const o=i?.error_code;switch(o){case T.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:g.EXTERNAL_API,message:"authorize error",data:i}):this.params.error$.next({id:"AuthorizeUnknown",category:g.NETWORK,message:"authorize error",thrown:i})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class ct{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.apiEnv,this.apiBaseUrl=t.apiBaseUrl,this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==_.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const t=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(t,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(t){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:g.NETWORK,message:"Unhandled resolve api base url error",thrown:t}),j[_.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,s,i){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:s,sessionKey:i}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:g.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:t,params:s}})}return!1}async sendRequest(t,s,i){const o=f(),a=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:g.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:g.NETWORK,message:"Unhandled request error",thrown:n,data:{method:t,params:s,sessionKey:i,time:f()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:s,sessionKey:i})}).then(n=>{const h=Number(n.headers.get("content-length"))===0,u=new Date(n.headers.get("date")??"").getTime(),m=f()-o;if(isFinite(u)&&this.timeSynchronisation.addServerTime(u,m),!h)return n.json().then(r=>Object.prototype.hasOwnProperty.call(r,"error_msg")?Promise.reject(r):r,a)},a)}_prepareQueryParams(t){const s=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&s.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([i,o])=>s.append(i,typeof o=="string"?o:JSON.stringify(o))),s}}const Q=5e3,dt=1e4,lt=6e4,O="onestat_events",ft=36*60*60*1e3,D=e=>e.timestamp+ft>=f();class pt{api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;flushMaxWait=P.isPersistent()?lt:0;constructor(t){this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:s,custom:{param:i}}=t;return["action_stop","close_at_empty_buffer"].includes(s)||s==="watch_coverage_record"&&i==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:g.WTF,message:String(t)??"Unknown logger error",thrown:t})}}firstFlush=V(()=>this.safeFlush(),Q,{maxWait:Q});debouncedFlush=V(()=>this.safeFlush(),dt,{maxWait:this.flushMaxWait});readFromStorage(){const t=P.get(O);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const s=this.readFromStorage(),o=(s[this.userSalt]??[]).filter(D);P.set(O,JSON.stringify({...s,[this.userSalt]:[...o,t]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(D):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const t=this.readFromStorage();delete t[this.userSalt],P.set(O,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[s,i]of Object.entries(t)){const o=i.filter(D);o.length?t[s]=o:delete t[s]}P.set(O,JSON.stringify(t))}log(t){this.addToStorage(t),!this.isPaused&&(this.isUrgent(t)?this.flush():this.lastVsid!==t.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=t.custom.vsid)}flush(t=!1){const s=this.getFromStorage();s.length!==0&&(this.api.authorized$.getValue()?(t?this.api.logBeacon(s):this.api.logRequest(s),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const gt=()=>{let e,t;try{e=window.self!==window.top}catch(i){i instanceof DOMException&&i.name==="SecurityError"?e=!0:(e=!1,console.error(i))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(i){console.error(i)}try{!t&&document.referrer&&(t=document.referrer)}catch(i){console.error(i)}const s=t?new URL(t).hostname:void 0;return{isEmbed:e,host:s}},mt=e=>e&&{[b.INVARIANT]:l.UNKNOWN,[b.Q_144P]:l.Q144P,[b.Q_240P]:l.Q240P,[b.Q_360P]:l.Q360P,[b.Q_480P]:l.Q480P,[b.Q_720P]:l.Q720P,[b.Q_1080P]:l.Q1080P,[b.Q_1440P]:l.Q1440P,[b.Q_2160P]:l.Q2160P,[b.Q_4320P]:l.UNKNOWN}[e],G=e=>e&&{[L.HTTP1]:x.HTTP1,[L.HTTP2]:x.HTTP2,[L.QUIC]:x.HTTP3}[e],St=e=>{if(e!==void 0)switch(e){case c.MPEG:return d.MP4;case c.DASH:case c.DASH_LIVE:return d.DASH;case c.DASH_SEP:return d.DASH_SEP;case c.DASH_ONDEMAND:return d.ONDEMAND_DASH;case c.DASH_WEBM:case c.DASH_LIVE_WEBM:return d.WEBM;case c.DASH_WEBM_AV1:return d.AV1;case c.DASH_LIVE_CMAF:return d.ONDEMAND_DASH_LIVE;case c.HLS:case c.HLS_LIVE:return d.HLS;case c.HLS_ONDEMAND:return d.ONDEMAND_HLS;case c.HLS_LIVE_CMAF:return d.ONDEMAND_HLS_LIVE;case c.WEB_RTC_LIVE:return d.WEBRTC;default:return X(e)}},U=e=>{if(e!==void 0)switch(e){case N.NONE:case N.INLINE:return;case N.FULLSCREEN:return w.FULLSCREEN;case N.SECOND_SCREEN:return w.EXTERNAL;case N.PIP:return w.PIP;default:return X(e)}},bt=e=>{switch(e){case"slow-2g":return y.POOR;case"2g":return y.POOR;case"3g":return y.GOOD;case"4g":return y.EXCELLENT}};class Et{offset=void 0;constructor(t){this.offset=t}getOffset(){return this.offset??0}setOffset(t){this.offset=t}now(){return Date.now()+(this.offset??0)}date(t=new Date){return t.setTime(t.getTime()+(this.offset??0)),t}addServerTime(t,s){const i=Date.now(),o=t-i-s/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const Y=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),_t=e=>new Z(t=>{const s=new $,i=k(B(window,"beforeunload"),e.events.willDestruct$),o=new H(void 0);let a;s.add(e.info.isLive$.pipe(tt()).subscribe(A=>{a&&(a.unsubscribe(),o.next(void 0)),A?a=e.info.liveTime$.pipe(et(C=>C&&C/1e3)).subscribe(o):a=e.info.position$.subscribe(o),s.add(a)}));const{playing$:n,paused$:h}=e.events,u=e.events.willSeek$.pipe(M(()=>e.info.playbackState$.getValue()===K.PLAYING)),m=e.events.seeked$.pipe(M(()=>e.info.playbackState$.getValue()===K.PLAYING)),r=k(n,m),p=k(h,u,i,e.events.looped$);let S;return s.add(r.subscribe(()=>S=o.getValue())),s.add(p.subscribe(()=>{const A=o.getValue();F(S)||S===A||F(A)||(t.next({from:S,to:A}),S=void 0)})),s});class wt{api;logger;config;subscription=new $;beforeunloadSubscription;timeSynchronisation=new Et;experimental;statContext;vsid=Y();isEmbed;embedParent;uiEvents;player;seekAction$=new H(I.UNKNOWN);constructor(t,s){this.statContext=t,this.config={...s.config??{},requestRetryCount:1};const i=new st;this.experimental={error$:i};const o=new ct({apiKey:nt,apiBaseUrl:j[s.apiEnv],apiEnv:s.apiEnv,error$:i,timeSynchronisation:this.timeSynchronisation});this.api=new ht({apiTransport:o,refreshAuthToken:s.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,mobile:this.statContext.mobile??!1,error$:i}),this.logger=new pt({api:this.api,error$:i,userSalt:s.userSalt});const{isEmbed:a,host:n}=gt();this.isEmbed=a,this.embedParent=n,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const s=new $,i=(r,p)=>s.add(r.subscribe(p));i(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),i(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),i(t.events.willResume$,()=>{this.logPlay()}),i(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),i(_t(t),r=>{const p=t.info.isLive$.getValue(),S={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};p?this.logWatchCoverageLive(S):this.logWatchCoverageRecord(S)});let o;i(t.info.isStalled$,r=>{r?o=f():(v(o)&&this.logEmptyBuffer({duration:f()-o}),o=void 0)});let a=!1;s.add(t.events.fatalError$.pipe(it()).subscribe(()=>a=!0)),i(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const p=v(o)?f()-o:void 0;this.logCloseAtEmptyBuffer({duration:p??0}),o=void 0}else a||this.logActionStop()}),i(t.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),i(t.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let n,h,u=!1;i(t.events.firstBytes$,r=>{n=f(),this.logFirstBytes({time:r})}),i(t.events.willStart$,()=>h=f()),i(t.info.currentBuffer$,r=>{!u&&r&&r.end-r.start>0&&v(n)&&(this.logPlayerReady({duration:f()-n}),u=!0)}),i(t.events.firstFrame$,()=>{v(n)&&!u&&(this.logPlayerReady({duration:f()-n}),u=!0),v(h)&&this.logFirstFrame({time:f()-h})}),i(t.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),i(W({muted:t.info.muted$,volume:t.info.volume$}),({muted:r,volume:p})=>this.updateContext({audible:!r&&p>0})),i(t.info.currentQuality$,r=>this.updateContext({quality:mt(r)})),i(t.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),i(t.info.currentFormat$,r=>this.updateContext({contentType:St(r)}));let m;return i(t.info.hostname$,r=>{this.updateContext({cdnHostname:r,failover:m!==void 0&&m!==r}),m=r}),i(t.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),i(t.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:G(r)}),this.updateContext({connectionType:G(r)})}),i(t.info.httpConnectionReused$,r=>{F(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),i(t.info.surface$,r=>this.updateContext({mode:U(r)})),i(W({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:r,available:p})=>{const S=p.find(({id:A})=>A===r);this.updateContext({subtitles:S?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToUi(t){this.uiEvents=t;const s=new $;return this.player&&(s.add(t.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),s.add(t.actionSeek$.subscribe(this.seekAction$)),s.add(t.inPiP$.subscribe(i=>{const o=i?w.PIP:U(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.inFullscreen$.subscribe(i=>{const o=i?w.FULLSCREEN:U(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.actionSetSubtitle$.subscribe(i=>{this.updateContext({subtitles:i})})),this.resubscribeBeforeunload(),this.subscription.add(s)),s}attachToAds(t){const s=new $;return s.add(t.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(t.started$.subscribe(i=>this.logAdStarted(i))).add(t.paused$.subscribe(()=>this.logAdPaused())).add(t.resumed$.subscribe(()=>this.logAdResumed())).add(t.ended$.subscribe(()=>this.logAdEnded())).add(t.skipped$.subscribe(()=>this.logAdSkipped())).add(t.clicked$.subscribe(()=>this.logAdClicked())),this.resubscribeBeforeunload(),this.subscription.add(s),s}authorize(t){return this.api.authorize(t)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=Y()}setFieldBlacklist(){}logInited(){}logReady(t){this.log({operation:"player_ready",param:String(t.time)})}logStarted(...t){this.logActionPlay(...t)}logPlay(){this.log({operation:"play_toggle"})}logPause(t){this.log({operation:"pause",param:String(Math.round(t.position))})}logSeek(t){this.log({operation:"seek",param:t.action,time:t.time})}logFirstBytes(t){this.log({operation:"first_bytes",param:String(t.time)})}logFirstFrame(t){this.log({operation:"first_frame",param:String(t.time)})}logError(t){this.log({operation:"content_error",param:`${t.fatal?"fatal":"recoverable"}_${t.errorType}`})}logWatchCoverageRecord(t){this.log({operation:"watch_coverage_record",param:`${t.start}-${t.end}`})}logWatchCoverageLive(t){const s=t.start+this.timeSynchronisation.getOffset(),i=t.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${s}-${i}`})}logEmptyBuffer(t){this.log({operation:"empty_buffer",param:String(t.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(t){this.log({operation:"adv",param:t})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}subscribe(){this.resubscribeBeforeunload();const t=window.navigator.connection;t&&"onchange"in t&&"effectiveType"in t&&this.subscription.add(k(B(t,"change"),ot(["init"])).subscribe(()=>this.updateContext({network:bt(t.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=B(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),this.subscription.add(this.beforeunloadSubscription)}logPlayerReady(t){this.log({operation:"player_ready",param:String(Math.round(t.duration))})}logActionPlay(t){this.log({operation:"action_play",param:String(Math.round(t.position))})}logCloseAtEmptyBuffer(t){this.log({operation:"close_at_empty_buffer",param:String(Math.round(t.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(t){const s=this.createLogItem(t);this.logger.log(s)}createLogItem({operation:t,param:s,time:i}){const o=this.timeSynchronisation.now(),a=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,n=this.statContext.firstConnectionReused,h={vsid:this.vsid,vid:this.statContext.movieId,ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?R.AUTO:this.statContext.autoplay===!1?R.MANUAL:void 0,param:s,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:a,connection_reused:n===!0?E.YES:n===!1?E.NO:void 0,cached_data:this.statContext.cached===!0?E.YES:this.statContext.cached===!1?E.NO:void 0,live:this.statContext.liveEdge?E.YES:void 0,muted:this.statContext.audible===!1?E.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:E.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};return{operation:t,type:1,time:i,network:this.statContext.network,timestamp:o,custom:h}}}export{_ as ApiEnv,x as ConnectionType,d as ContentType,wt as OneStat,l as Quality,I as SeekAction,q as VERSION};
|