@vkontakte/videoplayer-statistics 1.0.39 → 1.0.40-beta.1
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/package.json +3 -3
package/esnext.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.40-beta.1
|
|
3
|
+
* Wed, 06 Sep 2023 16:25:58 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-40/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{fillWithDefault as ct,ValueSubject as V,safeStorage as _,getExponentialDelay as ut,ErrorCategory as b,now as p,assertNever as it,Observable as ht,Subscription as C,merge as k,fromEvent as W,filterChanged as lt,map as dt,filter as z,Subject as ot,isNullable as q,isNonNullable as P,once as ft,combine as Q,observableFrom as pt}from"@vkontakte/videoplayer-shared/esnext.esm.js";import G from"lodash/debounce.js";import{Surface as x,VideoQuality as S,HttpConnectionType as B,VideoFormat as d,PlaybackState as j}from"@vkontakte/videoplayer-core/esnext.esm.js";var E;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(E||(E={}));var g;(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"})(g||(g={}));var f;(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"})(f||(f={}));var L;(function(e){e.AUTO="auto",e.MANUAL=""})(L||(L={}));var R;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})(R||(R={}));var A;(function(e){e[e.YES=1]="YES",e[e.NO=0]="NO"})(A||(A={}));var v;(function(e){e.EXCELLENT="excellent",e.GOOD="good",e.POOR="poor"})(v||(v={}));var T;(function(e){e.PIP="pip",e.FULLSCREEN="fullscreen",e.EXTERNAL="external",e.PREFETCH="prefetch"})(T||(T={}));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={}));var Y;(function(e){e.GRAPH_SHOW="iGraphShow",e.GRAPH_HIDE="iGraphHide",e.NEXT_AREA="iNextChapterArea",e.NEXT_BUTTON="iNextChapterBtn",e.WATCH_AGAIN="iWatchAgainBtn"})(Y||(Y={}));const gt={apiEnv:E.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},mt=e=>ct(e,gt);function bt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,t[o]=e[o===19?s&3|8:s]);return t.join("")}const X="1.0.39",St="CIOPGQJGDIHBABABA",J={[E.PROD]:"https://api.ok.ru",[E.VK_ALIAS]:"https://api.mycdn.me",[E.VIDEOTEST]:"https://videotestapi.ok.ru/api",[E.TEST]:"https://apitest.ok.ru",[E.AUTO]:""},Et="_one-stat_",F=`${Et}uuid`;var y;(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"})(y||(y={}));class At{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new V(!1);backoffTimeoutId;constructor(t){this.params=t;const i=_.get(F);i?i.startsWith('"')&&i.endsWith('"')?(this.uuid=i.replaceAll('"',""),_.set(F,this.uuid)):this.uuid=i:(this.uuid=bt(),_.set(F,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(t)}async logRequest(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const n=async(a,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,s,o)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:b.NETWORK,message:`Unknown ${i} error`,thrown:c});return}const h=c?.error_code;switch(h){case y.PARAM_SESSION_EXPIRED:case y.PARAM_SESSION_KEY:case y.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(a,l-1):void 0;case y.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(a,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:b.EXTERNAL_API,message:`${i} error`,data:c});return}}}};return n(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:${X}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=ut(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:b.NETWORK,message:"Otherwise unhandled error in authorization",thrown:s})).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",i={session_data:{version:2,device_id:this.uuid,client_version:X.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,i).then(s=>((!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:b.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=s?.session_key??void 0,this.sessionKey)).catch(async s=>{this.sessionKey=void 0;const o=s?.error_code;switch(o){case y.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:b.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:b.NETWORK,message:"authorize error",thrown:s})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class Z{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(t,i,s){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:i,options:s})}removeEventListener(t,i){if(!(t in this.listeners))return;const s=this.listeners[t];for(let o=0,n=s.length;o<n;o++)if(s[o].callback===i){s.splice(o,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const s=this.listeners[t.type].slice();for(let o=0,n=s.length;o<n;o++){const a=s[o];try{a.callback.call(this,t)}catch(l){Promise.resolve().then(()=>{throw l})}a.options&&a.options.once&&this.removeEventListener(t.type,a.callback)}return!t.defaultPrevented}}class rt extends Z{constructor(){super(),this.listeners||Z.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(t){t.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class _t{constructor(){Object.defineProperty(this,"signal",{value:new rt,writable:!0,configurable:!0})}abort(t){let i;try{i=new Event("abort")}catch{typeof document<"u"?document.createEvent?(i=document.createEvent("Event"),i.initEvent("abort",!1,!1)):(i=document.createEventObject(),i.type="abort"):i={type:"abort",bubbles:!1,cancelable:!1}}let s=t;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(_t.prototype[Symbol.toStringTag]="AbortController",rt.prototype[Symbol.toStringTag]="AbortSignal");function nt(e){return e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof e.Request=="function"&&!e.Request.prototype.hasOwnProperty("signal")||!e.AbortController}function wt(e){typeof e=="function"&&(e={fetch:e});const{fetch:t,Request:i=t.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=e;if(!nt({fetch:t,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:t,Request:n};let n=i;(n&&!n.prototype.hasOwnProperty("signal")||o)&&(n=function(h,r){let u;r&&r.signal&&(u=r.signal,delete r.signal);const m=new i(h,r);return u&&Object.defineProperty(m,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),m},n.prototype=i.prototype);const a=t;return{fetch:(c,h)=>{const r=n&&n.prototype.isPrototypeOf(c)?c.signal:h?h.signal:void 0;if(r){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(r.aborted)return Promise.reject(u);const m=new Promise((N,w)=>{r.addEventListener("abort",()=>w(u),{once:!0})});return h&&h.signal&&delete h.signal,Promise.race([m,a(c,h)])}return a(c,h)},Request:n}}const K=nt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),at=K?wt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,tt=K?at.fetch:window.fetch;K?at.Request:window.Request;class yt{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=J[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==E.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const t=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await tt(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:b.NETWORK,message:"Unhandled resolve api base url error",thrown:t}),J[E.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:i,sessionKey:s}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:b.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:t,params:i}})}return!1}async sendRequest(t,i,s){const o=p(),n=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:b.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:b.NETWORK,message:"Unhandled request error",thrown:a,data:{method:t,params:i,sessionKey:s,time:p()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),tt(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:i,sessionKey:s})}).then(a=>{const l=Number(a.headers.get("content-length"))===0,c=new Date(a.headers.get("date")??"").getTime(),h=p()-o;if(isFinite(c)&&this.timeSynchronisation?.addServerTime(c,h),!l)return a.json().then(r=>Object.prototype.hasOwnProperty.call(r,"error_msg")?Promise.reject(r):r,n)},n)}_prepareQueryParams(t){const i=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&i.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const $="onestat_events",U=e=>t=>t.timestamp+e>=p();class Tt{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;constructor(t){this.params=t,this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.firstFlush=G(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const i=_.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=G(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:i,custom:{param:s}}=t;return["action_stop","close_at_empty_buffer"].includes(i)||i==="watch_coverage_record"&&s==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:b.WTF,message:String(t)??"Unknown logger error",thrown:t})}}readFromStorage(){const t=_.get($);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(U(this.params.config.storageExpiration));_.set($,JSON.stringify({...i,[this.userSalt]:[...o,t]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(U(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const t=this.readFromStorage();delete t[this.userSalt],_.set($,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[i,s]of Object.entries(t)){const o=s.filter(U(this.params.config.storageExpiration));o.length?t[i]=o:delete t[i]}_.set($,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 i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(t&&this.params.config.useBeacon?this.api.logBeacon(i):this.api.logRequest(i),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 Pt=()=>{let e,t;try{e=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?e=!0:(e=!1,console.error(s))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!t&&document.referrer&&(t=document.referrer)}catch(s){console.error(s)}const i=t?new URL(t).hostname:void 0;return{isEmbed:e,host:i}},vt=e=>e&&{[S.INVARIANT]:g.UNKNOWN,[S.Q_144P]:g.Q144P,[S.Q_240P]:g.Q240P,[S.Q_360P]:g.Q360P,[S.Q_480P]:g.Q480P,[S.Q_720P]:g.Q720P,[S.Q_1080P]:g.Q1080P,[S.Q_1440P]:g.Q1440P,[S.Q_2160P]:g.Q2160P,[S.Q_4320P]:g.UNKNOWN}[e],et=e=>e&&{[B.HTTP1]:R.HTTP1,[B.HTTP2]:R.HTTP2,[B.QUIC]:R.HTTP3}[e],Nt=e=>{if(e!==void 0)switch(e){case d.MPEG:return f.MP4;case d.DASH:case d.DASH_LIVE:return f.DASH;case d.DASH_SEP:return f.DASH_SEP;case d.DASH_ONDEMAND:return f.ONDEMAND_DASH;case d.DASH_WEBM:case d.DASH_LIVE_WEBM:return f.WEBM;case d.DASH_WEBM_AV1:return f.AV1;case d.DASH_LIVE_CMAF:return f.ONDEMAND_DASH_LIVE;case d.HLS:case d.HLS_LIVE:return f.HLS;case d.HLS_ONDEMAND:return f.ONDEMAND_HLS;case d.HLS_LIVE_CMAF:return f.ONDEMAND_HLS_LIVE;case d.WEB_RTC_LIVE:return f.WEBRTC;default:return it(e)}},M=e=>{if(e!==void 0)switch(e){case x.NONE:case x.INLINE:return;case x.FULLSCREEN:return T.FULLSCREEN;case x.SECOND_SCREEN:return T.EXTERNAL;case x.PIP:return T.PIP;default:return it(e)}},Ot=e=>{switch(e){case"slow-2g":return v.POOR;case"2g":return v.POOR;case"3g":return v.GOOD;case"4g":return v.EXCELLENT}};class xt{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,i){const s=Date.now(),o=t-s-i/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 st=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Rt=e=>new ht(t=>{const i=new C,s=k(W(window,"beforeunload"),e.events.willDestruct$),o=new V(void 0);let n;i.add(e.info.isLive$.pipe(lt()).subscribe(O=>{n&&(n.unsubscribe(),o.next(void 0)),O?n=e.info.liveTime$.pipe(dt(D=>D&&D/1e3)).subscribe(o):n=e.info.position$.subscribe(o),i.add(n)}));const{playing$:a,paused$:l}=e.events,c=e.events.willSeek$.pipe(z(()=>e.info.playbackState$.getValue()===j.PLAYING)),h=e.events.seeked$.pipe(z(()=>e.info.playbackState$.getValue()===j.PLAYING));let r=!1;const u=new ot;i.add(c.subscribe(()=>{r||u.next(),r=!0})),i.add(h.subscribe(()=>r=!1));const m=k(a,h),N=k(l,u,s,e.events.looped$);let w;return i.add(m.subscribe(()=>w=o.getValue())),i.add(N.subscribe(()=>{const O=o.getValue();q(w)||w===O||q(O)||(t.next({from:w,to:O}),w=void 0)})),i}),H=()=>{const e=new C;return{subscription:e,subscribe:(t,i)=>{t&&e.add(t.subscribe(i))}}};class Lt{api;logger;config;subscription=new C;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=st();isEmbed;embedParent;uiEvents;player;seekAction$=new V(I.UNKNOWN);constructor(t,i){this.statContext=t,this.config=mt(i.config??{}),P(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new xt);const s=new ot;this.experimental={error$:s};const o=new yt({apiKey:St,config:this.config,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new At({config:this.config,apiTransport:o,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:s}),this.logger=new Tt({config:this.config,api:this.api,error$:s,userSalt:i.userSalt});const{isEmbed:n,host:a}=Pt();this.isEmbed=n,this.embedParent=a,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const i=new C,s=(r,u)=>i.add(r.subscribe(u));s(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),s(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),s(t.events.willResume$,()=>{this.logPlay()}),s(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),s(Rt(t),r=>{const u=t.info.isLive$.getValue(),m={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};u?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;s(t.info.isStalled$,r=>{r?o=p():(P(o)&&this.logEmptyBuffer({duration:p()-o}),o=void 0)});let n=!1;i.add(t.events.fatalError$.pipe(ft()).subscribe(()=>n=!0)),s(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const u=P(o)?p()-o:void 0;this.logCloseAtEmptyBuffer({duration:u??0}),o=void 0}else n||this.logActionStop()}),s(t.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),s(t.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let a,l,c=!1;s(t.events.firstBytes$,r=>{a=p(),this.logFirstBytes({time:r})}),s(t.events.willStart$,()=>l=p()),s(t.info.currentBuffer$,r=>{!c&&r&&r.end-r.start>0&&P(a)&&(this.logPlayerReady({duration:p()-a}),c=!0)}),s(t.events.firstFrame$,()=>{P(a)&&!c&&(this.logPlayerReady({duration:p()-a}),c=!0),P(l)&&this.logFirstFrame({time:p()-l})}),s(t.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),s(Q({muted:t.info.muted$,volume:t.info.volume$}),({muted:r,volume:u})=>this.updateContext({audible:!r&&u>0})),s(t.info.currentQuality$,r=>this.updateContext({quality:vt(r)})),s(t.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),s(t.info.currentFormat$,r=>this.updateContext({contentType:Nt(r)}));let h;return s(t.info.hostname$,r=>{this.updateContext({cdnHostname:r,failover:h!==void 0&&h!==r}),h=r}),s(t.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),s(t.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:et(r)}),this.updateContext({connectionType:et(r)})}),s(t.info.httpConnectionReused$,r=>{q(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),s(t.info.surface$,r=>this.updateContext({mode:M(r)})),s(Q({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:r,available:u})=>{const m=u.find(({id:N})=>N===r);this.updateContext({subtitles:m?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(t){this.uiEvents=t;const{subscription:i,subscribe:s}=H();return this.player&&(s(t.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),s(t.actionSeek$,this.seekAction$),s(t.inPiP$,o=>{const n=o?T.PIP:M(this.player?.info.surface$.getValue());this.updateContext({mode:n})}),s(t.inFullscreen$,o=>{const n=o?T.FULLSCREEN:M(this.player?.info.surface$.getValue());this.updateContext({mode:n})}),s(t.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(t){const{subscription:i,subscribe:s}=H();return s(t.slotRequested$,()=>this.logAdSlotRequest()),s(t.started$,o=>this.logAdStarted(o)),s(t.paused$,()=>this.logAdPaused()),s(t.resumed$,()=>this.logAdResumed()),s(t.ended$,()=>this.logAdEnded()),s(t.skipped$,()=>this.logAdSkipped()),s(t.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(t){const{subscription:i,subscribe:s}=H();return s(t.click$,o=>this.logInterfaceClick(o)),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}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=st()}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 i=this.timeSynchronisation?.getOffset()??0,s=t.start+i,o=t.end+i;this.log({operation:"watch_coverage_live",param:`${s}-${o}`})}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"})}logInterfaceClick(t){this.log({operation:"player_interface_click",param:t})}logNextMovie(t){this.log({operation:"next_movie",param:String(t)})}subscribe(){this.resubscribeBeforeunload();const t=window.navigator.connection;t&&"onchange"in t&&"effectiveType"in t&&this.subscription.add(k(W(t,"change"),pt(["init"])).subscribe(()=>this.updateContext({network:Ot(t.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=W(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){if(this.config.disabledOperations.includes(t.operation))return;const i=this.createLogItem(t);this.logger.log(i)}createLogItem({operation:t,param:i,time:s}){const o=this.timeSynchronisation?.now()??p(),n=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,a=this.statContext.firstConnectionReused,l={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?L.AUTO:this.statContext.autoplay===!1?L.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:n,connection_reused:a===!0?A.YES:a===!1?A.NO:void 0,cached_data:this.statContext.cached===!0?A.YES:this.statContext.cached===!1?A.NO:void 0,live:this.statContext.liveEdge?A.YES:void 0,muted:this.statContext.audible===!1?A.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:A.YES,ref_domain:this.isEmbed?this.embedParent:this.statContext.refUrl,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const c of this.config.disabledCustomFields)delete l[c];return{operation:t,type:1,time:s,network:this.statContext.network,timestamp:o,custom:l}}}export{E as ApiEnv,R as ConnectionType,f as ContentType,Y as InteractiveInterfaceClick,Lt as OneStat,g as Quality,I as SeekAction,X as VERSION};
|
|
6
|
+
import{fillWithDefault as ct,ValueSubject as V,safeStorage as _,getExponentialDelay as ut,ErrorCategory as b,now as p,assertNever as it,Observable as ht,Subscription as C,merge as k,fromEvent as W,filterChanged as lt,map as dt,filter as z,Subject as ot,isNullable as q,isNonNullable as P,once as ft,combine as Q,observableFrom as pt}from"@vkontakte/videoplayer-shared/esnext.esm.js";import G from"lodash/debounce.js";import{Surface as x,VideoQuality as S,HttpConnectionType as B,VideoFormat as d,PlaybackState as j}from"@vkontakte/videoplayer-core/esnext.esm.js";var E;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(E||(E={}));var g;(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"})(g||(g={}));var f;(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"})(f||(f={}));var L;(function(e){e.AUTO="auto",e.MANUAL=""})(L||(L={}));var R;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})(R||(R={}));var A;(function(e){e[e.YES=1]="YES",e[e.NO=0]="NO"})(A||(A={}));var v;(function(e){e.EXCELLENT="excellent",e.GOOD="good",e.POOR="poor"})(v||(v={}));var T;(function(e){e.PIP="pip",e.FULLSCREEN="fullscreen",e.EXTERNAL="external",e.PREFETCH="prefetch"})(T||(T={}));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={}));var Y;(function(e){e.GRAPH_SHOW="iGraphShow",e.GRAPH_HIDE="iGraphHide",e.NEXT_AREA="iNextChapterArea",e.NEXT_BUTTON="iNextChapterBtn",e.WATCH_AGAIN="iWatchAgainBtn"})(Y||(Y={}));const gt={apiEnv:E.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},mt=e=>ct(e,gt);function bt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,t[o]=e[o===19?s&3|8:s]);return t.join("")}const X="1.0.40-beta.1",St="CIOPGQJGDIHBABABA",J={[E.PROD]:"https://api.ok.ru",[E.VK_ALIAS]:"https://api.mycdn.me",[E.VIDEOTEST]:"https://videotestapi.ok.ru/api",[E.TEST]:"https://apitest.ok.ru",[E.AUTO]:""},Et="_one-stat_",F=`${Et}uuid`;var y;(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"})(y||(y={}));class At{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new V(!1);backoffTimeoutId;constructor(t){this.params=t;const i=_.get(F);i?i.startsWith('"')&&i.endsWith('"')?(this.uuid=i.replaceAll('"',""),_.set(F,this.uuid)):this.uuid=i:(this.uuid=bt(),_.set(F,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(t)}async logRequest(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const n=async(a,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,s,o)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:b.NETWORK,message:`Unknown ${i} error`,thrown:c});return}const h=c?.error_code;switch(h){case y.PARAM_SESSION_EXPIRED:case y.PARAM_SESSION_KEY:case y.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(a,l-1):void 0;case y.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(a,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:b.EXTERNAL_API,message:`${i} error`,data:c});return}}}};return n(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:${X}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=ut(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:b.NETWORK,message:"Otherwise unhandled error in authorization",thrown:s})).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",i={session_data:{version:2,device_id:this.uuid,client_version:X.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,i).then(s=>((!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:b.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=s?.session_key??void 0,this.sessionKey)).catch(async s=>{this.sessionKey=void 0;const o=s?.error_code;switch(o){case y.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:b.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:b.NETWORK,message:"authorize error",thrown:s})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class Z{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(t,i,s){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:i,options:s})}removeEventListener(t,i){if(!(t in this.listeners))return;const s=this.listeners[t];for(let o=0,n=s.length;o<n;o++)if(s[o].callback===i){s.splice(o,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const s=this.listeners[t.type].slice();for(let o=0,n=s.length;o<n;o++){const a=s[o];try{a.callback.call(this,t)}catch(l){Promise.resolve().then(()=>{throw l})}a.options&&a.options.once&&this.removeEventListener(t.type,a.callback)}return!t.defaultPrevented}}class rt extends Z{constructor(){super(),this.listeners||Z.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(t){t.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class _t{constructor(){Object.defineProperty(this,"signal",{value:new rt,writable:!0,configurable:!0})}abort(t){let i;try{i=new Event("abort")}catch{typeof document<"u"?document.createEvent?(i=document.createEvent("Event"),i.initEvent("abort",!1,!1)):(i=document.createEventObject(),i.type="abort"):i={type:"abort",bubbles:!1,cancelable:!1}}let s=t;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(_t.prototype[Symbol.toStringTag]="AbortController",rt.prototype[Symbol.toStringTag]="AbortSignal");function nt(e){return e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof e.Request=="function"&&!e.Request.prototype.hasOwnProperty("signal")||!e.AbortController}function wt(e){typeof e=="function"&&(e={fetch:e});const{fetch:t,Request:i=t.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=e;if(!nt({fetch:t,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:t,Request:n};let n=i;(n&&!n.prototype.hasOwnProperty("signal")||o)&&(n=function(h,r){let u;r&&r.signal&&(u=r.signal,delete r.signal);const m=new i(h,r);return u&&Object.defineProperty(m,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),m},n.prototype=i.prototype);const a=t;return{fetch:(c,h)=>{const r=n&&n.prototype.isPrototypeOf(c)?c.signal:h?h.signal:void 0;if(r){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(r.aborted)return Promise.reject(u);const m=new Promise((N,w)=>{r.addEventListener("abort",()=>w(u),{once:!0})});return h&&h.signal&&delete h.signal,Promise.race([m,a(c,h)])}return a(c,h)},Request:n}}const K=nt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),at=K?wt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,tt=K?at.fetch:window.fetch;K?at.Request:window.Request;class yt{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=J[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==E.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const t=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await tt(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:b.NETWORK,message:"Unhandled resolve api base url error",thrown:t}),J[E.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:i,sessionKey:s}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:b.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:t,params:i}})}return!1}async sendRequest(t,i,s){const o=p(),n=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:b.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:b.NETWORK,message:"Unhandled request error",thrown:a,data:{method:t,params:i,sessionKey:s,time:p()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),tt(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:i,sessionKey:s})}).then(a=>{const l=Number(a.headers.get("content-length"))===0,c=new Date(a.headers.get("date")??"").getTime(),h=p()-o;if(isFinite(c)&&this.timeSynchronisation?.addServerTime(c,h),!l)return a.json().then(r=>Object.prototype.hasOwnProperty.call(r,"error_msg")?Promise.reject(r):r,n)},n)}_prepareQueryParams(t){const i=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&i.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const $="onestat_events",U=e=>t=>t.timestamp+e>=p();class Tt{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;constructor(t){this.params=t,this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.firstFlush=G(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const i=_.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=G(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:i,custom:{param:s}}=t;return["action_stop","close_at_empty_buffer"].includes(i)||i==="watch_coverage_record"&&s==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:b.WTF,message:String(t)??"Unknown logger error",thrown:t})}}readFromStorage(){const t=_.get($);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(U(this.params.config.storageExpiration));_.set($,JSON.stringify({...i,[this.userSalt]:[...o,t]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(U(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const t=this.readFromStorage();delete t[this.userSalt],_.set($,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[i,s]of Object.entries(t)){const o=s.filter(U(this.params.config.storageExpiration));o.length?t[i]=o:delete t[i]}_.set($,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 i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(t&&this.params.config.useBeacon?this.api.logBeacon(i):this.api.logRequest(i),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 Pt=()=>{let e,t;try{e=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?e=!0:(e=!1,console.error(s))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!t&&document.referrer&&(t=document.referrer)}catch(s){console.error(s)}const i=t?new URL(t).hostname:void 0;return{isEmbed:e,host:i}},vt=e=>e&&{[S.INVARIANT]:g.UNKNOWN,[S.Q_144P]:g.Q144P,[S.Q_240P]:g.Q240P,[S.Q_360P]:g.Q360P,[S.Q_480P]:g.Q480P,[S.Q_720P]:g.Q720P,[S.Q_1080P]:g.Q1080P,[S.Q_1440P]:g.Q1440P,[S.Q_2160P]:g.Q2160P,[S.Q_4320P]:g.UNKNOWN}[e],et=e=>e&&{[B.HTTP1]:R.HTTP1,[B.HTTP2]:R.HTTP2,[B.QUIC]:R.HTTP3}[e],Nt=e=>{if(e!==void 0)switch(e){case d.MPEG:return f.MP4;case d.DASH:case d.DASH_LIVE:return f.DASH;case d.DASH_SEP:return f.DASH_SEP;case d.DASH_ONDEMAND:return f.ONDEMAND_DASH;case d.DASH_WEBM:case d.DASH_LIVE_WEBM:return f.WEBM;case d.DASH_WEBM_AV1:return f.AV1;case d.DASH_LIVE_CMAF:return f.ONDEMAND_DASH_LIVE;case d.HLS:case d.HLS_LIVE:return f.HLS;case d.HLS_ONDEMAND:return f.ONDEMAND_HLS;case d.HLS_LIVE_CMAF:return f.ONDEMAND_HLS_LIVE;case d.WEB_RTC_LIVE:return f.WEBRTC;default:return it(e)}},M=e=>{if(e!==void 0)switch(e){case x.NONE:case x.INLINE:return;case x.FULLSCREEN:return T.FULLSCREEN;case x.SECOND_SCREEN:return T.EXTERNAL;case x.PIP:return T.PIP;default:return it(e)}},Ot=e=>{switch(e){case"slow-2g":return v.POOR;case"2g":return v.POOR;case"3g":return v.GOOD;case"4g":return v.EXCELLENT}};class xt{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,i){const s=Date.now(),o=t-s-i/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 st=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Rt=e=>new ht(t=>{const i=new C,s=k(W(window,"beforeunload"),e.events.willDestruct$),o=new V(void 0);let n;i.add(e.info.isLive$.pipe(lt()).subscribe(O=>{n&&(n.unsubscribe(),o.next(void 0)),O?n=e.info.liveTime$.pipe(dt(D=>D&&D/1e3)).subscribe(o):n=e.info.position$.subscribe(o),i.add(n)}));const{playing$:a,paused$:l}=e.events,c=e.events.willSeek$.pipe(z(()=>e.info.playbackState$.getValue()===j.PLAYING)),h=e.events.seeked$.pipe(z(()=>e.info.playbackState$.getValue()===j.PLAYING));let r=!1;const u=new ot;i.add(c.subscribe(()=>{r||u.next(),r=!0})),i.add(h.subscribe(()=>r=!1));const m=k(a,h),N=k(l,u,s,e.events.looped$);let w;return i.add(m.subscribe(()=>w=o.getValue())),i.add(N.subscribe(()=>{const O=o.getValue();q(w)||w===O||q(O)||(t.next({from:w,to:O}),w=void 0)})),i}),H=()=>{const e=new C;return{subscription:e,subscribe:(t,i)=>{t&&e.add(t.subscribe(i))}}};class Lt{api;logger;config;subscription=new C;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=st();isEmbed;embedParent;uiEvents;player;seekAction$=new V(I.UNKNOWN);constructor(t,i){this.statContext=t,this.config=mt(i.config??{}),P(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new xt);const s=new ot;this.experimental={error$:s};const o=new yt({apiKey:St,config:this.config,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new At({config:this.config,apiTransport:o,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:s}),this.logger=new Tt({config:this.config,api:this.api,error$:s,userSalt:i.userSalt});const{isEmbed:n,host:a}=Pt();this.isEmbed=n,this.embedParent=a,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const i=new C,s=(r,u)=>i.add(r.subscribe(u));s(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),s(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),s(t.events.willResume$,()=>{this.logPlay()}),s(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),s(Rt(t),r=>{const u=t.info.isLive$.getValue(),m={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};u?this.logWatchCoverageLive(m):this.logWatchCoverageRecord(m)});let o;s(t.info.isStalled$,r=>{r?o=p():(P(o)&&this.logEmptyBuffer({duration:p()-o}),o=void 0)});let n=!1;i.add(t.events.fatalError$.pipe(ft()).subscribe(()=>n=!0)),s(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const u=P(o)?p()-o:void 0;this.logCloseAtEmptyBuffer({duration:u??0}),o=void 0}else n||this.logActionStop()}),s(t.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),s(t.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let a,l,c=!1;s(t.events.firstBytes$,r=>{a=p(),this.logFirstBytes({time:r})}),s(t.events.willStart$,()=>l=p()),s(t.info.currentBuffer$,r=>{!c&&r&&r.end-r.start>0&&P(a)&&(this.logPlayerReady({duration:p()-a}),c=!0)}),s(t.events.firstFrame$,()=>{P(a)&&!c&&(this.logPlayerReady({duration:p()-a}),c=!0),P(l)&&this.logFirstFrame({time:p()-l})}),s(t.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),s(Q({muted:t.info.muted$,volume:t.info.volume$}),({muted:r,volume:u})=>this.updateContext({audible:!r&&u>0})),s(t.info.currentQuality$,r=>this.updateContext({quality:vt(r)})),s(t.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),s(t.info.currentFormat$,r=>this.updateContext({contentType:Nt(r)}));let h;return s(t.info.hostname$,r=>{this.updateContext({cdnHostname:r,failover:h!==void 0&&h!==r}),h=r}),s(t.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),s(t.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:et(r)}),this.updateContext({connectionType:et(r)})}),s(t.info.httpConnectionReused$,r=>{q(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),s(t.info.surface$,r=>this.updateContext({mode:M(r)})),s(Q({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:r,available:u})=>{const m=u.find(({id:N})=>N===r);this.updateContext({subtitles:m?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(t){this.uiEvents=t;const{subscription:i,subscribe:s}=H();return this.player&&(s(t.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),s(t.actionSeek$,this.seekAction$),s(t.inPiP$,o=>{const n=o?T.PIP:M(this.player?.info.surface$.getValue());this.updateContext({mode:n})}),s(t.inFullscreen$,o=>{const n=o?T.FULLSCREEN:M(this.player?.info.surface$.getValue());this.updateContext({mode:n})}),s(t.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(t){const{subscription:i,subscribe:s}=H();return s(t.slotRequested$,()=>this.logAdSlotRequest()),s(t.started$,o=>this.logAdStarted(o)),s(t.paused$,()=>this.logAdPaused()),s(t.resumed$,()=>this.logAdResumed()),s(t.ended$,()=>this.logAdEnded()),s(t.skipped$,()=>this.logAdSkipped()),s(t.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(t){const{subscription:i,subscribe:s}=H();return s(t.click$,o=>this.logInterfaceClick(o)),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}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=st()}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 i=this.timeSynchronisation?.getOffset()??0,s=t.start+i,o=t.end+i;this.log({operation:"watch_coverage_live",param:`${s}-${o}`})}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"})}logInterfaceClick(t){this.log({operation:"player_interface_click",param:t})}logNextMovie(t){this.log({operation:"next_movie",param:String(t)})}subscribe(){this.resubscribeBeforeunload();const t=window.navigator.connection;t&&"onchange"in t&&"effectiveType"in t&&this.subscription.add(k(W(t,"change"),pt(["init"])).subscribe(()=>this.updateContext({network:Ot(t.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=W(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){if(this.config.disabledOperations.includes(t.operation))return;const i=this.createLogItem(t);this.logger.log(i)}createLogItem({operation:t,param:i,time:s}){const o=this.timeSynchronisation?.now()??p(),n=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,a=this.statContext.firstConnectionReused,l={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?L.AUTO:this.statContext.autoplay===!1?L.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:n,connection_reused:a===!0?A.YES:a===!1?A.NO:void 0,cached_data:this.statContext.cached===!0?A.YES:this.statContext.cached===!1?A.NO:void 0,live:this.statContext.liveEdge?A.YES:void 0,muted:this.statContext.audible===!1?A.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:A.YES,ref_domain:this.isEmbed?this.embedParent:this.statContext.refUrl,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const c of this.config.disabledCustomFields)delete l[c];return{operation:t,type:1,time:s,network:this.statContext.network,timestamp:o,custom:l}}}export{E as ApiEnv,R as ConnectionType,f as ContentType,Y as InteractiveInterfaceClick,Lt as OneStat,g as Quality,I as SeekAction,X as VERSION};
|
package/evergreen.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.40-beta.1
|
|
3
|
+
* Wed, 06 Sep 2023 16:25:58 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-40/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{fillWithDefault as st,ValueSubject as K,safeStorage as A,getExponentialDelay as it,ErrorCategory as m,now as l,assertNever as tt,Observable as ot,Subscription as R,merge as O,fromEvent as M,filterChanged as nt,map as rt,filter as z,Subject as et,isNullable as V,isNonNullable as w,once as at,combine as q,observableFrom as ht}from"@vkontakte/videoplayer-shared/esnext.esm.js";import Q from"lodash/debounce.js";import{Surface as v,VideoQuality as S,HttpConnectionType as B,VideoFormat as c,PlaybackState as G}from"@vkontakte/videoplayer-core/esnext.esm.js";var b;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(b||(b={}));var p;(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"})(p||(p={}));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 C;(function(e){e.AUTO="auto",e.MANUAL=""})(C||(C={}));var $;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})($||($={}));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 T;(function(e){e.PIP="pip",e.FULLSCREEN="fullscreen",e.EXTERNAL="external",e.PREFETCH="prefetch"})(T||(T={}));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={}));var Y;(function(e){e.GRAPH_SHOW="iGraphShow",e.GRAPH_HIDE="iGraphHide",e.NEXT_AREA="iNextChapterArea",e.NEXT_BUTTON="iNextChapterBtn",e.WATCH_AGAIN="iWatchAgainBtn"})(Y||(Y={}));const ut={apiEnv:b.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ct=e=>st(e,ut);function dt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,t[o]=e[o===19?s&3|8:s]);return t.join("")}const X="1.0.39",lt="CIOPGQJGDIHBABABA",j={[b.PROD]:"https://api.ok.ru",[b.VK_ALIAS]:"https://api.mycdn.me",[b.VIDEOTEST]:"https://videotestapi.ok.ru/api",[b.TEST]:"https://apitest.ok.ru",[b.AUTO]:""},ft="_one-stat_",U=`${ft}uuid`;var _;(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"})(_||(_={}));class pt{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new K(!1);backoffTimeoutId;constructor(t){this.params=t;const i=A.get(U);i?i.startsWith('"')&&i.endsWith('"')?(this.uuid=i.replaceAll('"',""),A.set(U,this.uuid)):this.uuid=i:(this.uuid=dt(),A.set(U,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(t)}async logRequest(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const r=async(a,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,s,o)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:m.NETWORK,message:`Unknown ${i} error`,thrown:h});return}const g=h?.error_code;switch(g){case _.PARAM_SESSION_EXPIRED:case _.PARAM_SESSION_KEY:case _.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(a,u-1):void 0;case _.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(a,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${g}`,category:m.EXTERNAL_API,message:`${i} error`,data:h});return}}}};return r(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:${X}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=it(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:m.NETWORK,message:"Otherwise unhandled error in authorization",thrown:s})).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",i={session_data:{version:2,device_id:this.uuid,client_version:X.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,i).then(s=>((!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:m.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=s?.session_key??void 0,this.sessionKey)).catch(async s=>{this.sessionKey=void 0;const o=s?.error_code;switch(o){case _.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:m.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:m.NETWORK,message:"authorize error",thrown:s})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class gt{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=j[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==b.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:m.NETWORK,message:"Unhandled resolve api base url error",thrown:t}),j[b.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:i,sessionKey:s}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:m.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:t,params:i}})}return!1}async sendRequest(t,i,s){const o=l(),r=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:m.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:m.NETWORK,message:"Unhandled request error",thrown:a,data:{method:t,params:i,sessionKey:s,time:l()-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:i,sessionKey:s})}).then(a=>{const u=Number(a.headers.get("content-length"))===0,h=new Date(a.headers.get("date")??"").getTime(),g=l()-o;if(isFinite(h)&&this.timeSynchronisation?.addServerTime(h,g),!u)return a.json().then(n=>Object.prototype.hasOwnProperty.call(n,"error_msg")?Promise.reject(n):n,r)},r)}_prepareQueryParams(t){const i=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&i.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const k="onestat_events",F=e=>t=>t.timestamp+e>=l();class mt{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;constructor(t){this.params=t,this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.firstFlush=Q(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const i=A.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Q(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:i,custom:{param:s}}=t;return["action_stop","close_at_empty_buffer"].includes(i)||i==="watch_coverage_record"&&s==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:m.WTF,message:String(t)??"Unknown logger error",thrown:t})}}readFromStorage(){const t=A.get(k);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(F(this.params.config.storageExpiration));A.set(k,JSON.stringify({...i,[this.userSalt]:[...o,t]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(F(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const t=this.readFromStorage();delete t[this.userSalt],A.set(k,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[i,s]of Object.entries(t)){const o=s.filter(F(this.params.config.storageExpiration));o.length?t[i]=o:delete t[i]}A.set(k,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 i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(t&&this.params.config.useBeacon?this.api.logBeacon(i):this.api.logRequest(i),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 St=()=>{let e,t;try{e=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?e=!0:(e=!1,console.error(s))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!t&&document.referrer&&(t=document.referrer)}catch(s){console.error(s)}const i=t?new URL(t).hostname:void 0;return{isEmbed:e,host:i}},bt=e=>e&&{[S.INVARIANT]:p.UNKNOWN,[S.Q_144P]:p.Q144P,[S.Q_240P]:p.Q240P,[S.Q_360P]:p.Q360P,[S.Q_480P]:p.Q480P,[S.Q_720P]:p.Q720P,[S.Q_1080P]:p.Q1080P,[S.Q_1440P]:p.Q1440P,[S.Q_2160P]:p.Q2160P,[S.Q_4320P]:p.UNKNOWN}[e],J=e=>e&&{[B.HTTP1]:$.HTTP1,[B.HTTP2]:$.HTTP2,[B.QUIC]:$.HTTP3}[e],Et=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 tt(e)}},H=e=>{if(e!==void 0)switch(e){case v.NONE:case v.INLINE:return;case v.FULLSCREEN:return T.FULLSCREEN;case v.SECOND_SCREEN:return T.EXTERNAL;case v.PIP:return T.PIP;default:return tt(e)}},At=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,i){const s=Date.now(),o=t-s-i/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 Z=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Tt=e=>new ot(t=>{const i=new R,s=O(M(window,"beforeunload"),e.events.willDestruct$),o=new K(void 0);let r;i.add(e.info.isLive$.pipe(nt()).subscribe(x=>{r&&(r.unsubscribe(),o.next(void 0)),x?r=e.info.liveTime$.pipe(rt(D=>D&&D/1e3)).subscribe(o):r=e.info.position$.subscribe(o),i.add(r)}));const{playing$:a,paused$:u}=e.events,h=e.events.willSeek$.pipe(z(()=>e.info.playbackState$.getValue()===G.PLAYING)),g=e.events.seeked$.pipe(z(()=>e.info.playbackState$.getValue()===G.PLAYING));let n=!1;const f=new et;i.add(h.subscribe(()=>{n||f.next(),n=!0})),i.add(g.subscribe(()=>n=!1));const P=O(a,g),L=O(u,f,s,e.events.looped$);let N;return i.add(P.subscribe(()=>N=o.getValue())),i.add(L.subscribe(()=>{const x=o.getValue();V(N)||N===x||V(x)||(t.next({from:N,to:x}),N=void 0)})),i}),W=()=>{const e=new R;return{subscription:e,subscribe:(t,i)=>{t&&e.add(t.subscribe(i))}}};class Nt{api;logger;config;subscription=new R;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=Z();isEmbed;embedParent;uiEvents;player;seekAction$=new K(I.UNKNOWN);constructor(t,i){this.statContext=t,this.config=ct(i.config??{}),w(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new _t);const s=new et;this.experimental={error$:s};const o=new gt({apiKey:lt,config:this.config,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new pt({config:this.config,apiTransport:o,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:s}),this.logger=new mt({config:this.config,api:this.api,error$:s,userSalt:i.userSalt});const{isEmbed:r,host:a}=St();this.isEmbed=r,this.embedParent=a,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const i=new R,s=(n,f)=>i.add(n.subscribe(f));s(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),s(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),s(t.events.willResume$,()=>{this.logPlay()}),s(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),s(Tt(t),n=>{const f=t.info.isLive$.getValue(),P={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};f?this.logWatchCoverageLive(P):this.logWatchCoverageRecord(P)});let o;s(t.info.isStalled$,n=>{n?o=l():(w(o)&&this.logEmptyBuffer({duration:l()-o}),o=void 0)});let r=!1;i.add(t.events.fatalError$.pipe(at()).subscribe(()=>r=!0)),s(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const f=w(o)?l()-o:void 0;this.logCloseAtEmptyBuffer({duration:f??0}),o=void 0}else r||this.logActionStop()}),s(t.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),s(t.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let a,u,h=!1;s(t.events.firstBytes$,n=>{a=l(),this.logFirstBytes({time:n})}),s(t.events.willStart$,()=>u=l()),s(t.info.currentBuffer$,n=>{!h&&n&&n.end-n.start>0&&w(a)&&(this.logPlayerReady({duration:l()-a}),h=!0)}),s(t.events.firstFrame$,()=>{w(a)&&!h&&(this.logPlayerReady({duration:l()-a}),h=!0),w(u)&&this.logFirstFrame({time:l()-u})}),s(t.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),s(q({muted:t.info.muted$,volume:t.info.volume$}),({muted:n,volume:f})=>this.updateContext({audible:!n&&f>0})),s(t.info.currentQuality$,n=>this.updateContext({quality:bt(n)})),s(t.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),s(t.info.currentFormat$,n=>this.updateContext({contentType:Et(n)}));let g;return s(t.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:g!==void 0&&g!==n}),g=n}),s(t.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),s(t.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:J(n)}),this.updateContext({connectionType:J(n)})}),s(t.info.httpConnectionReused$,n=>{V(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),s(t.info.surface$,n=>this.updateContext({mode:H(n)})),s(q({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:n,available:f})=>{const P=f.find(({id:L})=>L===n);this.updateContext({subtitles:P?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(t){this.uiEvents=t;const{subscription:i,subscribe:s}=W();return this.player&&(s(t.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),s(t.actionSeek$,this.seekAction$),s(t.inPiP$,o=>{const r=o?T.PIP:H(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),s(t.inFullscreen$,o=>{const r=o?T.FULLSCREEN:H(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),s(t.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(t){const{subscription:i,subscribe:s}=W();return s(t.slotRequested$,()=>this.logAdSlotRequest()),s(t.started$,o=>this.logAdStarted(o)),s(t.paused$,()=>this.logAdPaused()),s(t.resumed$,()=>this.logAdResumed()),s(t.ended$,()=>this.logAdEnded()),s(t.skipped$,()=>this.logAdSkipped()),s(t.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(t){const{subscription:i,subscribe:s}=W();return s(t.click$,o=>this.logInterfaceClick(o)),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}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=Z()}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 i=this.timeSynchronisation?.getOffset()??0,s=t.start+i,o=t.end+i;this.log({operation:"watch_coverage_live",param:`${s}-${o}`})}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"})}logInterfaceClick(t){this.log({operation:"player_interface_click",param:t})}logNextMovie(t){this.log({operation:"next_movie",param:String(t)})}subscribe(){this.resubscribeBeforeunload();const t=window.navigator.connection;t&&"onchange"in t&&"effectiveType"in t&&this.subscription.add(O(M(t,"change"),ht(["init"])).subscribe(()=>this.updateContext({network:At(t.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=M(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){if(this.config.disabledOperations.includes(t.operation))return;const i=this.createLogItem(t);this.logger.log(i)}createLogItem({operation:t,param:i,time:s}){const o=this.timeSynchronisation?.now()??l(),r=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,a=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?C.AUTO:this.statContext.autoplay===!1?C.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:r,connection_reused:a===!0?E.YES:a===!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.isEmbed?this.embedParent:this.statContext.refUrl,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const h of this.config.disabledCustomFields)delete u[h];return{operation:t,type:1,time:s,network:this.statContext.network,timestamp:o,custom:u}}}export{b as ApiEnv,$ as ConnectionType,d as ContentType,Y as InteractiveInterfaceClick,Nt as OneStat,p as Quality,I as SeekAction,X as VERSION};
|
|
6
|
+
import{fillWithDefault as st,ValueSubject as K,safeStorage as A,getExponentialDelay as it,ErrorCategory as m,now as l,assertNever as tt,Observable as ot,Subscription as R,merge as O,fromEvent as M,filterChanged as nt,map as rt,filter as z,Subject as et,isNullable as V,isNonNullable as w,once as at,combine as q,observableFrom as ht}from"@vkontakte/videoplayer-shared/esnext.esm.js";import Q from"lodash/debounce.js";import{Surface as v,VideoQuality as S,HttpConnectionType as B,VideoFormat as c,PlaybackState as G}from"@vkontakte/videoplayer-core/esnext.esm.js";var b;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(b||(b={}));var p;(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"})(p||(p={}));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 C;(function(e){e.AUTO="auto",e.MANUAL=""})(C||(C={}));var $;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})($||($={}));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 T;(function(e){e.PIP="pip",e.FULLSCREEN="fullscreen",e.EXTERNAL="external",e.PREFETCH="prefetch"})(T||(T={}));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={}));var Y;(function(e){e.GRAPH_SHOW="iGraphShow",e.GRAPH_HIDE="iGraphHide",e.NEXT_AREA="iNextChapterArea",e.NEXT_BUTTON="iNextChapterBtn",e.WATCH_AGAIN="iWatchAgainBtn"})(Y||(Y={}));const ut={apiEnv:b.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ct=e=>st(e,ut);function dt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,t[o]=e[o===19?s&3|8:s]);return t.join("")}const X="1.0.40-beta.1",lt="CIOPGQJGDIHBABABA",j={[b.PROD]:"https://api.ok.ru",[b.VK_ALIAS]:"https://api.mycdn.me",[b.VIDEOTEST]:"https://videotestapi.ok.ru/api",[b.TEST]:"https://apitest.ok.ru",[b.AUTO]:""},ft="_one-stat_",U=`${ft}uuid`;var _;(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"})(_||(_={}));class pt{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new K(!1);backoffTimeoutId;constructor(t){this.params=t;const i=A.get(U);i?i.startsWith('"')&&i.endsWith('"')?(this.uuid=i.replaceAll('"',""),A.set(U,this.uuid)):this.uuid=i:(this.uuid=dt(),A.set(U,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(t)}async logRequest(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const r=async(a,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,s,o)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:m.NETWORK,message:`Unknown ${i} error`,thrown:h});return}const g=h?.error_code;switch(g){case _.PARAM_SESSION_EXPIRED:case _.PARAM_SESSION_KEY:case _.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(a,u-1):void 0;case _.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(a,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${g}`,category:m.EXTERNAL_API,message:`${i} error`,data:h});return}}}};return r(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:${X}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=it(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:m.NETWORK,message:"Otherwise unhandled error in authorization",thrown:s})).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",i={session_data:{version:2,device_id:this.uuid,client_version:X.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,i).then(s=>((!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:m.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=s?.session_key??void 0,this.sessionKey)).catch(async s=>{this.sessionKey=void 0;const o=s?.error_code;switch(o){case _.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:m.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:m.NETWORK,message:"authorize error",thrown:s})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class gt{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=j[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==b.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:m.NETWORK,message:"Unhandled resolve api base url error",thrown:t}),j[b.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:i,sessionKey:s}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:m.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:t,params:i}})}return!1}async sendRequest(t,i,s){const o=l(),r=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:m.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:m.NETWORK,message:"Unhandled request error",thrown:a,data:{method:t,params:i,sessionKey:s,time:l()-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:i,sessionKey:s})}).then(a=>{const u=Number(a.headers.get("content-length"))===0,h=new Date(a.headers.get("date")??"").getTime(),g=l()-o;if(isFinite(h)&&this.timeSynchronisation?.addServerTime(h,g),!u)return a.json().then(n=>Object.prototype.hasOwnProperty.call(n,"error_msg")?Promise.reject(n):n,r)},r)}_prepareQueryParams(t){const i=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&i.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const k="onestat_events",F=e=>t=>t.timestamp+e>=l();class mt{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;constructor(t){this.params=t,this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.firstFlush=Q(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const i=A.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=Q(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:i,custom:{param:s}}=t;return["action_stop","close_at_empty_buffer"].includes(i)||i==="watch_coverage_record"&&s==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:m.WTF,message:String(t)??"Unknown logger error",thrown:t})}}readFromStorage(){const t=A.get(k);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(F(this.params.config.storageExpiration));A.set(k,JSON.stringify({...i,[this.userSalt]:[...o,t]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(F(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const t=this.readFromStorage();delete t[this.userSalt],A.set(k,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[i,s]of Object.entries(t)){const o=s.filter(F(this.params.config.storageExpiration));o.length?t[i]=o:delete t[i]}A.set(k,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 i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(t&&this.params.config.useBeacon?this.api.logBeacon(i):this.api.logRequest(i),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 St=()=>{let e,t;try{e=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?e=!0:(e=!1,console.error(s))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!t&&document.referrer&&(t=document.referrer)}catch(s){console.error(s)}const i=t?new URL(t).hostname:void 0;return{isEmbed:e,host:i}},bt=e=>e&&{[S.INVARIANT]:p.UNKNOWN,[S.Q_144P]:p.Q144P,[S.Q_240P]:p.Q240P,[S.Q_360P]:p.Q360P,[S.Q_480P]:p.Q480P,[S.Q_720P]:p.Q720P,[S.Q_1080P]:p.Q1080P,[S.Q_1440P]:p.Q1440P,[S.Q_2160P]:p.Q2160P,[S.Q_4320P]:p.UNKNOWN}[e],J=e=>e&&{[B.HTTP1]:$.HTTP1,[B.HTTP2]:$.HTTP2,[B.QUIC]:$.HTTP3}[e],Et=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 tt(e)}},H=e=>{if(e!==void 0)switch(e){case v.NONE:case v.INLINE:return;case v.FULLSCREEN:return T.FULLSCREEN;case v.SECOND_SCREEN:return T.EXTERNAL;case v.PIP:return T.PIP;default:return tt(e)}},At=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,i){const s=Date.now(),o=t-s-i/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 Z=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Tt=e=>new ot(t=>{const i=new R,s=O(M(window,"beforeunload"),e.events.willDestruct$),o=new K(void 0);let r;i.add(e.info.isLive$.pipe(nt()).subscribe(x=>{r&&(r.unsubscribe(),o.next(void 0)),x?r=e.info.liveTime$.pipe(rt(D=>D&&D/1e3)).subscribe(o):r=e.info.position$.subscribe(o),i.add(r)}));const{playing$:a,paused$:u}=e.events,h=e.events.willSeek$.pipe(z(()=>e.info.playbackState$.getValue()===G.PLAYING)),g=e.events.seeked$.pipe(z(()=>e.info.playbackState$.getValue()===G.PLAYING));let n=!1;const f=new et;i.add(h.subscribe(()=>{n||f.next(),n=!0})),i.add(g.subscribe(()=>n=!1));const P=O(a,g),L=O(u,f,s,e.events.looped$);let N;return i.add(P.subscribe(()=>N=o.getValue())),i.add(L.subscribe(()=>{const x=o.getValue();V(N)||N===x||V(x)||(t.next({from:N,to:x}),N=void 0)})),i}),W=()=>{const e=new R;return{subscription:e,subscribe:(t,i)=>{t&&e.add(t.subscribe(i))}}};class Nt{api;logger;config;subscription=new R;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=Z();isEmbed;embedParent;uiEvents;player;seekAction$=new K(I.UNKNOWN);constructor(t,i){this.statContext=t,this.config=ct(i.config??{}),w(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new _t);const s=new et;this.experimental={error$:s};const o=new gt({apiKey:lt,config:this.config,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new pt({config:this.config,apiTransport:o,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:s}),this.logger=new mt({config:this.config,api:this.api,error$:s,userSalt:i.userSalt});const{isEmbed:r,host:a}=St();this.isEmbed=r,this.embedParent=a,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const i=new R,s=(n,f)=>i.add(n.subscribe(f));s(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),s(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),s(t.events.willResume$,()=>{this.logPlay()}),s(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),s(Tt(t),n=>{const f=t.info.isLive$.getValue(),P={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};f?this.logWatchCoverageLive(P):this.logWatchCoverageRecord(P)});let o;s(t.info.isStalled$,n=>{n?o=l():(w(o)&&this.logEmptyBuffer({duration:l()-o}),o=void 0)});let r=!1;i.add(t.events.fatalError$.pipe(at()).subscribe(()=>r=!0)),s(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const f=w(o)?l()-o:void 0;this.logCloseAtEmptyBuffer({duration:f??0}),o=void 0}else r||this.logActionStop()}),s(t.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),s(t.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let a,u,h=!1;s(t.events.firstBytes$,n=>{a=l(),this.logFirstBytes({time:n})}),s(t.events.willStart$,()=>u=l()),s(t.info.currentBuffer$,n=>{!h&&n&&n.end-n.start>0&&w(a)&&(this.logPlayerReady({duration:l()-a}),h=!0)}),s(t.events.firstFrame$,()=>{w(a)&&!h&&(this.logPlayerReady({duration:l()-a}),h=!0),w(u)&&this.logFirstFrame({time:l()-u})}),s(t.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),s(q({muted:t.info.muted$,volume:t.info.volume$}),({muted:n,volume:f})=>this.updateContext({audible:!n&&f>0})),s(t.info.currentQuality$,n=>this.updateContext({quality:bt(n)})),s(t.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),s(t.info.currentFormat$,n=>this.updateContext({contentType:Et(n)}));let g;return s(t.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:g!==void 0&&g!==n}),g=n}),s(t.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),s(t.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:J(n)}),this.updateContext({connectionType:J(n)})}),s(t.info.httpConnectionReused$,n=>{V(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),s(t.info.surface$,n=>this.updateContext({mode:H(n)})),s(q({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:n,available:f})=>{const P=f.find(({id:L})=>L===n);this.updateContext({subtitles:P?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(t){this.uiEvents=t;const{subscription:i,subscribe:s}=W();return this.player&&(s(t.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),s(t.actionSeek$,this.seekAction$),s(t.inPiP$,o=>{const r=o?T.PIP:H(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),s(t.inFullscreen$,o=>{const r=o?T.FULLSCREEN:H(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),s(t.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(t){const{subscription:i,subscribe:s}=W();return s(t.slotRequested$,()=>this.logAdSlotRequest()),s(t.started$,o=>this.logAdStarted(o)),s(t.paused$,()=>this.logAdPaused()),s(t.resumed$,()=>this.logAdResumed()),s(t.ended$,()=>this.logAdEnded()),s(t.skipped$,()=>this.logAdSkipped()),s(t.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(t){const{subscription:i,subscribe:s}=W();return s(t.click$,o=>this.logInterfaceClick(o)),s(t.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}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=Z()}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 i=this.timeSynchronisation?.getOffset()??0,s=t.start+i,o=t.end+i;this.log({operation:"watch_coverage_live",param:`${s}-${o}`})}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"})}logInterfaceClick(t){this.log({operation:"player_interface_click",param:t})}logNextMovie(t){this.log({operation:"next_movie",param:String(t)})}subscribe(){this.resubscribeBeforeunload();const t=window.navigator.connection;t&&"onchange"in t&&"effectiveType"in t&&this.subscription.add(O(M(t,"change"),ht(["init"])).subscribe(()=>this.updateContext({network:At(t.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=M(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){if(this.config.disabledOperations.includes(t.operation))return;const i=this.createLogItem(t);this.logger.log(i)}createLogItem({operation:t,param:i,time:s}){const o=this.timeSynchronisation?.now()??l(),r=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,a=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?C.AUTO:this.statContext.autoplay===!1?C.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:r,connection_reused:a===!0?E.YES:a===!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.isEmbed?this.embedParent:this.statContext.refUrl,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const h of this.config.disabledCustomFields)delete u[h];return{operation:t,type:1,time:s,network:this.statContext.network,timestamp:o,custom:u}}}export{b as ApiEnv,$ as ConnectionType,d as ContentType,Y as InteractiveInterfaceClick,Nt as OneStat,p as Quality,I as SeekAction,X as VERSION};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vkontakte/videoplayer-statistics",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.40-beta.1",
|
|
4
4
|
"author": "vk.com",
|
|
5
5
|
"description": "Statistics library for vk.com videoplayer",
|
|
6
6
|
"homepage": "https://vk.com",
|
|
@@ -49,10 +49,10 @@
|
|
|
49
49
|
"**/*.d.ts"
|
|
50
50
|
],
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@vkontakte/videoplayer-shared": "
|
|
52
|
+
"@vkontakte/videoplayer-shared": "1.0.29-beta.1",
|
|
53
53
|
"lodash": "4.17.21"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@vkontakte/videoplayer-core": "
|
|
56
|
+
"@vkontakte/videoplayer-core": "2.0.90-beta.2"
|
|
57
57
|
}
|
|
58
58
|
}
|