@vkontakte/videoplayer-statistics 1.0.38 → 1.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/evergreen.esm.js +4 -4
- package/index.d.ts +18 -17
- package/package.json +1 -1
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.39
|
|
3
|
+
* Tue, 29 Aug 2023 12:33:55 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-39/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{fillWithDefault as nt,ValueSubject as q,safeStorage as w,getExponentialDelay as at,ErrorCategory as m,now as p,assertNever as st,Observable as ct,Subscription as v,merge as C,fromEvent as H,filterChanged as ut,map as ht,filter as B,isNullable as W,isNonNullable as P,Subject as lt,once as dt,combine as K,observableFrom as ft}from"@vkontakte/videoplayer-shared/esnext.esm.js";import z from"lodash/debounce.js";import{Surface as x,VideoQuality as S,HttpConnectionType as F,VideoFormat as d,PlaybackState as Q}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 $;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})($||($={}));var A;(function(e){e[e.YES=1]="YES",e[e.NO=0]="NO"})(A||(A={}));var N;(function(e){e.EXCELLENT="excellent",e.GOOD="good",e.POOR="poor"})(N||(N={}));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 G;(function(e){e.GRAPH_SHOW="iGraphShow",e.GRAPH_HIDE="iGraphHide",e.NEXT_AREA="iNextChapterArea",e.NEXT_BUTTON="iNextChapterBtn",e.WATCH_AGAIN="iWatchAgainBtn"})(G||(G={}));const pt={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}},gt=e=>nt(e,pt);function bt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let s=0,i,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(s<=2&&(s=33554432+Math.random()*16777216|0),i=s&15,s=s>>4,t[o]=e[o===19?i&3|8:i]);return t.join("")}const j="1.0.38",mt="CIOPGQJGDIHBABABA",Y={[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]:""},St="_one-stat_",X=`${St}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 Et{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new q(!1);backoffTimeoutId;constructor(t){this.params=t;const s=w.get(X);s?this.uuid=String(s):(this.uuid=bt(),w.set(X,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(s,i,o)||this.logRequest(t)}async logRequest(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const n=async(a,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,i,o)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:m.NETWORK,message:`Unknown ${s} error`,thrown:c});return}const u=c?.error_code;switch(u){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#${u}`,category:m.EXTERNAL_API,message:`${s} 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:${j}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=at(this.consequentAuthErrors,this.params.config.backoff);return new Promise(s=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(s).catch(i=>this.params.error$.next({id:"AuthorizeBackoff",category:m.NETWORK,message:"Otherwise unhandled error in authorization",thrown:i})).finally(()=>this.backoffTimeoutId=0)},t))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const t="auth.anonymLogin",s={session_data:{version:2,device_id:this.uuid,client_version:j.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(s.session_data.auth_token=this.authToken,s.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,s).then(i=>((!i||!i.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:m.EXTERNAL_API,message:"No session key",data:i}),this.sessionKey=i?.session_key??void 0,this.sessionKey)).catch(async i=>{this.sessionKey=void 0;const o=i?.error_code;switch(o){case y.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:i}):this.params.error$.next({id:"AuthorizeUnknown",category:m.NETWORK,message:"authorize error",thrown:i})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class J{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(t,s,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:s,options:i})}removeEventListener(t,s){if(!(t in this.listeners))return;const i=this.listeners[t];for(let o=0,n=i.length;o<n;o++)if(i[o].callback===s){i.splice(o,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const i=this.listeners[t.type].slice();for(let o=0,n=i.length;o<n;o++){const a=i[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 it extends J{constructor(){super(),this.listeners||J.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 At{constructor(){Object.defineProperty(this,"signal",{value:new it,writable:!0,configurable:!0})}abort(t){let s;try{s=new Event("abort")}catch{typeof document<"u"?document.createEvent?(s=document.createEvent("Event"),s.initEvent("abort",!1,!1)):(s=document.createEventObject(),s.type="abort"):s={type:"abort",bubbles:!1,cancelable:!1}}let i=t;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(s)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(At.prototype[Symbol.toStringTag]="AbortController",it.prototype[Symbol.toStringTag]="AbortSignal");function ot(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 _t(e){typeof e=="function"&&(e={fetch:e});const{fetch:t,Request:s=t.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=e;if(!ot({fetch:t,Request:s,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:t,Request:n};let n=s;(n&&!n.prototype.hasOwnProperty("signal")||o)&&(n=function(u,r){let h;r&&r.signal&&(h=r.signal,delete r.signal);const b=new s(u,r);return h&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),b},n.prototype=s.prototype);const a=t;return{fetch:(c,u)=>{const r=n&&n.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(r){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(r.aborted)return Promise.reject(h);const b=new Promise((O,_)=>{r.addEventListener("abort",()=>_(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([b,a(c,u)])}return a(c,u)},Request:n}}const V=ot({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rt=V?_t({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Z=V?rt.fetch:window.fetch;V?rt.Request:window.Request;class wt{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=Y[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 Z(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}),Y[E.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,s,i){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:s,sessionKey:i}),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:m.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:t,params:s}})}return!1}async sendRequest(t,s,i){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: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:s,sessionKey:i,time:p()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),Z(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:s,sessionKey:i})}).then(a=>{const l=Number(a.headers.get("content-length"))===0,c=new Date(a.headers.get("date")??"").getTime(),u=p()-o;if(isFinite(c)&&this.timeSynchronisation?.addServerTime(c,u),!l)return a.json().then(r=>Object.prototype.hasOwnProperty.call(r,"error_msg")?Promise.reject(r):r,n)},n)}_prepareQueryParams(t){const s=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&s.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([i,o])=>s.append(i,typeof o=="string"?o:JSON.stringify(o))),s}}const k="onestat_events",U=e=>t=>t.timestamp+e>=p();class yt{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=z(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const s=w.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=z(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:s}),this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:s,custom:{param:i}}=t;return["action_stop","close_at_empty_buffer"].includes(s)||s==="watch_coverage_record"&&i==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:m.WTF,message:String(t)??"Unknown logger error",thrown:t})}}readFromStorage(){const t=w.get(k);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const s=this.readFromStorage(),o=(s[this.userSalt]??[]).filter(U(this.params.config.storageExpiration));w.set(k,JSON.stringify({...s,[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],w.set(k,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[s,i]of Object.entries(t)){const o=i.filter(U(this.params.config.storageExpiration));o.length?t[s]=o:delete t[s]}w.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 s=this.getFromStorage();s.length!==0&&(this.api.authorized$.getValue()?(t&&this.params.config.useBeacon?this.api.logBeacon(s):this.api.logRequest(s),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const Tt=()=>{let e,t;try{e=window.self!==window.top}catch(i){i instanceof DOMException&&i.name==="SecurityError"?e=!0:(e=!1,console.error(i))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(i){console.error(i)}try{!t&&document.referrer&&(t=document.referrer)}catch(i){console.error(i)}const s=t?new URL(t).hostname:void 0;return{isEmbed:e,host:s}},Pt=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],tt=e=>e&&{[F.HTTP1]:$.HTTP1,[F.HTTP2]:$.HTTP2,[F.QUIC]:$.HTTP3}[e],vt=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 st(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 st(e)}},Nt=e=>{switch(e){case"slow-2g":return N.POOR;case"2g":return N.POOR;case"3g":return N.GOOD;case"4g":return N.EXCELLENT}};class Ot{offset=void 0;constructor(t){this.offset=t}getOffset(){return this.offset??0}setOffset(t){this.offset=t}now(){return Date.now()+(this.offset??0)}date(t=new Date){return t.setTime(t.getTime()+(this.offset??0)),t}addServerTime(t,s){const i=Date.now(),o=t-i-s/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const et=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Rt=e=>new ct(t=>{const s=new v,i=C(H(window,"beforeunload"),e.events.willDestruct$),o=new q(void 0);let n;s.add(e.info.isLive$.pipe(ut()).subscribe(R=>{n&&(n.unsubscribe(),o.next(void 0)),R?n=e.info.liveTime$.pipe(ht(D=>D&&D/1e3)).subscribe(o):n=e.info.position$.subscribe(o),s.add(n)}));const{playing$:a,paused$:l}=e.events,c=e.events.willSeek$.pipe(B(()=>e.info.playbackState$.getValue()===Q.PLAYING)),u=e.events.seeked$.pipe(B(()=>e.info.playbackState$.getValue()===Q.PLAYING));let r=!1;s.add(c.subscribe(()=>r=!0)),s.add(u.subscribe(()=>r=!1));const h=c.pipe(B(()=>!r)),b=C(a,u),O=C(l,h,i,e.events.looped$);let _;return s.add(b.subscribe(()=>_=o.getValue())),s.add(O.subscribe(()=>{const R=o.getValue();W(_)||_===R||W(R)||(t.next({from:_,to:R}),_=void 0)})),s});class Ct{api;logger;config;subscription=new v;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=et();isEmbed;embedParent;uiEvents;player;seekAction$=new q(I.UNKNOWN);constructor(t,s){this.statContext=t,this.config=gt(s.config??{}),P(s.apiEnv)&&(this.config.apiEnv=s.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Ot);const i=new lt;this.experimental={error$:i};const o=new wt({apiKey:mt,config:this.config,error$:i,timeSynchronisation:this.timeSynchronisation});this.api=new Et({config:this.config,apiTransport:o,refreshAuthToken:s.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:i}),this.logger=new yt({config:this.config,api:this.api,error$:i,userSalt:s.userSalt});const{isEmbed:n,host:a}=Tt();this.isEmbed=n,this.embedParent=a,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const s=new v,i=(r,h)=>s.add(r.subscribe(h));i(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),i(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),i(t.events.willResume$,()=>{this.logPlay()}),i(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),i(Rt(t),r=>{const h=t.info.isLive$.getValue(),b={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};h?this.logWatchCoverageLive(b):this.logWatchCoverageRecord(b)});let o;i(t.info.isStalled$,r=>{r?o=p():(P(o)&&this.logEmptyBuffer({duration:p()-o}),o=void 0)});let n=!1;s.add(t.events.fatalError$.pipe(dt()).subscribe(()=>n=!0)),i(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const h=P(o)?p()-o:void 0;this.logCloseAtEmptyBuffer({duration:h??0}),o=void 0}else n||this.logActionStop()}),i(t.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),i(t.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let a,l,c=!1;i(t.events.firstBytes$,r=>{a=p(),this.logFirstBytes({time:r})}),i(t.events.willStart$,()=>l=p()),i(t.info.currentBuffer$,r=>{!c&&r&&r.end-r.start>0&&P(a)&&(this.logPlayerReady({duration:p()-a}),c=!0)}),i(t.events.firstFrame$,()=>{P(a)&&!c&&(this.logPlayerReady({duration:p()-a}),c=!0),P(l)&&this.logFirstFrame({time:p()-l})}),i(t.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),i(K({muted:t.info.muted$,volume:t.info.volume$}),({muted:r,volume:h})=>this.updateContext({audible:!r&&h>0})),i(t.info.currentQuality$,r=>this.updateContext({quality:Pt(r)})),i(t.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),i(t.info.currentFormat$,r=>this.updateContext({contentType:vt(r)}));let u;return i(t.info.hostname$,r=>{this.updateContext({cdnHostname:r,failover:u!==void 0&&u!==r}),u=r}),i(t.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),i(t.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:tt(r)}),this.updateContext({connectionType:tt(r)})}),i(t.info.httpConnectionReused$,r=>{W(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),i(t.info.surface$,r=>this.updateContext({mode:M(r)})),i(K({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:r,available:h})=>{const b=h.find(({id:O})=>O===r);this.updateContext({subtitles:b?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToUi(t){this.uiEvents=t;const s=new v;return this.player&&(s.add(t.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),s.add(t.actionSeek$.subscribe(this.seekAction$)),s.add(t.inPiP$.subscribe(i=>{const o=i?T.PIP:M(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.inFullscreen$.subscribe(i=>{const o=i?T.FULLSCREEN:M(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.actionSetSubtitle$.subscribe(i=>{this.updateContext({subtitles:i})})),s.add(t.nextMovie$.subscribe(i=>this.logNextMovie(i))),this.resubscribeBeforeunload(),this.subscription.add(s)),s}attachToAds(t){const s=new v;return s.add(t.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(t.started$.subscribe(i=>this.logAdStarted(i))).add(t.paused$.subscribe(()=>this.logAdPaused())).add(t.resumed$.subscribe(()=>this.logAdResumed())).add(t.ended$.subscribe(()=>this.logAdEnded())).add(t.skipped$.subscribe(()=>this.logAdSkipped())).add(t.clicked$.subscribe(()=>this.logAdClicked())),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToInteractive(t){const s=new v;return s.add(t.click$.subscribe(i=>this.logInterfaceClick(i))).add(t.nextMovie$.subscribe(i=>this.logNextMovie(i))),this.resubscribeBeforeunload(),this.subscription.add(s),s}authorize(t){return this.api.authorize(t)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=et()}setFieldBlacklist(){}logInited(){}logReady(t){this.log({operation:"player_ready",param:String(t.time)})}logStarted(...t){this.logActionPlay(...t)}logPlay(){this.log({operation:"play_toggle"})}logPause(t){this.log({operation:"pause",param:String(Math.round(t.position))})}logSeek(t){this.log({operation:"seek",param:t.action,time:t.time})}logFirstBytes(t){this.log({operation:"first_bytes",param:String(t.time)})}logFirstFrame(t){this.log({operation:"first_frame",param:String(t.time)})}logError(t){this.log({operation:"content_error",param:`${t.fatal?"fatal":"recoverable"}_${t.errorType}`})}logWatchCoverageRecord(t){this.log({operation:"watch_coverage_record",param:`${t.start}-${t.end}`})}logWatchCoverageLive(t){const s=this.timeSynchronisation?.getOffset()??0,i=t.start+s,o=t.end+s;this.log({operation:"watch_coverage_live",param:`${i}-${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(C(H(t,"change"),ft(["init"])).subscribe(()=>this.updateContext({network:Nt(t.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=H(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 s=this.createLogItem(t);this.logger.log(s)}createLogItem({operation:t,param:s,time:i}){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:s,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.embedParent,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:i,network:this.statContext.network,timestamp:o,custom:l}}}export{E as ApiEnv,$ as ConnectionType,f as ContentType,G as InteractiveInterfaceClick,Ct as OneStat,g as Quality,I as SeekAction,j 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.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};
|
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.39
|
|
3
|
+
* Tue, 29 Aug 2023 12:33:55 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-39/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{fillWithDefault as tt,ValueSubject as V,safeStorage as _,getExponentialDelay as et,ErrorCategory as m,now as l,assertNever as Z,Observable as st,Subscription as y,merge as R,fromEvent as M,filterChanged as it,map as ot,filter as B,isNullable as W,isNonNullable as w,Subject as nt,once as rt,combine as K,observableFrom as at}from"@vkontakte/videoplayer-shared/esnext.esm.js";import z from"lodash/debounce.js";import{Surface as $,VideoQuality as b,HttpConnectionType as U,VideoFormat as c,PlaybackState as q}from"@vkontakte/videoplayer-core/esnext.esm.js";var S;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(S||(S={}));var f;(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"})(f||(f={}));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 k;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})(k||(k={}));var E;(function(e){e[e.YES=1]="YES",e[e.NO=0]="NO"})(E||(E={}));var N;(function(e){e.EXCELLENT="excellent",e.GOOD="good",e.POOR="poor"})(N||(N={}));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 Q;(function(e){e.GRAPH_SHOW="iGraphShow",e.GRAPH_HIDE="iGraphHide",e.NEXT_AREA="iNextChapterArea",e.NEXT_BUTTON="iNextChapterBtn",e.WATCH_AGAIN="iWatchAgainBtn"})(Q||(Q={}));const ht={apiEnv:S.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}},ut=e=>tt(e,ht);function ct(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let s=0,i,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(s<=2&&(s=33554432+Math.random()*16777216|0),i=s&15,s=s>>4,t[o]=e[o===19?i&3|8:i]);return t.join("")}const G="1.0.38",dt="CIOPGQJGDIHBABABA",Y={[S.PROD]:"https://api.ok.ru",[S.VK_ALIAS]:"https://api.mycdn.me",[S.VIDEOTEST]:"https://videotestapi.ok.ru/api",[S.TEST]:"https://apitest.ok.ru",[S.AUTO]:""},lt="_one-stat_",X=`${lt}uuid`;var A;(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"})(A||(A={}));class ft{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new V(!1);backoffTimeoutId;constructor(t){this.params=t;const s=_.get(X);s?this.uuid=String(s):(this.uuid=ct(),_.set(X,this.uuid))}async authorize(t){return this.authToken=t??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(s,i,o)||this.logRequest(t)}async logRequest(t){const s="log.externalLog",i=this.createLogParams(t),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const a=async(r,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,i,o)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:m.NETWORK,message:`Unknown ${s} error`,thrown:h});return}const p=h?.error_code;switch(p){case A.PARAM_SESSION_EXPIRED:case A.PARAM_SESSION_KEY:case A.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?a(r,u-1):void 0;case A.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?a(r,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:m.EXTERNAL_API,message:`${s} error`,data:h});return}}}};return a(t)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(t){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${G}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=et(this.consequentAuthErrors,this.params.config.backoff);return new Promise(s=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(s).catch(i=>this.params.error$.next({id:"AuthorizeBackoff",category:m.NETWORK,message:"Otherwise unhandled error in authorization",thrown:i})).finally(()=>this.backoffTimeoutId=0)},t))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const t="auth.anonymLogin",s={session_data:{version:2,device_id:this.uuid,client_version:G.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(s.session_data.auth_token=this.authToken,s.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,s).then(i=>((!i||!i.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:m.EXTERNAL_API,message:"No session key",data:i}),this.sessionKey=i?.session_key??void 0,this.sessionKey)).catch(async i=>{this.sessionKey=void 0;const o=i?.error_code;switch(o){case A.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:i}):this.params.error$.next({id:"AuthorizeUnknown",category:m.NETWORK,message:"authorize error",thrown:i})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class pt{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=Y[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==S.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}),Y[S.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,s,i){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:s,sessionKey:i}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(r){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:m.NETWORK,message:"Unhandled beacon error",thrown:r,data:{method:t,params:s}})}return!1}async sendRequest(t,s,i){const o=l(),a=r=>{if(r instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(r.message)){this.params.error$.next({id:"Network",category:m.NETWORK,message:"Request failed",thrown:r});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:m.NETWORK,message:"Unhandled request error",thrown:r,data:{method:t,params:s,sessionKey:i,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:s,sessionKey:i})}).then(r=>{const u=Number(r.headers.get("content-length"))===0,h=new Date(r.headers.get("date")??"").getTime(),p=l()-o;if(isFinite(h)&&this.timeSynchronisation?.addServerTime(h,p),!u)return r.json().then(n=>Object.prototype.hasOwnProperty.call(n,"error_msg")?Promise.reject(n):n,a)},a)}_prepareQueryParams(t){const s=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&s.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([i,o])=>s.append(i,typeof o=="string"?o:JSON.stringify(o))),s}}const O="onestat_events",F=e=>t=>t.timestamp+e>=l();class gt{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=z(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const s=_.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=z(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:s}),this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=t=>{const{operation:s,custom:{param:i}}=t;return["action_stop","close_at_empty_buffer"].includes(s)||s==="watch_coverage_record"&&i==="0-0"};safeFlush(){try{this.flush()}catch(t){this.error$.next({id:"LoggerError",category:m.WTF,message:String(t)??"Unknown logger error",thrown:t})}}readFromStorage(){const t=_.get(O);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(t){if(!this.userSalt){this.unsaltedStorage.push(t);return}const s=this.readFromStorage(),o=(s[this.userSalt]??[]).filter(F(this.params.config.storageExpiration));_.set(O,JSON.stringify({...s,[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],_.set(O,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[s,i]of Object.entries(t)){const o=i.filter(F(this.params.config.storageExpiration));o.length?t[s]=o:delete t[s]}_.set(O,JSON.stringify(t))}log(t){this.addToStorage(t),!this.isPaused&&(this.isUrgent(t)?this.flush():this.lastVsid!==t.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=t.custom.vsid)}flush(t=!1){const s=this.getFromStorage();s.length!==0&&(this.api.authorized$.getValue()?(t&&this.params.config.useBeacon?this.api.logBeacon(s):this.api.logRequest(s),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const mt=()=>{let e,t;try{e=window.self!==window.top}catch(i){i instanceof DOMException&&i.name==="SecurityError"?e=!0:(e=!1,console.error(i))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(i){console.error(i)}try{!t&&document.referrer&&(t=document.referrer)}catch(i){console.error(i)}const s=t?new URL(t).hostname:void 0;return{isEmbed:e,host:s}},bt=e=>e&&{[b.INVARIANT]:f.UNKNOWN,[b.Q_144P]:f.Q144P,[b.Q_240P]:f.Q240P,[b.Q_360P]:f.Q360P,[b.Q_480P]:f.Q480P,[b.Q_720P]:f.Q720P,[b.Q_1080P]:f.Q1080P,[b.Q_1440P]:f.Q1440P,[b.Q_2160P]:f.Q2160P,[b.Q_4320P]:f.UNKNOWN}[e],j=e=>e&&{[U.HTTP1]:k.HTTP1,[U.HTTP2]:k.HTTP2,[U.QUIC]:k.HTTP3}[e],St=e=>{if(e!==void 0)switch(e){case c.MPEG:return d.MP4;case c.DASH:case c.DASH_LIVE:return d.DASH;case c.DASH_SEP:return d.DASH_SEP;case c.DASH_ONDEMAND:return d.ONDEMAND_DASH;case c.DASH_WEBM:case c.DASH_LIVE_WEBM:return d.WEBM;case c.DASH_WEBM_AV1:return d.AV1;case c.DASH_LIVE_CMAF:return d.ONDEMAND_DASH_LIVE;case c.HLS:case c.HLS_LIVE:return d.HLS;case c.HLS_ONDEMAND:return d.ONDEMAND_HLS;case c.HLS_LIVE_CMAF:return d.ONDEMAND_HLS_LIVE;case c.WEB_RTC_LIVE:return d.WEBRTC;default:return Z(e)}},H=e=>{if(e!==void 0)switch(e){case $.NONE:case $.INLINE:return;case $.FULLSCREEN:return T.FULLSCREEN;case $.SECOND_SCREEN:return T.EXTERNAL;case $.PIP:return T.PIP;default:return Z(e)}},Et=e=>{switch(e){case"slow-2g":return N.POOR;case"2g":return N.POOR;case"3g":return N.GOOD;case"4g":return N.EXCELLENT}};class _t{offset=void 0;constructor(t){this.offset=t}getOffset(){return this.offset??0}setOffset(t){this.offset=t}now(){return Date.now()+(this.offset??0)}date(t=new Date){return t.setTime(t.getTime()+(this.offset??0)),t}addServerTime(t,s){const i=Date.now(),o=t-i-s/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const J=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),At=e=>new st(t=>{const s=new y,i=R(M(window,"beforeunload"),e.events.willDestruct$),o=new V(void 0);let a;s.add(e.info.isLive$.pipe(it()).subscribe(x=>{a&&(a.unsubscribe(),o.next(void 0)),x?a=e.info.liveTime$.pipe(ot(D=>D&&D/1e3)).subscribe(o):a=e.info.position$.subscribe(o),s.add(a)}));const{playing$:r,paused$:u}=e.events,h=e.events.willSeek$.pipe(B(()=>e.info.playbackState$.getValue()===q.PLAYING)),p=e.events.seeked$.pipe(B(()=>e.info.playbackState$.getValue()===q.PLAYING));let n=!1;s.add(h.subscribe(()=>n=!0)),s.add(p.subscribe(()=>n=!1));const g=h.pipe(B(()=>!n)),P=R(r,p),L=R(u,g,i,e.events.looped$);let v;return s.add(P.subscribe(()=>v=o.getValue())),s.add(L.subscribe(()=>{const x=o.getValue();W(v)||v===x||W(x)||(t.next({from:v,to:x}),v=void 0)})),s});class yt{api;logger;config;subscription=new y;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=J();isEmbed;embedParent;uiEvents;player;seekAction$=new V(I.UNKNOWN);constructor(t,s){this.statContext=t,this.config=ut(s.config??{}),w(s.apiEnv)&&(this.config.apiEnv=s.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new _t);const i=new nt;this.experimental={error$:i};const o=new pt({apiKey:dt,config:this.config,error$:i,timeSynchronisation:this.timeSynchronisation});this.api=new ft({config:this.config,apiTransport:o,refreshAuthToken:s.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:i}),this.logger=new gt({config:this.config,api:this.api,error$:i,userSalt:s.userSalt});const{isEmbed:a,host:r}=mt();this.isEmbed=a,this.embedParent=r,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const s=new y,i=(n,g)=>s.add(n.subscribe(g));i(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),i(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),i(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),i(t.events.willResume$,()=>{this.logPlay()}),i(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),i(At(t),n=>{const g=t.info.isLive$.getValue(),P={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};g?this.logWatchCoverageLive(P):this.logWatchCoverageRecord(P)});let o;i(t.info.isStalled$,n=>{n?o=l():(w(o)&&this.logEmptyBuffer({duration:l()-o}),o=void 0)});let a=!1;s.add(t.events.fatalError$.pipe(rt()).subscribe(()=>a=!0)),i(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const g=w(o)?l()-o:void 0;this.logCloseAtEmptyBuffer({duration:g??0}),o=void 0}else a||this.logActionStop()}),i(t.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),i(t.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let r,u,h=!1;i(t.events.firstBytes$,n=>{r=l(),this.logFirstBytes({time:n})}),i(t.events.willStart$,()=>u=l()),i(t.info.currentBuffer$,n=>{!h&&n&&n.end-n.start>0&&w(r)&&(this.logPlayerReady({duration:l()-r}),h=!0)}),i(t.events.firstFrame$,()=>{w(r)&&!h&&(this.logPlayerReady({duration:l()-r}),h=!0),w(u)&&this.logFirstFrame({time:l()-u})}),i(t.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),i(K({muted:t.info.muted$,volume:t.info.volume$}),({muted:n,volume:g})=>this.updateContext({audible:!n&&g>0})),i(t.info.currentQuality$,n=>this.updateContext({quality:bt(n)})),i(t.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),i(t.info.currentFormat$,n=>this.updateContext({contentType:St(n)}));let p;return i(t.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:p!==void 0&&p!==n}),p=n}),i(t.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),i(t.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:j(n)}),this.updateContext({connectionType:j(n)})}),i(t.info.httpConnectionReused$,n=>{W(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),i(t.info.surface$,n=>this.updateContext({mode:H(n)})),i(K({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:n,available:g})=>{const P=g.find(({id:L})=>L===n);this.updateContext({subtitles:P?.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToUi(t){this.uiEvents=t;const s=new y;return this.player&&(s.add(t.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),s.add(t.actionSeek$.subscribe(this.seekAction$)),s.add(t.inPiP$.subscribe(i=>{const o=i?T.PIP:H(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.inFullscreen$.subscribe(i=>{const o=i?T.FULLSCREEN:H(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),s.add(t.actionSetSubtitle$.subscribe(i=>{this.updateContext({subtitles:i})})),s.add(t.nextMovie$.subscribe(i=>this.logNextMovie(i))),this.resubscribeBeforeunload(),this.subscription.add(s)),s}attachToAds(t){const s=new y;return s.add(t.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(t.started$.subscribe(i=>this.logAdStarted(i))).add(t.paused$.subscribe(()=>this.logAdPaused())).add(t.resumed$.subscribe(()=>this.logAdResumed())).add(t.ended$.subscribe(()=>this.logAdEnded())).add(t.skipped$.subscribe(()=>this.logAdSkipped())).add(t.clicked$.subscribe(()=>this.logAdClicked())),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToInteractive(t){const s=new y;return s.add(t.click$.subscribe(i=>this.logInterfaceClick(i))).add(t.nextMovie$.subscribe(i=>this.logNextMovie(i))),this.resubscribeBeforeunload(),this.subscription.add(s),s}authorize(t){return this.api.authorize(t)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=J()}setFieldBlacklist(){}logInited(){}logReady(t){this.log({operation:"player_ready",param:String(t.time)})}logStarted(...t){this.logActionPlay(...t)}logPlay(){this.log({operation:"play_toggle"})}logPause(t){this.log({operation:"pause",param:String(Math.round(t.position))})}logSeek(t){this.log({operation:"seek",param:t.action,time:t.time})}logFirstBytes(t){this.log({operation:"first_bytes",param:String(t.time)})}logFirstFrame(t){this.log({operation:"first_frame",param:String(t.time)})}logError(t){this.log({operation:"content_error",param:`${t.fatal?"fatal":"recoverable"}_${t.errorType}`})}logWatchCoverageRecord(t){this.log({operation:"watch_coverage_record",param:`${t.start}-${t.end}`})}logWatchCoverageLive(t){const s=this.timeSynchronisation?.getOffset()??0,i=t.start+s,o=t.end+s;this.log({operation:"watch_coverage_live",param:`${i}-${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(R(M(t,"change"),at(["init"])).subscribe(()=>this.updateContext({network:Et(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 s=this.createLogItem(t);this.logger.log(s)}createLogItem({operation:t,param:s,time:i}){const o=this.timeSynchronisation?.now()??l(),a=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,r=this.statContext.firstConnectionReused,u={vsid:this.vsid,vid:this.statContext.movieId,ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?C.AUTO:this.statContext.autoplay===!1?C.MANUAL:void 0,param:s,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:a,connection_reused:r===!0?E.YES:r===!1?E.NO:void 0,cached_data:this.statContext.cached===!0?E.YES:this.statContext.cached===!1?E.NO:void 0,live:this.statContext.liveEdge?E.YES:void 0,muted:this.statContext.audible===!1?E.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:E.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const h of this.config.disabledCustomFields)delete u[h];return{operation:t,type:1,time:i,network:this.statContext.network,timestamp:o,custom:u}}}export{S as ApiEnv,k as ConnectionType,d as ContentType,Q as InteractiveInterfaceClick,yt as OneStat,f as Quality,I as SeekAction,G 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.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};
|
package/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Kbps, RecursivePartial, Milliseconds, IObservable, ISubscription, IError, Seconds
|
|
1
|
+
import { Kbps, RecursivePartial, Milliseconds, IObservable, ISubscription, IError, Seconds } from '@vkontakte/videoplayer-shared';
|
|
2
2
|
import { IPlayer } from '@vkontakte/videoplayer-core';
|
|
3
3
|
|
|
4
4
|
type Operation = 'action_play' | 'first_bytes' | 'player_ready' | 'first_frame' | 'seek' | 'watch_coverage_record' | 'watch_coverage_live' | 'empty_buffer' | 'action_stop' | 'close_at_empty_buffer' | 'content_error' | 'player_interface_click' | 'next_movie' | 'play_toggle' | 'pause' | 'adv';
|
|
@@ -129,25 +129,25 @@ interface IConfig {
|
|
|
129
129
|
type IOptionalConfig = RecursivePartial<IConfig>;
|
|
130
130
|
|
|
131
131
|
interface IUIEvents {
|
|
132
|
-
actionRewind
|
|
133
|
-
actionSeek
|
|
134
|
-
inPiP
|
|
135
|
-
inFullscreen
|
|
136
|
-
actionSetSubtitle
|
|
137
|
-
nextMovie
|
|
132
|
+
actionRewind$?: IObservable<void>;
|
|
133
|
+
actionSeek$?: IObservable<SeekAction>;
|
|
134
|
+
inPiP$?: IObservable<boolean>;
|
|
135
|
+
inFullscreen$?: IObservable<boolean>;
|
|
136
|
+
actionSetSubtitle$?: IObservable<string>;
|
|
137
|
+
nextMovie$?: IObservable<number>;
|
|
138
138
|
}
|
|
139
139
|
interface IAdsEvents {
|
|
140
|
-
slotRequested
|
|
141
|
-
started
|
|
142
|
-
paused
|
|
143
|
-
resumed
|
|
144
|
-
ended
|
|
145
|
-
skipped
|
|
146
|
-
clicked
|
|
140
|
+
slotRequested$?: IObservable<void>;
|
|
141
|
+
started$?: IObservable<string>;
|
|
142
|
+
paused$?: IObservable<void>;
|
|
143
|
+
resumed$?: IObservable<void>;
|
|
144
|
+
ended$?: IObservable<void>;
|
|
145
|
+
skipped$?: IObservable<void>;
|
|
146
|
+
clicked$?: IObservable<void>;
|
|
147
147
|
}
|
|
148
148
|
interface IInteractiveEvents {
|
|
149
|
-
click
|
|
150
|
-
nextMovie
|
|
149
|
+
click$?: IObservable<InteractiveInterfaceClick>;
|
|
150
|
+
nextMovie$?: IObservable<number>;
|
|
151
151
|
}
|
|
152
152
|
|
|
153
153
|
interface IOneStat {
|
|
@@ -359,6 +359,7 @@ interface IStatContext {
|
|
|
359
359
|
albumId?: string;
|
|
360
360
|
vkPlaylistId?: string;
|
|
361
361
|
trackCode?: string;
|
|
362
|
+
refUrl?: string;
|
|
362
363
|
place?: string;
|
|
363
364
|
cdnHostname?: string;
|
|
364
365
|
downloadSpeed?: Kbps;
|
|
@@ -403,7 +404,7 @@ declare class OneStat implements IOneStat {
|
|
|
403
404
|
constructor(statContext: IStatContext, params: IConstructorParams);
|
|
404
405
|
updateContext(newContext: Partial<IStatContext>): void;
|
|
405
406
|
attachTo(player: IPlayer): ISubscription;
|
|
406
|
-
attachToUi(events: IUIEvents):
|
|
407
|
+
attachToUi(events: IUIEvents): ISubscription;
|
|
407
408
|
attachToAds(adsEvents: IAdsEvents): ISubscription;
|
|
408
409
|
attachToInteractive(interactiveEvents: IInteractiveEvents): ISubscription;
|
|
409
410
|
authorize(authToken?: string): Promise<unknown>;
|