@vkontakte/videoplayer-statistics 1.0.34 → 1.0.35-dev.f578f79.0
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 +151 -53
- package/package.json +3 -3
package/es2018.cjs.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.35-dev.f578f79.0
|
|
3
|
+
* Wed, 10 May 2023 11:40:54 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-35/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var a=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),n=require("@vkontakte/videoplayer-core/es2018.cjs.js"),I=require("lodash/debounce.js");const A="_one-stat_",g=(()=>{try{const t=Date.now().toString(),e=window.localStorage;e.setItem(t,t);const o=e.getItem(t)===t;return e.removeItem(t),o?e:null}catch(t){return null}})();function x(t){const e=g?g.getItem(A+t):null;if(e===null)return null;try{return JSON.parse(e)}catch(o){return null}}function $(t,e){try{g&&g.setItem(A+t,JSON.stringify(e))}catch(o){}}function q(t){g&&g.removeItem(A+t)}var _={get(t){return x(t)||null},set(t,e){$(t,e)},remove(t){q(t)}};function B(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let o=0,s,r;for(r=0;r<36;r++)r===8||r===13||r===18||r===23?e[r]="-":r===14?e[r]="4":(o<=2&&(o=33554432+Math.random()*16777216|0),s=o&15,o=o>>4,e[r]=t[r===19?s&3|8:s]);return e.join("")}exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="144",t.Q240P="240",t.Q360P="360",t.Q480P="480",t.Q720P="720",t.Q1080P="1080",t.Q1440P="1440",t.Q2160P="2160",t.Q4320P="4320",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ScreenDestination=void 0;(function(t){t.CHROMECAST="chromecast",t.APPLE_TV="appletv",t.PIP="pip",t.HEADPHONES="externalHeadphones",t.SCREEN=""})(exports.ScreenDestination||(exports.ScreenDestination={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.RTMP="rtmp",t.UNKNOWN="unknown"})(exports.ContentType||(exports.ContentType={}));var y;(function(t){t.AUTO="auto",t.MANUAL=""})(y||(y={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var b;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(b||(b={}));const v="1.0.34",Q="es2018.cjs.js",F="CIOPGQJGDIHBABABA",P={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},D={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var p;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(p||(p={}));class H{constructor(e){this.consequentAuthErrors=0,this.authorized$=new a.ValueSubject(!1),this.params=e;const o=_.get("uuid");o?this.uuid=String(o):(this.uuid=B(),_.set("uuid",this.uuid))}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const o="log.externalLog",s=this.createLogParams(e),r=this.sessionKey;if(!r)return;this.params.apiTransport.sendBeacon(o,s,r)||this.logRequest(e)}async logRequest(e){var o;const s="log.externalLog",r=this.createLogParams(e),i=(o=this.sessionKey)!==null&&o!==void 0?o:await this._authorizeWithBackoff();if(!i)return;const u=async(f,l=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,r,i)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:a.ErrorCategory.NETWORK,message:`Unknown ${s} error`,thrown:h});return}const c=h==null?void 0:h.error_code;switch(c){case p.PARAM_SESSION_EXPIRED:case p.PARAM_SESSION_KEY:case p.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?u(f,l-1):void 0;case p.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?u(f,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${c}`,category:a.ErrorCategory.EXTERNAL_API,message:`${s} error`,data:h});return}}}};return u(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${Q}:${v}`,platform:"WEB",items:e.map(o=>({...o,time:0,type:1}))})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=a.getExponentialDelay(this.consequentAuthErrors,D);return new Promise(o=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(o).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:a.ErrorCategory.NETWORK,message:"Otherwise unhandle errror in authrization",thrown:s})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",o={session_data:{version:2,device_id:this.uuid,client_version:v.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(o.session_data.auth_token=this.authToken,o.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,o).then(s=>{var r;return(!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:a.ErrorCategory.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=(r=s==null?void 0:s.session_key)!==null&&r!==void 0?r:void 0,this.sessionKey}).catch(async s=>{this.sessionKey=void 0;const r=s==null?void 0:s.error_code;switch(r){case p.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}r?this.params.error$.next({id:`Authorize#${r}`,category:a.ErrorCategory.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:a.ErrorCategory.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 S{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,o,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:o,options:s})}removeEventListener(e,o){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,i=s.length;r<i;r++)if(s[r].callback===o){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,i=s.length;r<i;r++){const u=s[r];try{u.callback.call(this,e)}catch(f){Promise.resolve().then(()=>{throw f})}u.options&&u.options.once&&this.removeEventListener(e.type,u.callback)}return!e.defaultPrevented}}class O extends S{constructor(){super(),this.listeners||S.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class U{constructor(){Object.defineProperty(this,"signal",{value:new O,writable:!0,configurable:!0})}abort(e){let o;try{o=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(o=document.createEvent("Event"),o.initEvent("abort",!1,!1)):(o=document.createEventObject(),o.type="abort"):o={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(o)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(U.prototype[Symbol.toStringTag]="AbortController",O.prototype[Symbol.toStringTag]="AbortSignal");function R(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function V(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:o=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=t;if(!R({fetch:e,Request:o,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:i};let i=o;(i&&!i.prototype.hasOwnProperty("signal")||r)&&(i=function(h,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);const m=new o(h,c);return d&&Object.defineProperty(m,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),m},i.prototype=o.prototype);const u=e;return{fetch:(l,h)=>{const c=i&&i.prototype.isPrototypeOf(l)?l.signal:h?h.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(k){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);const m=new Promise((k,L)=>{c.addEventListener("abort",()=>L(d),{once:!0})});return h&&h.signal&&delete h.signal,Promise.race([m,u(l,h)])}return u(l,h)},Request:i}}const E=R({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),C=E?V({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,w=E?C.fetch:window.fetch;E?C.Request:window.Request;class M{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const o=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),r=await(await w(o,{method:"GET",mode:"cors",cache:"no-cache"})).json(),i=(e=r==null?void 0:r.Answer[0])===null||e===void 0?void 0:e.data;if(!i)throw new Error("Wrong DNS response");return i}catch(o){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:a.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:o}),P[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,o,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const r=this._prepareQueryParams({method:e,queryParams:o,sessionKey:s}),i=new window.Blob([r.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:a.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:o}})}return!1}async sendRequest(e,o,s){const r=a.now(),i=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:a.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:a.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:o,sessionKey:s,time:a.now()-r}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),w(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:o,sessionKey:s})}).then(u=>{var f;const l=Number(u.headers.get("content-length"))===0,h=new Date((f=u.headers.get("date"))!==null&&f!==void 0?f:"").getTime(),c=a.now()-r;if(isFinite(h)&&this.timeSynchronisation.addServerTime(h,c),!l)return u.json().then(d=>Object.prototype.hasOwnProperty.call(d,"error_msg")?Promise.reject(d):d,i)},i)}_prepareQueryParams(e){const o=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&o.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([s,r])=>o.append(s,typeof r=="string"?r:JSON.stringify(r))),o}}const N=3e3,K=N*5;class W{constructor(e){this.requestQueue=[],this.isPaused=!1,this.debouncedFlush=I(()=>{var o;try{this.flush()}catch(s){this.error$.next({id:"LoggerError",category:a.ErrorCategory.WTF,message:(o=String(s))!==null&&o!==void 0?o:"Unknown logger error",thrown:s})}},N,{maxWait:K}),this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(o=>{o&&this.debouncedFlush()})}log(e){this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}class z{constructor(e){this.offset=void 0,this.offset=e}getOffset(){var e;return(e=this.offset)!==null&&e!==void 0?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!==null&&e!==void 0?e:0)}date(e=new Date){var o;return e.setTime(e.getTime()+((o=this.offset)!==null&&o!==void 0?o:0)),e}addServerTime(e,o){const s=Date.now(),r=e-s-o/2;if(Math.abs(r)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(r):this.offset=Math.round(.2*r+(1-.2)*this.offset)}}const T=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),j=t=>t&&{[n.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[n.VideoQuality.Q_144P]:exports.Quality.Q144P,[n.VideoQuality.Q_240P]:exports.Quality.Q240P,[n.VideoQuality.Q_360P]:exports.Quality.Q360P,[n.VideoQuality.Q_480P]:exports.Quality.Q480P,[n.VideoQuality.Q_720P]:exports.Quality.Q720P,[n.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[n.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[n.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[n.VideoQuality.Q_4320P]:exports.Quality.Q4320P}[t],G=t=>t&&{[n.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[n.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[n.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],Y=t=>{if(t!==void 0)switch(t){case n.VideoFormat.MPEG:return exports.ContentType.MP4;case n.VideoFormat.DASH:case n.VideoFormat.DASH_LIVE:case n.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.DASH;case n.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case n.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case n.VideoFormat.DASH_WEBM:case n.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case n.VideoFormat.HLS:case n.VideoFormat.HLS_LIVE:case n.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.HLS;case n.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case n.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.RTMP;default:return a.assertNever(t)}};class J{constructor(e,o){var s;this.subscription=new a.Subscription,this.timeSynchronisation=new z,this.vsid=T(),this.fieldBlacklist=[],this.statContext=e,this.config={...(s=o.config)!==null&&s!==void 0?s:{},requestRetryCount:1};const r=new a.Subject;this.experimental={error$:r};const i=new M({apiKey:F,apiBaseUrl:P[o.apiEnv],apiEnv:o.apiEnv,error$:r,timeSynchronisation:this.timeSynchronisation});this.api=new H({apiTransport:i,refreshAuthToken:o.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,error$:r}),this.logger=new W({api:this.api,error$:r}),this.subscription.add(a.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)))}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let o;return new a.Subscription().add(e.events.started$.subscribe(()=>{this.logStarted({position:e.info.position$.getValue()})})).add(e.events.looped$.subscribe(()=>{this.resetViewSession(),this.logStarted({position:e.info.position$.getValue()})})).add(e.events.seeked$.subscribe(()=>{this.logSeek()})).add(e.events.willPause$.subscribe(()=>{this.logPause({position:e.info.position$.getValue()})})).add(e.events.willResume$.subscribe(()=>{this.logPlay()})).add(e.events.managedError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.fatalError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.inited$.subscribe(()=>{this.logInited()})).add(e.events.canplay$.subscribe(s=>{this.logReady({time:s})})).add(e.events.firstBytes$.subscribe(s=>{this.logFirstBytes({time:s})})).add(e.events.firstFrame$.subscribe(s=>{this.logFirstFrame({time:s})})).add(e.events.watchCoverageRecord$.subscribe(s=>{this.logWatchCoverageRecord(s)})).add(e.events.watchCoverageLive$.subscribe(s=>{this.logWatchCoverageLive(s)})).add(e.info.isStalled$.subscribe(s=>{s?o=a.now():(a.isNonNullable(o)&&this.logEmptyBuffer({duration:a.now()-o}),o=void 0)})).add(e.events.ended$.subscribe(()=>{const s=e.info.throughputEstimation$.getValue();a.isNonNullable(s)&&this.logDownloadSpeed({speed:s/8})})).add(e.info.hostname$.subscribe(s=>{this.updateContext({cdnHostname:s})})).add(e.info.httpConnectionType$.subscribe(s=>{this.updateContext({connectionType:G(s)})})).add(e.info.httpConnectionReused$.subscribe(s=>{this.updateContext({connectionReused:s})})).add(e.info.currentQuality$.subscribe(s=>{this.updateContext({quality:j(s)})})).add(e.info.currentFormat$.subscribe(s=>{this.updateContext({contentType:Y(s)})})).add(e.info.chromecastState$.subscribe(s=>{this.updateContext({destination:s===n.ChromecastState.CONNECTED?exports.ScreenDestination.CHROMECAST:exports.ScreenDestination.SCREEN})}))}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=T()}setFieldBlacklist(e=[]){this.fieldBlacklist=e}logInited(){this.log({operation:"init"})}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(e){this.log({operation:"play",param:String(Math.round(e.position))})}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(){this.log({operation:"seek"})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"error",param:e.errorType})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`}),this.logger.flush(!0)}logWatchCoverageLive(e){const o=e.start+this.timeSynchronisation.getOffset(),s=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${o}-${s}`}),this.logger.flush(!0)}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(e){this.log({operation:"download_speed",param:String(e.speed)})}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}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"})}log(e){const o=this.createLogItem(e);this.logger.log(o)}createLogItem({operation:e,param:o}){const s=this.timeSynchronisation.now(),r={vsid:this.vsid,vid:this.statContext.movieId,quality:this.statContext.quality,dst:this.statContext.destination,ct:this.statContext.contentType,aid:this.statContext.albumId,place:this.statContext.place,cdn_host:this.statContext.cdnHostname,connection_type:this.statContext.connectionType,connection_reused:this.statContext.connectionReused===!0?b.YES:this.statContext.connectionReused===!1?b.NO:void 0,stat_type:this.statContext.autoplay===!0?y.AUTO:this.statContext.autoplay===!1?y.MANUAL:void 0,vk_playlist_id:this.statContext.vkPlaylistId,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode};o!==void 0&&(r.param=o);for(const i of this.fieldBlacklist)delete r[i];return{operation:e,timestamp:s,custom:r}}}exports.OneStat=J;
|
|
6
|
+
"use strict";var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),I=require("lodash/debounce.js"),c=require("@vkontakte/videoplayer-core/es2018.cjs.js");function D(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let i=0,o,s;for(s=0;s<36;s++)s===8||s===13||s===18||s===23?e[s]="-":s===14?e[s]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),o=i&15,i=i>>4,e[s]=t[s===19?o&3|8:o]);return e.join("")}exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(exports.ContentType||(exports.ContentType={}));var _;(function(t){t.AUTO="auto",t.MANUAL=""})(_||(_={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var b;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(b||(b={}));var y;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(y||(y={}));var E;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(E||(E={}));exports.SeekAction=void 0;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(exports.SeekAction||(exports.SeekAction={}));const v="1.0.35-dev.f578f79.0",V="es2018.cjs.js",U="CIOPGQJGDIHBABABA",R={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},q="_one-stat_",T=`${q}uuid`,B={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var m;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(m||(m={}));class F{constructor(e){this.consequentAuthErrors=0,this.authorized$=new r.ValueSubject(!1),this.params=e;const i=r.safeStorage.get(T);i?this.uuid=String(i):(this.uuid=D(),r.safeStorage.set(T,this.uuid))}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const i="log.externalLog",o=this.createLogParams(e),s=this.sessionKey;if(!s)return;this.params.apiTransport.sendBeacon(i,o,s)||this.logRequest(e)}async logRequest(e){var i;const o="log.externalLog",s=this.createLogParams(e),a=(i=this.sessionKey)!==null&&i!==void 0?i:await this._authorizeWithBackoff();if(!a)return;const u=async(f,h=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(o,s,a)}catch(d){if(!d||!("error_code"in d)){this.params.error$.next({id:"logRequestUnknown",category:r.ErrorCategory.NETWORK,message:`Unknown ${o} error`,thrown:d});return}const n=d==null?void 0:d.error_code;switch(n){case m.PARAM_SESSION_EXPIRED:case m.PARAM_SESSION_KEY:case m.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),h>0?u(f,h-1):void 0;case m.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),h>0?u(f,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${n}`,category:r.ErrorCategory.EXTERNAL_API,message:`${o} error`,data:d});return}}}};return u(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${V}:${v}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=r.getExponentialDelay(this.consequentAuthErrors,B);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(o=>this.params.error$.next({id:"AuthorizeBackoff",category:r.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:o})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",i={session_data:{version:2,device_id:this.uuid,client_version:v.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(e,i).then(o=>{var s;return(!o||!o.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:r.ErrorCategory.EXTERNAL_API,message:"No session key",data:o}),this.sessionKey=(s=o==null?void 0:o.session_key)!==null&&s!==void 0?s:void 0,this.sessionKey}).catch(async o=>{this.sessionKey=void 0;const s=o==null?void 0:o.error_code;switch(s){case m.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}s?this.params.error$.next({id:`Authorize#${s}`,category:r.ErrorCategory.EXTERNAL_API,message:"authorize error",data:o}):this.params.error$.next({id:"AuthorizeUnknown",category:r.ErrorCategory.NETWORK,message:"authorize error",thrown:o})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class P{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,i,o){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:i,options:o})}removeEventListener(e,i){if(!(e in this.listeners))return;const o=this.listeners[e];for(let s=0,a=o.length;s<a;s++)if(o[s].callback===i){o.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const o=this.listeners[e.type].slice();for(let s=0,a=o.length;s<a;s++){const u=o[s];try{u.callback.call(this,e)}catch(f){Promise.resolve().then(()=>{throw f})}u.options&&u.options.once&&this.removeEventListener(e.type,u.callback)}return!e.defaultPrevented}}class $ extends P{constructor(){super(),this.listeners||P.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Q{constructor(){Object.defineProperty(this,"signal",{value:new $,writable:!0,configurable:!0})}abort(e){let i;try{i=new Event("abort")}catch(s){typeof document!="undefined"?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 o=e;if(o===void 0)if(typeof document=="undefined")o=new Error("This operation was aborted"),o.name="AbortError";else try{o=new DOMException("signal is aborted without reason")}catch(s){o=new Error("This operation was aborted"),o.name="AbortError"}this.signal.reason=o,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(Q.prototype[Symbol.toStringTag]="AbortController",$.prototype[Symbol.toStringTag]="AbortSignal");function L(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function H(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=t;if(!L({fetch:e,Request:i,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty("signal")||s)&&(a=function(d,n){let l;n&&n.signal&&(l=n.signal,delete n.signal);const p=new i(d,n);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},a.prototype=i.prototype);const u=e;return{fetch:(h,d)=>{const n=a&&a.prototype.isPrototypeOf(h)?h.signal:d?d.signal:void 0;if(n){let l;try{l=new DOMException("Aborted","AbortError")}catch(g){l=new Error("Aborted"),l.name="AbortError"}if(n.aborted)return Promise.reject(l);const p=new Promise((g,A)=>{n.addEventListener("abort",()=>A(l),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([p,u(h,d)])}return u(h,d)},Request:a}}const w=L({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),k=w?H({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,C=w?k.fetch:window.fetch;w?k.Request:window.Request;class M{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),s=await(await C(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),a=(e=s==null?void 0:s.Answer[0])===null||e===void 0?void 0:e.data;if(!a)throw new Error("Wrong DNS response");return a}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:r.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),R[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,o){if(!window.Blob||!window.navigator.sendBeacon)return!1;const s=this._prepareQueryParams({method:e,queryParams:i,sessionKey:o}),a=new window.Blob([s.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:r.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:i}})}return!1}async sendRequest(e,i,o){const s=r.now(),a=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:r.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:r.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:i,sessionKey:o,time:r.now()-s}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),C(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:o})}).then(u=>{var f;const h=Number(u.headers.get("content-length"))===0,d=new Date((f=u.headers.get("date"))!==null&&f!==void 0?f:"").getTime(),n=r.now()-s;if(isFinite(d)&&this.timeSynchronisation.addServerTime(d,n),!h)return u.json().then(l=>Object.prototype.hasOwnProperty.call(l,"error_msg")?Promise.reject(l):l,a)},a)}_prepareQueryParams(e){const i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([o,s])=>i.append(o,typeof s=="string"?s:JSON.stringify(s))),i}}const x=3e3,W=x*5;class K{constructor(e){this.requestQueue=[],this.isPaused=!1,this.debouncedFlush=I(()=>{var i;try{this.flush()}catch(o){this.error$.next({id:"LoggerError",category:r.ErrorCategory.WTF,message:(i=String(o))!==null&&i!==void 0?i:"Unknown logger error",thrown:o})}},x,{maxWait:W}),this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()})}log(e){console.log(e.operation,e.custom.param,e),this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(console.log("Sending",this.requestQueue.length,"events",this.requestQueue),e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}const z=()=>{let t,e;try{t=window.self!==window.top}catch(o){o instanceof DOMException&&o.name==="SecurityError"?t=!0:(t=!1,console.error(o))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(o){console.error(o)}try{!e&&document.referrer&&(e=document.referrer)}catch(o){console.error(o)}const i=e?new URL(e).hostname:void 0;return{isEmbed:t,host:i}},j=t=>t&&{[c.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[c.VideoQuality.Q_144P]:exports.Quality.Q144P,[c.VideoQuality.Q_240P]:exports.Quality.Q240P,[c.VideoQuality.Q_360P]:exports.Quality.Q360P,[c.VideoQuality.Q_480P]:exports.Quality.Q480P,[c.VideoQuality.Q_720P]:exports.Quality.Q720P,[c.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[c.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[c.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[c.VideoQuality.Q_4320P]:exports.Quality.UNKNOWN}[t],N=t=>t&&{[c.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[c.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[c.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],G=t=>{if(t!==void 0)switch(t){case c.VideoFormat.MPEG:return exports.ContentType.MP4;case c.VideoFormat.DASH:case c.VideoFormat.DASH_LIVE:return exports.ContentType.DASH;case c.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case c.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case c.VideoFormat.DASH_WEBM:case c.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case c.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.ONDEMAND_DASH_LIVE;case c.VideoFormat.HLS:case c.VideoFormat.HLS_LIVE:return exports.ContentType.HLS;case c.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case c.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.ONDEMAND_HLS_LIVE;case c.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.WEBRTC;default:return r.assertNever(t)}},S=t=>{if(t!==void 0)switch(t){case c.Surface.NONE:case c.Surface.INLINE:return;case c.Surface.FULLSCREEN:return E.FULLSCREEN;case c.Surface.SECOND_SCREEN:return E.EXTERNAL;case c.Surface.PIP:return E.PIP;default:return r.assertNever(t)}},Y=t=>{switch(t){case"slow-2g":return y.POOR;case"2g":return y.POOR;case"3g":return y.GOOD;case"4g":return y.EXCELLENT}};class X{constructor(e){this.offset=void 0,this.offset=e}getOffset(){var e;return(e=this.offset)!==null&&e!==void 0?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!==null&&e!==void 0?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!==null&&i!==void 0?i:0)),e}addServerTime(e,i){const o=Date.now(),s=e-o-i/2;if(Math.abs(s)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(s):this.offset=Math.round(.2*s+(1-.2)*this.offset)}}const O=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),J=t=>new r.Observable(e=>{const i=new r.Subscription,o=r.merge(r.fromEvent(window,"beforeunload"),t.events.willDestruct$),s=new r.ValueSubject(void 0);let a;t.info.isLive$.pipe(r.filterChanged()).subscribe(g=>{a&&(a.unsubscribe(),s.next(void 0)),g?a=t.info.liveTime$.pipe(r.map(A=>A&&A/1e3)).subscribe(s):a=t.info.position$.subscribe(s),i.add(a)});const{playing$:u,paused$:f}=t.events,h=t.events.willSeek$.pipe(r.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING)),d=t.events.seeked$.pipe(r.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING)),n=r.merge(u,d),l=r.merge(f,h,o,t.events.looped$);let p;return i.add(n.subscribe(()=>p=s.getValue())),i.add(l.subscribe(()=>{const g=s.getValue();r.isNullable(p)||p===g||r.isNullable(g)||(e.next({from:p,to:g}),p=void 0)})),i});class Z{constructor(e,i){var o,s;this.subscription=new r.Subscription,this.timeSynchronisation=new X,this.vsid=O(),this.seekAction$=new r.ValueSubject(exports.SeekAction.UNKNOWN),this.statContext=e,this.config={...(o=i.config)!==null&&o!==void 0?o:{},requestRetryCount:1};const a=new r.Subject;this.experimental={error$:a};const u=new M({apiKey:U,apiBaseUrl:R[i.apiEnv],apiEnv:i.apiEnv,error$:a,timeSynchronisation:this.timeSynchronisation});this.api=new F({apiTransport:u,refreshAuthToken:i.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,mobile:(s=this.statContext.mobile)!==null&&s!==void 0?s:!1,error$:a}),this.logger=new K({api:this.api,error$:a});const{isEmbed:f,host:h}=z();this.isEmbed=f,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const i=new r.Subscription,o=(n,l)=>i.add(n.subscribe(l));o(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(exports.SeekAction.UNKNOWN)}),o(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),o(e.events.willResume$,()=>{this.logPlay()}),o(e.events.started$,()=>{this.statContext.clip&&(this.logWatchCoverageRecord({start:0,end:0}),this.logger.flush())}),o(J(e),n=>{const l=e.info.isLive$.getValue(),p={start:n.from,end:n.to};l?this.logWatchCoverageLive(p):this.logWatchCoverageRecord(p)});let s;o(e.info.isStalled$,n=>{n?s=r.now():(r.isNonNullable(s)&&this.logEmptyBuffer({duration:r.now()-s}),s=void 0)});let a=!1;i.add(e.events.fatalError$.pipe(r.once()).subscribe(()=>a=!0)),o(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const l=r.isNonNullable(s)?r.now()-s:void 0;this.logCloseAtEmptyBuffer({duration:l!=null?l:0}),s=void 0}else a||this.logActionStop();this.logger.flush()}),o(e.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),o(e.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let u,f,h=!1;o(e.events.firstBytes$,n=>{u=r.now(),this.logFirstBytes({time:n})}),o(e.events.willStart$,()=>f=r.now()),o(e.info.currentBuffer$,n=>{!h&&n&&n.end-n.start>0&&r.isNonNullable(u)&&(this.logPlayerReady({duration:r.now()-u}),h=!0)}),o(e.events.firstFrame$,()=>{r.isNonNullable(u)&&!h&&(this.logPlayerReady({duration:r.now()-u}),h=!0),r.isNonNullable(f)&&this.logFirstFrame({time:r.now()-f})}),o(e.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),o(r.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:n,volume:l})=>this.updateContext({audible:!n&&l>0})),o(e.info.currentQuality$,n=>this.updateContext({quality:j(n)})),o(e.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),o(e.info.currentFormat$,n=>this.updateContext({contentType:G(n)}));let d;return o(e.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:d!==void 0&&d!==n}),d=n}),o(e.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),o(e.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:N(n)}),this.updateContext({connectionType:N(n)})}),o(e.info.httpConnectionReused$,n=>{r.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),o(e.info.surface$,n=>this.updateContext({mode:S(n)})),o(r.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:n,available:l})=>{const p=l.find(({id:g})=>g===n);this.updateContext({subtitles:p==null?void 0:p.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;const i=new r.Subscription;return this.player&&(i.add(e.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),i.add(e.actionSeek$.subscribe(this.seekAction$)),i.add(e.inPiP$.subscribe(o=>{var s;const a=o?E.PIP:S((s=this.player)===null||s===void 0?void 0:s.info.surface$.getValue());this.updateContext({mode:a})})),i.add(e.inFullscreen$.subscribe(o=>{var s;const a=o?E.FULLSCREEN:S((s=this.player)===null||s===void 0?void 0:s.info.surface$.getValue());this.updateContext({mode:a})})),this.subscription.add(i)),i}attachToAds(e){const i=new r.Subscription;return i.add(e.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(e.started$.subscribe(o=>this.logAdStarted(o))).add(e.paused$.subscribe(()=>this.logAdPaused())).add(e.resumed$.subscribe(()=>this.logAdResumed())).add(e.ended$.subscribe(()=>this.logAdEnded())).add(e.skipped$.subscribe(()=>this.logAdSkipped())).add(e.clicked$.subscribe(()=>this.logAdClicked())),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=O()}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){const i=e.start+this.timeSynchronisation.getOffset(),o=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${i}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}subscribe(){this.subscription.add(r.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)));const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).subscribe(()=>this.updateContext({network:Y(e.effectiveType)})))}logPlayerReady(e){this.log({operation:"player_ready",param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:"action_play",param:String(Math.round(e.position))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){const i=this.createLogItem(e);this.logger.log(i)}createLogItem({operation:e,param:i,time:o}){const s=this.timeSynchronisation.now(),a=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,f={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?_.AUTO:this.statContext.autoplay===!1?_.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:a,connection_reused:u===!0?b.YES:u===!1?b.NO:void 0,cached_data:this.statContext.cached===!0?b.YES:this.statContext.cached===!1?b.NO:void 0,live:this.statContext.liveEdge?b.YES:void 0,muted:this.statContext.audible===!1?b.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:b.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};return{operation:e,type:1,time:o,network:this.statContext.network,timestamp:s,custom:f}}}exports.OneStat=Z;
|
package/es2018.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.35-dev.f578f79.0
|
|
3
|
+
* Wed, 10 May 2023 11:40:54 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-35/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as K,getExponentialDelay as Q,ErrorCategory as f,now as E,assertNever as W,Subscription as N,Subject as z,fromEvent as V,isNonNullable as k}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{VideoQuality as p,HttpConnectionType as T,VideoFormat as c,ChromecastState as j}from"@vkontakte/videoplayer-core/es2018.esm.js";import G from"lodash/debounce.js";const R="_one-stat_",_=(()=>{try{const t=Date.now().toString(),e=window.localStorage;e.setItem(t,t);const r=e.getItem(t)===t;return e.removeItem(t),r?e:null}catch(t){return null}})();function Y(t){const e=_?_.getItem(R+t):null;if(e===null)return null;try{return JSON.parse(e)}catch(r){return null}}function J(t,e){try{_&&_.setItem(R+t,JSON.stringify(e))}catch(r){}}function X(t){_&&_.removeItem(R+t)}var L={get(t){return Y(t)||null},set(t,e){J(t,e)},remove(t){X(t)}};function Z(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let r=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(r<=2&&(r=33554432+Math.random()*16777216|0),s=r&15,r=r>>4,e[o]=t[o===19?s&3|8:s]);return e.join("")}var b;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(b||(b={}));var d;(function(t){t.Q144P="144",t.Q240P="240",t.Q360P="360",t.Q480P="480",t.Q720P="720",t.Q1080P="1080",t.Q1440P="1440",t.Q2160P="2160",t.Q4320P="4320",t.UNKNOWN="unknown"})(d||(d={}));var v;(function(t){t.CHROMECAST="chromecast",t.APPLE_TV="appletv",t.PIP="pip",t.HEADPHONES="externalHeadphones",t.SCREEN=""})(v||(v={}));var g;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.RTMP="rtmp",t.UNKNOWN="unknown"})(g||(g={}));var w;(function(t){t.AUTO="auto",t.MANUAL=""})(w||(w={}));var S;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(S||(S={}));var P;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(P||(P={}));const I="1.0.34",ee="es2018.esm.js",te="CIOPGQJGDIHBABABA",B={[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]:""},se={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var A;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(A||(A={}));class re{constructor(e){this.consequentAuthErrors=0,this.authorized$=new K(!1),this.params=e;const r=L.get("uuid");r?this.uuid=String(r):(this.uuid=Z(),L.set("uuid",this.uuid))}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const r="log.externalLog",s=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(r,s,o)||this.logRequest(e)}async logRequest(e){var r;const s="log.externalLog",o=this.createLogParams(e),i=(r=this.sessionKey)!==null&&r!==void 0?r:await this._authorizeWithBackoff();if(!i)return;const n=async(m,l=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,o,i)}catch(a){if(!a||!("error_code"in a)){this.params.error$.next({id:"logRequestUnknown",category:f.NETWORK,message:`Unknown ${s} error`,thrown:a});return}const h=a==null?void 0:a.error_code;switch(h){case A.PARAM_SESSION_EXPIRED:case A.PARAM_SESSION_KEY:case A.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(m,l-1):void 0;case A.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(m,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:f.EXTERNAL_API,message:`${s} error`,data:a});return}}}};return n(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${ee}:${I}`,platform:"WEB",items:e.map(r=>({...r,time:0,type:1}))})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=Q(this.consequentAuthErrors,se);return new Promise(r=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(r).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:f.NETWORK,message:"Otherwise unhandle errror in authrization",thrown:s})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",r={session_data:{version:2,device_id:this.uuid,client_version:I.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(r.session_data.auth_token=this.authToken,r.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,r).then(s=>{var o;return(!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:f.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=(o=s==null?void 0:s.session_key)!==null&&o!==void 0?o:void 0,this.sessionKey}).catch(async s=>{this.sessionKey=void 0;const o=s==null?void 0:s.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:f.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:f.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 C{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,r,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:r,options:s})}removeEventListener(e,r){if(!(e in this.listeners))return;const s=this.listeners[e];for(let o=0,i=s.length;o<i;o++)if(s[o].callback===r){s.splice(o,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let o=0,i=s.length;o<i;o++){const n=s[o];try{n.callback.call(this,e)}catch(m){Promise.resolve().then(()=>{throw m})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class q extends C{constructor(){super(),this.listeners||C.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class oe{constructor(){Object.defineProperty(this,"signal",{value:new q,writable:!0,configurable:!0})}abort(e){let r;try{r=new Event("abort")}catch(o){typeof document!="undefined"?document.createEvent?(r=document.createEvent("Event"),r.initEvent("abort",!1,!1)):(r=document.createEventObject(),r.type="abort"):r={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(o){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(r)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(oe.prototype[Symbol.toStringTag]="AbortController",q.prototype[Symbol.toStringTag]="AbortSignal");function D(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function ie(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:r=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=t;if(!D({fetch:e,Request:r,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:e,Request:i};let i=r;(i&&!i.prototype.hasOwnProperty("signal")||o)&&(i=function(a,h){let u;h&&h.signal&&(u=h.signal,delete h.signal);const y=new r(a,h);return u&&Object.defineProperty(y,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),y},i.prototype=r.prototype);const n=e;return{fetch:(l,a)=>{const h=i&&i.prototype.isPrototypeOf(l)?l.signal:a?a.signal:void 0;if(h){let u;try{u=new DOMException("Aborted","AbortError")}catch(M){u=new Error("Aborted"),u.name="AbortError"}if(h.aborted)return Promise.reject(u);const y=new Promise((M,F)=>{h.addEventListener("abort",()=>F(u),{once:!0})});return a&&a.signal&&delete a.signal,Promise.race([y,n(l,a)])}return n(l,a)},Request:i}}const O=D({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),H=O?ie({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,x=O?H.fetch:window.fetch;O?H.Request:window.Request;class ne{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!==b.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const r=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await x(r,{method:"GET",mode:"cors",cache:"no-cache"})).json(),i=(e=o==null?void 0:o.Answer[0])===null||e===void 0?void 0:e.data;if(!i)throw new Error("Wrong DNS response");return i}catch(r){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:f.NETWORK,message:"Unhandled resolve api base url error",thrown:r}),B[b.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,r,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:e,queryParams:r,sessionKey:s}),i=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:f.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:r}})}return!1}async sendRequest(e,r,s){const o=E(),i=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:f.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:f.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:r,sessionKey:s,time:E()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),x(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:r,sessionKey:s})}).then(n=>{var m;const l=Number(n.headers.get("content-length"))===0,a=new Date((m=n.headers.get("date"))!==null&&m!==void 0?m:"").getTime(),h=E()-o;if(isFinite(a)&&this.timeSynchronisation.addServerTime(a,h),!l)return n.json().then(u=>Object.prototype.hasOwnProperty.call(u,"error_msg")?Promise.reject(u):u,i)},i)}_prepareQueryParams(e){const r=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&r.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([s,o])=>r.append(s,typeof o=="string"?o:JSON.stringify(o))),r}}const U=3e3,ae=U*5;class he{constructor(e){this.requestQueue=[],this.isPaused=!1,this.debouncedFlush=G(()=>{var r;try{this.flush()}catch(s){this.error$.next({id:"LoggerError",category:f.WTF,message:(r=String(s))!==null&&r!==void 0?r:"Unknown logger error",thrown:s})}},U,{maxWait:ae}),this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(r=>{r&&this.debouncedFlush()})}log(e){this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}class ue{constructor(e){this.offset=void 0,this.offset=e}getOffset(){var e;return(e=this.offset)!==null&&e!==void 0?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!==null&&e!==void 0?e:0)}date(e=new Date){var r;return e.setTime(e.getTime()+((r=this.offset)!==null&&r!==void 0?r:0)),e}addServerTime(e,r){const s=Date.now(),o=e-s-r/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 $=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),ce=t=>t&&{[p.INVARIANT]:d.UNKNOWN,[p.Q_144P]:d.Q144P,[p.Q_240P]:d.Q240P,[p.Q_360P]:d.Q360P,[p.Q_480P]:d.Q480P,[p.Q_720P]:d.Q720P,[p.Q_1080P]:d.Q1080P,[p.Q_1440P]:d.Q1440P,[p.Q_2160P]:d.Q2160P,[p.Q_4320P]:d.Q4320P}[t],le=t=>t&&{[T.HTTP1]:S.HTTP1,[T.HTTP2]:S.HTTP2,[T.QUIC]:S.HTTP3}[t],de=t=>{if(t!==void 0)switch(t){case c.MPEG:return g.MP4;case c.DASH:case c.DASH_LIVE:case c.DASH_LIVE_CMAF:return g.DASH;case c.DASH_SEP:return g.DASH_SEP;case c.DASH_ONDEMAND:return g.ONDEMAND_DASH;case c.DASH_WEBM:case c.DASH_LIVE_WEBM:return g.WEBM;case c.HLS:case c.HLS_LIVE:case c.HLS_LIVE_CMAF:return g.HLS;case c.HLS_ONDEMAND:return g.ONDEMAND_HLS;case c.WEB_RTC_LIVE:return g.RTMP;default:return W(t)}};class me{constructor(e,r){var s;this.subscription=new N,this.timeSynchronisation=new ue,this.vsid=$(),this.fieldBlacklist=[],this.statContext=e,this.config={...(s=r.config)!==null&&s!==void 0?s:{},requestRetryCount:1};const o=new z;this.experimental={error$:o};const i=new ne({apiKey:te,apiBaseUrl:B[r.apiEnv],apiEnv:r.apiEnv,error$:o,timeSynchronisation:this.timeSynchronisation});this.api=new re({apiTransport:i,refreshAuthToken:r.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,error$:o}),this.logger=new he({api:this.api,error$:o}),this.subscription.add(V(window,"beforeunload").subscribe(()=>this.logger.flush(!0)))}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let r;return new N().add(e.events.started$.subscribe(()=>{this.logStarted({position:e.info.position$.getValue()})})).add(e.events.looped$.subscribe(()=>{this.resetViewSession(),this.logStarted({position:e.info.position$.getValue()})})).add(e.events.seeked$.subscribe(()=>{this.logSeek()})).add(e.events.willPause$.subscribe(()=>{this.logPause({position:e.info.position$.getValue()})})).add(e.events.willResume$.subscribe(()=>{this.logPlay()})).add(e.events.managedError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.fatalError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.inited$.subscribe(()=>{this.logInited()})).add(e.events.canplay$.subscribe(s=>{this.logReady({time:s})})).add(e.events.firstBytes$.subscribe(s=>{this.logFirstBytes({time:s})})).add(e.events.firstFrame$.subscribe(s=>{this.logFirstFrame({time:s})})).add(e.events.watchCoverageRecord$.subscribe(s=>{this.logWatchCoverageRecord(s)})).add(e.events.watchCoverageLive$.subscribe(s=>{this.logWatchCoverageLive(s)})).add(e.info.isStalled$.subscribe(s=>{s?r=E():(k(r)&&this.logEmptyBuffer({duration:E()-r}),r=void 0)})).add(e.events.ended$.subscribe(()=>{const s=e.info.throughputEstimation$.getValue();k(s)&&this.logDownloadSpeed({speed:s/8})})).add(e.info.hostname$.subscribe(s=>{this.updateContext({cdnHostname:s})})).add(e.info.httpConnectionType$.subscribe(s=>{this.updateContext({connectionType:le(s)})})).add(e.info.httpConnectionReused$.subscribe(s=>{this.updateContext({connectionReused:s})})).add(e.info.currentQuality$.subscribe(s=>{this.updateContext({quality:ce(s)})})).add(e.info.currentFormat$.subscribe(s=>{this.updateContext({contentType:de(s)})})).add(e.info.chromecastState$.subscribe(s=>{this.updateContext({destination:s===j.CONNECTED?v.CHROMECAST:v.SCREEN})}))}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=$()}setFieldBlacklist(e=[]){this.fieldBlacklist=e}logInited(){this.log({operation:"init"})}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(e){this.log({operation:"play",param:String(Math.round(e.position))})}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(){this.log({operation:"seek"})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"error",param:e.errorType})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`}),this.logger.flush(!0)}logWatchCoverageLive(e){const r=e.start+this.timeSynchronisation.getOffset(),s=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${r}-${s}`}),this.logger.flush(!0)}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(e){this.log({operation:"download_speed",param:String(e.speed)})}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}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"})}log(e){const r=this.createLogItem(e);this.logger.log(r)}createLogItem({operation:e,param:r}){const s=this.timeSynchronisation.now(),o={vsid:this.vsid,vid:this.statContext.movieId,quality:this.statContext.quality,dst:this.statContext.destination,ct:this.statContext.contentType,aid:this.statContext.albumId,place:this.statContext.place,cdn_host:this.statContext.cdnHostname,connection_type:this.statContext.connectionType,connection_reused:this.statContext.connectionReused===!0?P.YES:this.statContext.connectionReused===!1?P.NO:void 0,stat_type:this.statContext.autoplay===!0?w.AUTO:this.statContext.autoplay===!1?w.MANUAL:void 0,vk_playlist_id:this.statContext.vkPlaylistId,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode};r!==void 0&&(o.param=r);for(const i of this.fieldBlacklist)delete o[i];return{operation:e,timestamp:s,custom:o}}}export{b as ApiEnv,S as ConnectionType,g as ContentType,me as OneStat,d as Quality,v as ScreenDestination};
|
|
6
|
+
import{ValueSubject as U,safeStorage as q,getExponentialDelay as te,ErrorCategory as b,now as m,assertNever as G,Observable as se,Subscription as R,merge as $,fromEvent as I,filterChanged as ie,map as oe,filter as M,isNullable as D,Subject as ne,once as re,combine as H,observableFrom as ae,isNonNullable as T}from"@vkontakte/videoplayer-shared/es2018.esm.js";import ue from"lodash/debounce.js";import{Surface as O,VideoQuality as E,HttpConnectionType as k,VideoFormat as f,PlaybackState as F}from"@vkontakte/videoplayer-core/es2018.esm.js";function ce(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,e[o]=t[o===19?s&3|8:s]);return e.join("")}var w;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(w||(w={}));var p;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(p||(p={}));var g;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(g||(g={}));var L;(function(t){t.AUTO="auto",t.MANUAL=""})(L||(L={}));var N;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(N||(N={}));var A;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(A||(A={}));var y;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(y||(y={}));var v;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(v||(v={}));var C;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(C||(C={}));const W="1.0.35-dev.f578f79.0",he="es2018.esm.js",de="CIOPGQJGDIHBABABA",Y={[w.PROD]:"https://api.ok.ru",[w.VK_ALIAS]:"https://api.mycdn.me",[w.VIDEOTEST]:"https://videotestapi.ok.ru/api",[w.TEST]:"https://apitest.ok.ru",[w.AUTO]:""},le="_one-stat_",K=`${le}uuid`,fe={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var S;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(S||(S={}));class pe{constructor(e){this.consequentAuthErrors=0,this.authorized$=new U(!1),this.params=e;const i=q.get(K);i?this.uuid=String(i):(this.uuid=ce(),q.set(K,this.uuid))}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const i="log.externalLog",s=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(e)}async logRequest(e){var i;const s="log.externalLog",o=this.createLogParams(e),r=(i=this.sessionKey)!==null&&i!==void 0?i:await this._authorizeWithBackoff();if(!r)return;const a=async(d,h=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,o,r)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:b.NETWORK,message:`Unknown ${s} error`,thrown:c});return}const n=c==null?void 0:c.error_code;switch(n){case S.PARAM_SESSION_EXPIRED:case S.PARAM_SESSION_KEY:case S.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),h>0?a(d,h-1):void 0;case S.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),h>0?a(d,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${n}`,category:b.EXTERNAL_API,message:`${s} error`,data:c});return}}}};return a(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${he}:${W}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=te(this.consequentAuthErrors,fe);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)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",i={session_data:{version:2,device_id:this.uuid,client_version:W.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(e,i).then(s=>{var o;return(!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:b.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=(o=s==null?void 0:s.session_key)!==null&&o!==void 0?o:void 0,this.sessionKey}).catch(async s=>{this.sessionKey=void 0;const o=s==null?void 0:s.error_code;switch(o){case S.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 V{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,i,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:i,options:s})}removeEventListener(e,i){if(!(e in this.listeners))return;const s=this.listeners[e];for(let o=0,r=s.length;o<r;o++)if(s[o].callback===i){s.splice(o,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let o=0,r=s.length;o<r;o++){const a=s[o];try{a.callback.call(this,e)}catch(d){Promise.resolve().then(()=>{throw d})}a.options&&a.options.once&&this.removeEventListener(e.type,a.callback)}return!e.defaultPrevented}}class X extends V{constructor(){super(),this.listeners||V.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class ge{constructor(){Object.defineProperty(this,"signal",{value:new X,writable:!0,configurable:!0})}abort(e){let i;try{i=new Event("abort")}catch(o){typeof document!="undefined"?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=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(o){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(ge.prototype[Symbol.toStringTag]="AbortController",X.prototype[Symbol.toStringTag]="AbortSignal");function J(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function me(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=t;if(!J({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty("signal")||o)&&(r=function(c,n){let u;n&&n.signal&&(u=n.signal,delete n.signal);const l=new i(c,n);return u&&Object.defineProperty(l,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),l},r.prototype=i.prototype);const a=e;return{fetch:(h,c)=>{const n=r&&r.prototype.isPrototypeOf(h)?h.signal:c?c.signal:void 0;if(n){let u;try{u=new DOMException("Aborted","AbortError")}catch(_){u=new Error("Aborted"),u.name="AbortError"}if(n.aborted)return Promise.reject(u);const l=new Promise((_,P)=>{n.addEventListener("abort",()=>P(u),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([l,a(h,c)])}return a(h,c)},Request:r}}const B=J({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Z=B?me({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Q=B?Z.fetch:window.fetch;B?Z.Request:window.Request;class be{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!==w.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await Q(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])===null||e===void 0?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:b.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),Y[w.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:e,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:b.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}async sendRequest(e,i,s){const o=m(),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: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:e,params:i,sessionKey:s,time:m()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),Q(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:s})}).then(a=>{var d;const h=Number(a.headers.get("content-length"))===0,c=new Date((d=a.headers.get("date"))!==null&&d!==void 0?d:"").getTime(),n=m()-o;if(isFinite(c)&&this.timeSynchronisation.addServerTime(c,n),!h)return a.json().then(u=>Object.prototype.hasOwnProperty.call(u,"error_msg")?Promise.reject(u):u,r)},r)}_prepareQueryParams(e){const i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const ee=3e3,Ee=ee*5;class _e{constructor(e){this.requestQueue=[],this.isPaused=!1,this.debouncedFlush=ue(()=>{var i;try{this.flush()}catch(s){this.error$.next({id:"LoggerError",category:b.WTF,message:(i=String(s))!==null&&i!==void 0?i:"Unknown logger error",thrown:s})}},ee,{maxWait:Ee}),this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()})}log(e){console.log(e.operation,e.custom.param,e),this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(console.log("Sending",this.requestQueue.length,"events",this.requestQueue),e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}const Ae=()=>{let t,e;try{t=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?t=!0:(t=!1,console.error(s))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!e&&document.referrer&&(e=document.referrer)}catch(s){console.error(s)}const i=e?new URL(e).hostname:void 0;return{isEmbed:t,host:i}},we=t=>t&&{[E.INVARIANT]:p.UNKNOWN,[E.Q_144P]:p.Q144P,[E.Q_240P]:p.Q240P,[E.Q_360P]:p.Q360P,[E.Q_480P]:p.Q480P,[E.Q_720P]:p.Q720P,[E.Q_1080P]:p.Q1080P,[E.Q_1440P]:p.Q1440P,[E.Q_2160P]:p.Q2160P,[E.Q_4320P]:p.UNKNOWN}[t],z=t=>t&&{[k.HTTP1]:N.HTTP1,[k.HTTP2]:N.HTTP2,[k.QUIC]:N.HTTP3}[t],Se=t=>{if(t!==void 0)switch(t){case f.MPEG:return g.MP4;case f.DASH:case f.DASH_LIVE:return g.DASH;case f.DASH_SEP:return g.DASH_SEP;case f.DASH_ONDEMAND:return g.ONDEMAND_DASH;case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return g.WEBM;case f.DASH_LIVE_CMAF:return g.ONDEMAND_DASH_LIVE;case f.HLS:case f.HLS_LIVE:return g.HLS;case f.HLS_ONDEMAND:return g.ONDEMAND_HLS;case f.HLS_LIVE_CMAF:return g.ONDEMAND_HLS_LIVE;case f.WEB_RTC_LIVE:return g.WEBRTC;default:return G(t)}},x=t=>{if(t!==void 0)switch(t){case O.NONE:case O.INLINE:return;case O.FULLSCREEN:return v.FULLSCREEN;case O.SECOND_SCREEN:return v.EXTERNAL;case O.PIP:return v.PIP;default:return G(t)}},ve=t=>{switch(t){case"slow-2g":return y.POOR;case"2g":return y.POOR;case"3g":return y.GOOD;case"4g":return y.EXCELLENT}};class ye{constructor(e){this.offset=void 0,this.offset=e}getOffset(){var e;return(e=this.offset)!==null&&e!==void 0?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!==null&&e!==void 0?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!==null&&i!==void 0?i:0)),e}addServerTime(e,i){const s=Date.now(),o=e-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 j=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Pe=t=>new se(e=>{const i=new R,s=$(I(window,"beforeunload"),t.events.willDestruct$),o=new U(void 0);let r;t.info.isLive$.pipe(ie()).subscribe(_=>{r&&(r.unsubscribe(),o.next(void 0)),_?r=t.info.liveTime$.pipe(oe(P=>P&&P/1e3)).subscribe(o):r=t.info.position$.subscribe(o),i.add(r)});const{playing$:a,paused$:d}=t.events,h=t.events.willSeek$.pipe(M(()=>t.info.playbackState$.getValue()===F.PLAYING)),c=t.events.seeked$.pipe(M(()=>t.info.playbackState$.getValue()===F.PLAYING)),n=$(a,c),u=$(d,h,s,t.events.looped$);let l;return i.add(n.subscribe(()=>l=o.getValue())),i.add(u.subscribe(()=>{const _=o.getValue();D(l)||l===_||D(_)||(e.next({from:l,to:_}),l=void 0)})),i});class Ne{constructor(e,i){var s,o;this.subscription=new R,this.timeSynchronisation=new ye,this.vsid=j(),this.seekAction$=new U(C.UNKNOWN),this.statContext=e,this.config={...(s=i.config)!==null&&s!==void 0?s:{},requestRetryCount:1};const r=new ne;this.experimental={error$:r};const a=new be({apiKey:de,apiBaseUrl:Y[i.apiEnv],apiEnv:i.apiEnv,error$:r,timeSynchronisation:this.timeSynchronisation});this.api=new pe({apiTransport:a,refreshAuthToken:i.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,mobile:(o=this.statContext.mobile)!==null&&o!==void 0?o:!1,error$:r}),this.logger=new _e({api:this.api,error$:r});const{isEmbed:d,host:h}=Ae();this.isEmbed=d,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const i=new R,s=(n,u)=>i.add(n.subscribe(u));s(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),s(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),s(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(C.UNKNOWN)}),s(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),s(e.events.willResume$,()=>{this.logPlay()}),s(e.events.started$,()=>{this.statContext.clip&&(this.logWatchCoverageRecord({start:0,end:0}),this.logger.flush())}),s(Pe(e),n=>{const u=e.info.isLive$.getValue(),l={start:n.from,end:n.to};u?this.logWatchCoverageLive(l):this.logWatchCoverageRecord(l)});let o;s(e.info.isStalled$,n=>{n?o=m():(T(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(re()).subscribe(()=>r=!0)),s(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const u=T(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:u!=null?u:0}),o=void 0}else r||this.logActionStop();this.logger.flush()}),s(e.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),s(e.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let a,d,h=!1;s(e.events.firstBytes$,n=>{a=m(),this.logFirstBytes({time:n})}),s(e.events.willStart$,()=>d=m()),s(e.info.currentBuffer$,n=>{!h&&n&&n.end-n.start>0&&T(a)&&(this.logPlayerReady({duration:m()-a}),h=!0)}),s(e.events.firstFrame$,()=>{T(a)&&!h&&(this.logPlayerReady({duration:m()-a}),h=!0),T(d)&&this.logFirstFrame({time:m()-d})}),s(e.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),s(H({muted:e.info.muted$,volume:e.info.volume$}),({muted:n,volume:u})=>this.updateContext({audible:!n&&u>0})),s(e.info.currentQuality$,n=>this.updateContext({quality:we(n)})),s(e.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),s(e.info.currentFormat$,n=>this.updateContext({contentType:Se(n)}));let c;return s(e.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:c!==void 0&&c!==n}),c=n}),s(e.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),s(e.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(n)}),this.updateContext({connectionType:z(n)})}),s(e.info.httpConnectionReused$,n=>{D(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),s(e.info.surface$,n=>this.updateContext({mode:x(n)})),s(H({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:n,available:u})=>{const l=u.find(({id:_})=>_===n);this.updateContext({subtitles:l==null?void 0:l.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;const i=new R;return this.player&&(i.add(e.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),i.add(e.actionSeek$.subscribe(this.seekAction$)),i.add(e.inPiP$.subscribe(s=>{var o;const r=s?v.PIP:x((o=this.player)===null||o===void 0?void 0:o.info.surface$.getValue());this.updateContext({mode:r})})),i.add(e.inFullscreen$.subscribe(s=>{var o;const r=s?v.FULLSCREEN:x((o=this.player)===null||o===void 0?void 0:o.info.surface$.getValue());this.updateContext({mode:r})})),this.subscription.add(i)),i}attachToAds(e){const i=new R;return i.add(e.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(e.started$.subscribe(s=>this.logAdStarted(s))).add(e.paused$.subscribe(()=>this.logAdPaused())).add(e.resumed$.subscribe(()=>this.logAdResumed())).add(e.ended$.subscribe(()=>this.logAdEnded())).add(e.skipped$.subscribe(()=>this.logAdSkipped())).add(e.clicked$.subscribe(()=>this.logAdClicked())),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}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(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){const i=e.start+this.timeSynchronisation.getOffset(),s=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${i}-${s}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}subscribe(){this.subscription.add(I(window,"beforeunload").subscribe(()=>this.logger.flush(!0)));const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add($(I(e,"change"),ae(["init"])).subscribe(()=>this.updateContext({network:ve(e.effectiveType)})))}logPlayerReady(e){this.log({operation:"player_ready",param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:"action_play",param:String(Math.round(e.position))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){const i=this.createLogItem(e);this.logger.log(i)}createLogItem({operation:e,param:i,time:s}){const o=this.timeSynchronisation.now(),r=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,a=this.statContext.firstConnectionReused,d={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:r,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};return{operation:e,type:1,time:s,network:this.statContext.network,timestamp:o,custom:d}}}export{w as ApiEnv,N as ConnectionType,g as ContentType,Ne as OneStat,p as Quality,C as SeekAction};
|
package/esnext.cjs.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.35-dev.f578f79.0
|
|
3
|
+
* Wed, 10 May 2023 11:40:54 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-35/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var a=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),i=require("@vkontakte/videoplayer-core/esnext.cjs.js"),L=require("lodash/debounce.js");const A="_one-stat_",g=(()=>{try{const t=Date.now().toString(),e=window.localStorage;e.setItem(t,t);const o=e.getItem(t)===t;return e.removeItem(t),o?e:null}catch{return null}})();function x(t){const e=g?g.getItem(A+t):null;if(e===null)return null;try{return JSON.parse(e)}catch{return null}}function $(t,e){try{g&&g.setItem(A+t,JSON.stringify(e))}catch{}}function B(t){g&&g.removeItem(A+t)}var S={get(t){return x(t)||null},set(t,e){$(t,e)},remove(t){B(t)}};function q(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let o=0,s,r;for(r=0;r<36;r++)r===8||r===13||r===18||r===23?e[r]="-":r===14?e[r]="4":(o<=2&&(o=33554432+Math.random()*16777216|0),s=o&15,o=o>>4,e[r]=t[r===19?s&3|8:s]);return e.join("")}exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="144",t.Q240P="240",t.Q360P="360",t.Q480P="480",t.Q720P="720",t.Q1080P="1080",t.Q1440P="1440",t.Q2160P="2160",t.Q4320P="4320",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ScreenDestination=void 0;(function(t){t.CHROMECAST="chromecast",t.APPLE_TV="appletv",t.PIP="pip",t.HEADPHONES="externalHeadphones",t.SCREEN=""})(exports.ScreenDestination||(exports.ScreenDestination={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.RTMP="rtmp",t.UNKNOWN="unknown"})(exports.ContentType||(exports.ContentType={}));var y;(function(t){t.AUTO="auto",t.MANUAL=""})(y||(y={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var b;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(b||(b={}));const _="1.0.34",Q="esnext.cjs.js",F="CIOPGQJGDIHBABABA",v={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},D={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var p;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(p||(p={}));class H{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new a.ValueSubject(!1);backoffTimeoutId;constructor(e){this.params=e;const o=S.get("uuid");o?this.uuid=String(o):(this.uuid=q(),S.set("uuid",this.uuid))}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const o="log.externalLog",s=this.createLogParams(e),r=this.sessionKey;if(!r)return;this.params.apiTransport.sendBeacon(o,s,r)||this.logRequest(e)}async logRequest(e){const o="log.externalLog",s=this.createLogParams(e),r=this.sessionKey??await this._authorizeWithBackoff();if(!r)return;const n=async(u,l=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(o,s,r)}catch(h){if(!h||!("error_code"in h)){this.params.error$.next({id:"logRequestUnknown",category:a.ErrorCategory.NETWORK,message:`Unknown ${o} error`,thrown:h});return}const c=h?.error_code;switch(c){case p.PARAM_SESSION_EXPIRED:case p.PARAM_SESSION_KEY:case p.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(u,l-1):void 0;case p.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?n(u,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${c}`,category:a.ErrorCategory.EXTERNAL_API,message:`${o} error`,data:h});return}}}};return n(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${Q}:${_}`,platform:"WEB",items:e.map(o=>({...o,time:0,type:1}))})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=a.getExponentialDelay(this.consequentAuthErrors,D);return new Promise(o=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(o).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:a.ErrorCategory.NETWORK,message:"Otherwise unhandle errror in authrization",thrown:s})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",o={session_data:{version:2,device_id:this.uuid,client_version:_.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(o.session_data.auth_token=this.authToken,o.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,o).then(s=>((!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:a.ErrorCategory.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 r=s?.error_code;switch(r){case p.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}r?this.params.error$.next({id:`Authorize#${r}`,category:a.ErrorCategory.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:a.ErrorCategory.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 T{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,o,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:o,options:s})}removeEventListener(e,o){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,n=s.length;r<n;r++)if(s[r].callback===o){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,n=s.length;r<n;r++){const u=s[r];try{u.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}u.options&&u.options.once&&this.removeEventListener(e.type,u.callback)}return!e.defaultPrevented}}class O extends T{constructor(){super(),this.listeners||T.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class U{constructor(){Object.defineProperty(this,"signal",{value:new O,writable:!0,configurable:!0})}abort(e){let o;try{o=new Event("abort")}catch{typeof document<"u"?document.createEvent?(o=document.createEvent("Event"),o.initEvent("abort",!1,!1)):(o=document.createEventObject(),o.type="abort"):o={type:"abort",bubbles:!1,cancelable:!1}}let s=e;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(o)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(U.prototype[Symbol.toStringTag]="AbortController",O.prototype[Symbol.toStringTag]="AbortSignal");function R(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function V(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:o=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=t;if(!R({fetch:e,Request:o,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=o;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(c,d){let f;d&&d.signal&&(f=d.signal,delete d.signal);const m=new o(c,d);return f&&Object.defineProperty(m,"signal",{writable:!1,enumerable:!1,configurable:!0,value:f}),m},n.prototype=o.prototype);const u=e;return{fetch:(h,c)=>{const d=n&&n.prototype.isPrototypeOf(h)?h.signal:c?c.signal:void 0;if(d){let f;try{f=new DOMException("Aborted","AbortError")}catch{f=new Error("Aborted"),f.name="AbortError"}if(d.aborted)return Promise.reject(f);const m=new Promise((k,I)=>{d.addEventListener("abort",()=>I(f),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([m,u(h,c)])}return u(h,c)},Request:n}}const E=R({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),C=E?V({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,w=E?C.fetch:window.fetch;E?C.Request:window.Request;class M{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),r=(await(await w(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!r)throw new Error("Wrong DNS response");return r}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:a.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),v[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,o,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const r=this._prepareQueryParams({method:e,queryParams:o,sessionKey:s}),n=new window.Blob([r.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:a.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:o}})}return!1}async sendRequest(e,o,s){const r=a.now(),n=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:a.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:a.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:o,sessionKey:s,time:a.now()-r}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),w(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:o,sessionKey:s})}).then(u=>{const l=Number(u.headers.get("content-length"))===0,h=new Date(u.headers.get("date")??"").getTime(),c=a.now()-r;if(isFinite(h)&&this.timeSynchronisation.addServerTime(h,c),!l)return u.json().then(d=>Object.prototype.hasOwnProperty.call(d,"error_msg")?Promise.reject(d):d,n)},n)}_prepareQueryParams(e){const o=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&o.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([s,r])=>o.append(s,typeof r=="string"?r:JSON.stringify(r))),o}}const N=3e3,K=N*5;class z{api;error$;requestQueue=[];subscription;isPaused=!1;debouncedFlush=L(()=>{try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:a.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}},N,{maxWait:K});constructor(e){this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(o=>{o&&this.debouncedFlush()})}log(e){this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}class W{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,o){const s=Date.now(),r=e-s-o/2;if(Math.abs(r)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(r):this.offset=Math.round(.2*r+(1-.2)*this.offset)}}const P=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),j=t=>t&&{[i.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[i.VideoQuality.Q_144P]:exports.Quality.Q144P,[i.VideoQuality.Q_240P]:exports.Quality.Q240P,[i.VideoQuality.Q_360P]:exports.Quality.Q360P,[i.VideoQuality.Q_480P]:exports.Quality.Q480P,[i.VideoQuality.Q_720P]:exports.Quality.Q720P,[i.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[i.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[i.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[i.VideoQuality.Q_4320P]:exports.Quality.Q4320P}[t],G=t=>t&&{[i.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[i.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[i.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],Y=t=>{if(t!==void 0)switch(t){case i.VideoFormat.MPEG:return exports.ContentType.MP4;case i.VideoFormat.DASH:case i.VideoFormat.DASH_LIVE:case i.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.DASH;case i.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case i.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case i.VideoFormat.DASH_WEBM:case i.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case i.VideoFormat.HLS:case i.VideoFormat.HLS_LIVE:case i.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.HLS;case i.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case i.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.RTMP;default:return a.assertNever(t)}};class J{api;logger;config;subscription=new a.Subscription;timeSynchronisation=new W;experimental;statContext;vsid=P();fieldBlacklist=[];constructor(e,o){this.statContext=e,this.config={...o.config??{},requestRetryCount:1};const s=new a.Subject;this.experimental={error$:s};const r=new M({apiKey:F,apiBaseUrl:v[o.apiEnv],apiEnv:o.apiEnv,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new H({apiTransport:r,refreshAuthToken:o.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,error$:s}),this.logger=new z({api:this.api,error$:s}),this.subscription.add(a.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)))}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let o;return new a.Subscription().add(e.events.started$.subscribe(()=>{this.logStarted({position:e.info.position$.getValue()})})).add(e.events.looped$.subscribe(()=>{this.resetViewSession(),this.logStarted({position:e.info.position$.getValue()})})).add(e.events.seeked$.subscribe(()=>{this.logSeek()})).add(e.events.willPause$.subscribe(()=>{this.logPause({position:e.info.position$.getValue()})})).add(e.events.willResume$.subscribe(()=>{this.logPlay()})).add(e.events.managedError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.fatalError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.inited$.subscribe(()=>{this.logInited()})).add(e.events.canplay$.subscribe(s=>{this.logReady({time:s})})).add(e.events.firstBytes$.subscribe(s=>{this.logFirstBytes({time:s})})).add(e.events.firstFrame$.subscribe(s=>{this.logFirstFrame({time:s})})).add(e.events.watchCoverageRecord$.subscribe(s=>{this.logWatchCoverageRecord(s)})).add(e.events.watchCoverageLive$.subscribe(s=>{this.logWatchCoverageLive(s)})).add(e.info.isStalled$.subscribe(s=>{s?o=a.now():(a.isNonNullable(o)&&this.logEmptyBuffer({duration:a.now()-o}),o=void 0)})).add(e.events.ended$.subscribe(()=>{const s=e.info.throughputEstimation$.getValue();a.isNonNullable(s)&&this.logDownloadSpeed({speed:s/8})})).add(e.info.hostname$.subscribe(s=>{this.updateContext({cdnHostname:s})})).add(e.info.httpConnectionType$.subscribe(s=>{this.updateContext({connectionType:G(s)})})).add(e.info.httpConnectionReused$.subscribe(s=>{this.updateContext({connectionReused:s})})).add(e.info.currentQuality$.subscribe(s=>{this.updateContext({quality:j(s)})})).add(e.info.currentFormat$.subscribe(s=>{this.updateContext({contentType:Y(s)})})).add(e.info.chromecastState$.subscribe(s=>{this.updateContext({destination:s===i.ChromecastState.CONNECTED?exports.ScreenDestination.CHROMECAST:exports.ScreenDestination.SCREEN})}))}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=P()}setFieldBlacklist(e=[]){this.fieldBlacklist=e}logInited(){this.log({operation:"init"})}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(e){this.log({operation:"play",param:String(Math.round(e.position))})}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(){this.log({operation:"seek"})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"error",param:e.errorType})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`}),this.logger.flush(!0)}logWatchCoverageLive(e){const o=e.start+this.timeSynchronisation.getOffset(),s=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${o}-${s}`}),this.logger.flush(!0)}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(e){this.log({operation:"download_speed",param:String(e.speed)})}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}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"})}log(e){const o=this.createLogItem(e);this.logger.log(o)}createLogItem({operation:e,param:o}){const s=this.timeSynchronisation.now(),r={vsid:this.vsid,vid:this.statContext.movieId,quality:this.statContext.quality,dst:this.statContext.destination,ct:this.statContext.contentType,aid:this.statContext.albumId,place:this.statContext.place,cdn_host:this.statContext.cdnHostname,connection_type:this.statContext.connectionType,connection_reused:this.statContext.connectionReused===!0?b.YES:this.statContext.connectionReused===!1?b.NO:void 0,stat_type:this.statContext.autoplay===!0?y.AUTO:this.statContext.autoplay===!1?y.MANUAL:void 0,vk_playlist_id:this.statContext.vkPlaylistId,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode};o!==void 0&&(r.param=o);for(const n of this.fieldBlacklist)delete r[n];return{operation:e,timestamp:s,custom:r}}}exports.OneStat=J;
|
|
6
|
+
"use strict";var n=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),I=require("lodash/debounce.js"),c=require("@vkontakte/videoplayer-core/esnext.cjs.js");function D(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let i=0,o,s;for(s=0;s<36;s++)s===8||s===13||s===18||s===23?e[s]="-":s===14?e[s]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),o=i&15,i=i>>4,e[s]=t[s===19?o&3|8:o]);return e.join("")}exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(exports.ContentType||(exports.ContentType={}));var S;(function(t){t.AUTO="auto",t.MANUAL=""})(S||(S={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var m;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(m||(m={}));var y;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(y||(y={}));var E;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(E||(E={}));exports.SeekAction=void 0;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(exports.SeekAction||(exports.SeekAction={}));const T="1.0.35-dev.f578f79.0",U="esnext.cjs.js",B="CIOPGQJGDIHBABABA",R={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},V="_one-stat_",P=`${V}uuid`,q={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var b;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(b||(b={}));class F{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new n.ValueSubject(!1);backoffTimeoutId;constructor(e){this.params=e;const i=n.safeStorage.get(P);i?this.uuid=String(i):(this.uuid=D(),n.safeStorage.set(P,this.uuid))}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const i="log.externalLog",o=this.createLogParams(e),s=this.sessionKey;if(!s)return;this.params.apiTransport.sendBeacon(i,o,s)||this.logRequest(e)}async logRequest(e){const i="log.externalLog",o=this.createLogParams(e),s=this.sessionKey??await this._authorizeWithBackoff();if(!s)return;const a=async(u,f=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,o,s)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:n.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:l});return}const d=l?.error_code;switch(d){case b.PARAM_SESSION_EXPIRED:case b.PARAM_SESSION_KEY:case b.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),f>0?a(u,f-1):void 0;case b.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),f>0?a(u,f-1):void 0;default:{this.params.error$.next({id:`LogRequest#${d}`,category:n.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return a(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${U}:${T}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=n.getExponentialDelay(this.consequentAuthErrors,q);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(o=>this.params.error$.next({id:"AuthorizeBackoff",category:n.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:o})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",i={session_data:{version:2,device_id:this.uuid,client_version:T.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(e,i).then(o=>((!o||!o.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:n.ErrorCategory.EXTERNAL_API,message:"No session key",data:o}),this.sessionKey=o?.session_key??void 0,this.sessionKey)).catch(async o=>{this.sessionKey=void 0;const s=o?.error_code;switch(s){case b.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}s?this.params.error$.next({id:`Authorize#${s}`,category:n.ErrorCategory.EXTERNAL_API,message:"authorize error",data:o}):this.params.error$.next({id:"AuthorizeUnknown",category:n.ErrorCategory.NETWORK,message:"authorize error",thrown:o})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class v{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,i,o){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:i,options:o})}removeEventListener(e,i){if(!(e in this.listeners))return;const o=this.listeners[e];for(let s=0,a=o.length;s<a;s++)if(o[s].callback===i){o.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const o=this.listeners[e.type].slice();for(let s=0,a=o.length;s<a;s++){const u=o[s];try{u.callback.call(this,e)}catch(f){Promise.resolve().then(()=>{throw f})}u.options&&u.options.once&&this.removeEventListener(e.type,u.callback)}return!e.defaultPrevented}}class $ extends v{constructor(){super(),this.listeners||v.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Q{constructor(){Object.defineProperty(this,"signal",{value:new $,writable:!0,configurable:!0})}abort(e){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 o=e;if(o===void 0)if(typeof document>"u")o=new Error("This operation was aborted"),o.name="AbortError";else try{o=new DOMException("signal is aborted without reason")}catch{o=new Error("This operation was aborted"),o.name="AbortError"}this.signal.reason=o,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Q.prototype[Symbol.toStringTag]="AbortController",$.prototype[Symbol.toStringTag]="AbortSignal");function L(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function H(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=t;if(!L({fetch:e,Request:i,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty("signal")||s)&&(a=function(d,r){let h;r&&r.signal&&(h=r.signal,delete r.signal);const p=new i(d,r);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},a.prototype=i.prototype);const u=e;return{fetch:(l,d)=>{const r=a&&a.prototype.isPrototypeOf(l)?l.signal:d?d.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 p=new Promise((g,A)=>{r.addEventListener("abort",()=>A(h),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([p,u(l,d)])}return u(l,d)},Request:a}}const _=L({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),k=_?H({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,C=_?k.fetch:window.fetch;_?k.Request:window.Request;class M{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),s=(await(await C(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!s)throw new Error("Wrong DNS response");return s}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:n.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),R[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,o){if(!window.Blob||!window.navigator.sendBeacon)return!1;const s=this._prepareQueryParams({method:e,queryParams:i,sessionKey:o}),a=new window.Blob([s.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:n.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:i}})}return!1}async sendRequest(e,i,o){const s=n.now(),a=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:n.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:n.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:i,sessionKey:o,time:n.now()-s}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),C(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:o})}).then(u=>{const f=Number(u.headers.get("content-length"))===0,l=new Date(u.headers.get("date")??"").getTime(),d=n.now()-s;if(isFinite(l)&&this.timeSynchronisation.addServerTime(l,d),!f)return u.json().then(r=>Object.prototype.hasOwnProperty.call(r,"error_msg")?Promise.reject(r):r,a)},a)}_prepareQueryParams(e){const i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([o,s])=>i.append(o,typeof s=="string"?s:JSON.stringify(s))),i}}const x=3e3,W=x*5;class K{api;error$;requestQueue=[];subscription;isPaused=!1;debouncedFlush=I(()=>{try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:n.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}},x,{maxWait:W});constructor(e){this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()})}log(e){console.log(e.operation,e.custom.param,e),this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(console.log("Sending",this.requestQueue.length,"events",this.requestQueue),e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}const z=()=>{let t,e;try{t=window.self!==window.top}catch(o){o instanceof DOMException&&o.name==="SecurityError"?t=!0:(t=!1,console.error(o))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(o){console.error(o)}try{!e&&document.referrer&&(e=document.referrer)}catch(o){console.error(o)}const i=e?new URL(e).hostname:void 0;return{isEmbed:t,host:i}},j=t=>t&&{[c.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[c.VideoQuality.Q_144P]:exports.Quality.Q144P,[c.VideoQuality.Q_240P]:exports.Quality.Q240P,[c.VideoQuality.Q_360P]:exports.Quality.Q360P,[c.VideoQuality.Q_480P]:exports.Quality.Q480P,[c.VideoQuality.Q_720P]:exports.Quality.Q720P,[c.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[c.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[c.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[c.VideoQuality.Q_4320P]:exports.Quality.UNKNOWN}[t],N=t=>t&&{[c.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[c.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[c.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],G=t=>{if(t!==void 0)switch(t){case c.VideoFormat.MPEG:return exports.ContentType.MP4;case c.VideoFormat.DASH:case c.VideoFormat.DASH_LIVE:return exports.ContentType.DASH;case c.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case c.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case c.VideoFormat.DASH_WEBM:case c.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case c.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.ONDEMAND_DASH_LIVE;case c.VideoFormat.HLS:case c.VideoFormat.HLS_LIVE:return exports.ContentType.HLS;case c.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case c.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.ONDEMAND_HLS_LIVE;case c.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.WEBRTC;default:return n.assertNever(t)}},w=t=>{if(t!==void 0)switch(t){case c.Surface.NONE:case c.Surface.INLINE:return;case c.Surface.FULLSCREEN:return E.FULLSCREEN;case c.Surface.SECOND_SCREEN:return E.EXTERNAL;case c.Surface.PIP:return E.PIP;default:return n.assertNever(t)}},Y=t=>{switch(t){case"slow-2g":return y.POOR;case"2g":return y.POOR;case"3g":return y.GOOD;case"4g":return y.EXCELLENT}};class X{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){const o=Date.now(),s=e-o-i/2;if(Math.abs(s)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(s):this.offset=Math.round(.2*s+(1-.2)*this.offset)}}const O=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),J=t=>new n.Observable(e=>{const i=new n.Subscription,o=n.merge(n.fromEvent(window,"beforeunload"),t.events.willDestruct$),s=new n.ValueSubject(void 0);let a;t.info.isLive$.pipe(n.filterChanged()).subscribe(g=>{a&&(a.unsubscribe(),s.next(void 0)),g?a=t.info.liveTime$.pipe(n.map(A=>A&&A/1e3)).subscribe(s):a=t.info.position$.subscribe(s),i.add(a)});const{playing$:u,paused$:f}=t.events,l=t.events.willSeek$.pipe(n.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING)),d=t.events.seeked$.pipe(n.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING)),r=n.merge(u,d),h=n.merge(f,l,o,t.events.looped$);let p;return i.add(r.subscribe(()=>p=s.getValue())),i.add(h.subscribe(()=>{const g=s.getValue();n.isNullable(p)||p===g||n.isNullable(g)||(e.next({from:p,to:g}),p=void 0)})),i});class Z{api;logger;config;subscription=new n.Subscription;timeSynchronisation=new X;experimental;statContext;vsid=O();isEmbed;embedParent;uiEvents;player;seekAction$=new n.ValueSubject(exports.SeekAction.UNKNOWN);constructor(e,i){this.statContext=e,this.config={...i.config??{},requestRetryCount:1};const o=new n.Subject;this.experimental={error$:o};const s=new M({apiKey:B,apiBaseUrl:R[i.apiEnv],apiEnv:i.apiEnv,error$:o,timeSynchronisation:this.timeSynchronisation});this.api=new F({apiTransport:s,refreshAuthToken:i.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,mobile:this.statContext.mobile??!1,error$:o}),this.logger=new K({api:this.api,error$:o});const{isEmbed:a,host:u}=z();this.isEmbed=a,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const i=new n.Subscription,o=(r,h)=>i.add(r.subscribe(h));o(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(exports.SeekAction.UNKNOWN)}),o(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),o(e.events.willResume$,()=>{this.logPlay()}),o(e.events.started$,()=>{this.statContext.clip&&(this.logWatchCoverageRecord({start:0,end:0}),this.logger.flush())}),o(J(e),r=>{const h=e.info.isLive$.getValue(),p={start:r.from,end:r.to};h?this.logWatchCoverageLive(p):this.logWatchCoverageRecord(p)});let s;o(e.info.isStalled$,r=>{r?s=n.now():(n.isNonNullable(s)&&this.logEmptyBuffer({duration:n.now()-s}),s=void 0)});let a=!1;i.add(e.events.fatalError$.pipe(n.once()).subscribe(()=>a=!0)),o(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const h=n.isNonNullable(s)?n.now()-s:void 0;this.logCloseAtEmptyBuffer({duration:h??0}),s=void 0}else a||this.logActionStop();this.logger.flush()}),o(e.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),o(e.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let u,f,l=!1;o(e.events.firstBytes$,r=>{u=n.now(),this.logFirstBytes({time:r})}),o(e.events.willStart$,()=>f=n.now()),o(e.info.currentBuffer$,r=>{!l&&r&&r.end-r.start>0&&n.isNonNullable(u)&&(this.logPlayerReady({duration:n.now()-u}),l=!0)}),o(e.events.firstFrame$,()=>{n.isNonNullable(u)&&!l&&(this.logPlayerReady({duration:n.now()-u}),l=!0),n.isNonNullable(f)&&this.logFirstFrame({time:n.now()-f})}),o(e.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),o(n.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:r,volume:h})=>this.updateContext({audible:!r&&h>0})),o(e.info.currentQuality$,r=>this.updateContext({quality:j(r)})),o(e.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),o(e.info.currentFormat$,r=>this.updateContext({contentType:G(r)}));let d;return o(e.info.hostname$,r=>{this.updateContext({cdnHostname:r,failover:d!==void 0&&d!==r}),d=r}),o(e.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),o(e.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:N(r)}),this.updateContext({connectionType:N(r)})}),o(e.info.httpConnectionReused$,r=>{n.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),o(e.info.surface$,r=>this.updateContext({mode:w(r)})),o(n.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:r,available:h})=>{const p=h.find(({id:g})=>g===r);this.updateContext({subtitles:p?.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;const i=new n.Subscription;return this.player&&(i.add(e.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),i.add(e.actionSeek$.subscribe(this.seekAction$)),i.add(e.inPiP$.subscribe(o=>{const s=o?E.PIP:w(this.player?.info.surface$.getValue());this.updateContext({mode:s})})),i.add(e.inFullscreen$.subscribe(o=>{const s=o?E.FULLSCREEN:w(this.player?.info.surface$.getValue());this.updateContext({mode:s})})),this.subscription.add(i)),i}attachToAds(e){const i=new n.Subscription;return i.add(e.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(e.started$.subscribe(o=>this.logAdStarted(o))).add(e.paused$.subscribe(()=>this.logAdPaused())).add(e.resumed$.subscribe(()=>this.logAdResumed())).add(e.ended$.subscribe(()=>this.logAdEnded())).add(e.skipped$.subscribe(()=>this.logAdSkipped())).add(e.clicked$.subscribe(()=>this.logAdClicked())),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=O()}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){const i=e.start+this.timeSynchronisation.getOffset(),o=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${i}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}subscribe(){this.subscription.add(n.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)));const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(n.merge(n.fromEvent(e,"change"),n.observableFrom(["init"])).subscribe(()=>this.updateContext({network:Y(e.effectiveType)})))}logPlayerReady(e){this.log({operation:"player_ready",param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:"action_play",param:String(Math.round(e.position))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){const i=this.createLogItem(e);this.logger.log(i)}createLogItem({operation:e,param:i,time:o}){const s=this.timeSynchronisation.now(),a=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,f={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?S.AUTO:this.statContext.autoplay===!1?S.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:a,connection_reused:u===!0?m.YES:u===!1?m.NO:void 0,cached_data:this.statContext.cached===!0?m.YES:this.statContext.cached===!1?m.NO:void 0,live:this.statContext.liveEdge?m.YES:void 0,muted:this.statContext.audible===!1?m.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:m.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};return{operation:e,type:1,time:o,network:this.statContext.network,timestamp:s,custom:f}}}exports.OneStat=Z;
|
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.35-dev.f578f79.0
|
|
3
|
+
* Wed, 10 May 2023 11:40:54 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-35/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as K,getExponentialDelay as z,ErrorCategory as l,now as _,assertNever as Q,Subscription as N,Subject as W,fromEvent as V,isNonNullable as k}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{VideoQuality as f,HttpConnectionType as v,VideoFormat as c,ChromecastState as j}from"@vkontakte/videoplayer-core/esnext.esm.js";import G from"lodash/debounce.js";const R="_one-stat_",E=(()=>{try{const t=Date.now().toString(),e=window.localStorage;e.setItem(t,t);const r=e.getItem(t)===t;return e.removeItem(t),r?e:null}catch{return null}})();function Y(t){const e=E?E.getItem(R+t):null;if(e===null)return null;try{return JSON.parse(e)}catch{return null}}function J(t,e){try{E&&E.setItem(R+t,JSON.stringify(e))}catch{}}function X(t){E&&E.removeItem(R+t)}var I={get(t){return Y(t)||null},set(t,e){J(t,e)},remove(t){X(t)}};function Z(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let r=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(r<=2&&(r=33554432+Math.random()*16777216|0),s=r&15,r=r>>4,e[o]=t[o===19?s&3|8:s]);return e.join("")}var b;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(b||(b={}));var d;(function(t){t.Q144P="144",t.Q240P="240",t.Q360P="360",t.Q480P="480",t.Q720P="720",t.Q1080P="1080",t.Q1440P="1440",t.Q2160P="2160",t.Q4320P="4320",t.UNKNOWN="unknown"})(d||(d={}));var w;(function(t){t.CHROMECAST="chromecast",t.APPLE_TV="appletv",t.PIP="pip",t.HEADPHONES="externalHeadphones",t.SCREEN=""})(w||(w={}));var p;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.RTMP="rtmp",t.UNKNOWN="unknown"})(p||(p={}));var P;(function(t){t.AUTO="auto",t.MANUAL=""})(P||(P={}));var S;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(S||(S={}));var T;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(T||(T={}));const L="1.0.34",ee="esnext.esm.js",te="CIOPGQJGDIHBABABA",B={[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]:""},se={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var A;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(A||(A={}));class re{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new K(!1);backoffTimeoutId;constructor(e){this.params=e;const r=I.get("uuid");r?this.uuid=String(r):(this.uuid=Z(),I.set("uuid",this.uuid))}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const r="log.externalLog",s=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(r,s,o)||this.logRequest(e)}async logRequest(e){const r="log.externalLog",s=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const i=async(n,g=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(r,s,o)}catch(a){if(!a||!("error_code"in a)){this.params.error$.next({id:"logRequestUnknown",category:l.NETWORK,message:`Unknown ${r} error`,thrown:a});return}const h=a?.error_code;switch(h){case A.PARAM_SESSION_EXPIRED:case A.PARAM_SESSION_KEY:case A.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),g>0?i(n,g-1):void 0;case A.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),g>0?i(n,g-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:l.EXTERNAL_API,message:`${r} error`,data:a});return}}}};return i(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${ee}:${L}`,platform:"WEB",items:e.map(r=>({...r,time:0,type:1}))})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=z(this.consequentAuthErrors,se);return new Promise(r=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(r).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:l.NETWORK,message:"Otherwise unhandle errror in authrization",thrown:s})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",r={session_data:{version:2,device_id:this.uuid,client_version:L.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(r.session_data.auth_token=this.authToken,r.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,r).then(s=>((!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:l.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 A.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:l.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:l.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 x{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,r,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:r,options:s})}removeEventListener(e,r){if(!(e in this.listeners))return;const s=this.listeners[e];for(let o=0,i=s.length;o<i;o++)if(s[o].callback===r){s.splice(o,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let o=0,i=s.length;o<i;o++){const n=s[o];try{n.callback.call(this,e)}catch(g){Promise.resolve().then(()=>{throw g})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class q extends x{constructor(){super(),this.listeners||x.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class oe{constructor(){Object.defineProperty(this,"signal",{value:new q,writable:!0,configurable:!0})}abort(e){let r;try{r=new Event("abort")}catch{typeof document<"u"?document.createEvent?(r=document.createEvent("Event"),r.initEvent("abort",!1,!1)):(r=document.createEventObject(),r.type="abort"):r={type:"abort",bubbles:!1,cancelable:!1}}let s=e;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(r)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(oe.prototype[Symbol.toStringTag]="AbortController",q.prototype[Symbol.toStringTag]="AbortSignal");function U(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function ie(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:r=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=t;if(!U({fetch:e,Request:r,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:e,Request:i};let i=r;(i&&!i.prototype.hasOwnProperty("signal")||o)&&(i=function(h,u){let m;u&&u.signal&&(m=u.signal,delete u.signal);const y=new r(h,u);return m&&Object.defineProperty(y,"signal",{writable:!1,enumerable:!1,configurable:!0,value:m}),y},i.prototype=r.prototype);const n=e;return{fetch:(a,h)=>{const u=i&&i.prototype.isPrototypeOf(a)?a.signal:h?h.signal:void 0;if(u){let m;try{m=new DOMException("Aborted","AbortError")}catch{m=new Error("Aborted"),m.name="AbortError"}if(u.aborted)return Promise.reject(m);const y=new Promise((M,F)=>{u.addEventListener("abort",()=>F(m),{once:!0})});return h&&h.signal&&delete h.signal,Promise.race([y,n(a,h)])}return n(a,h)},Request:i}}const O=U({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),D=O?ie({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,C=O?D.fetch:window.fetch;O?D.Request:window.Request;class ne{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==b.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await C(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:l.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),B[b.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,r,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:e,queryParams:r,sessionKey:s}),i=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:l.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:r}})}return!1}async sendRequest(e,r,s){const o=_(),i=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:l.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:l.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:r,sessionKey:s,time:_()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),C(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:r,sessionKey:s})}).then(n=>{const g=Number(n.headers.get("content-length"))===0,a=new Date(n.headers.get("date")??"").getTime(),h=_()-o;if(isFinite(a)&&this.timeSynchronisation.addServerTime(a,h),!g)return n.json().then(u=>Object.prototype.hasOwnProperty.call(u,"error_msg")?Promise.reject(u):u,i)},i)}_prepareQueryParams(e){const r=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&r.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([s,o])=>r.append(s,typeof o=="string"?o:JSON.stringify(o))),r}}const H=3e3,ae=H*5;class he{api;error$;requestQueue=[];subscription;isPaused=!1;debouncedFlush=G(()=>{try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:l.WTF,message:String(e)??"Unknown logger error",thrown:e})}},H,{maxWait:ae});constructor(e){this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(r=>{r&&this.debouncedFlush()})}log(e){this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}class ue{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,r){const s=Date.now(),o=e-s-r/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 $=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),ce=t=>t&&{[f.INVARIANT]:d.UNKNOWN,[f.Q_144P]:d.Q144P,[f.Q_240P]:d.Q240P,[f.Q_360P]:d.Q360P,[f.Q_480P]:d.Q480P,[f.Q_720P]:d.Q720P,[f.Q_1080P]:d.Q1080P,[f.Q_1440P]:d.Q1440P,[f.Q_2160P]:d.Q2160P,[f.Q_4320P]:d.Q4320P}[t],de=t=>t&&{[v.HTTP1]:S.HTTP1,[v.HTTP2]:S.HTTP2,[v.QUIC]:S.HTTP3}[t],le=t=>{if(t!==void 0)switch(t){case c.MPEG:return p.MP4;case c.DASH:case c.DASH_LIVE:case c.DASH_LIVE_CMAF:return p.DASH;case c.DASH_SEP:return p.DASH_SEP;case c.DASH_ONDEMAND:return p.ONDEMAND_DASH;case c.DASH_WEBM:case c.DASH_LIVE_WEBM:return p.WEBM;case c.HLS:case c.HLS_LIVE:case c.HLS_LIVE_CMAF:return p.HLS;case c.HLS_ONDEMAND:return p.ONDEMAND_HLS;case c.WEB_RTC_LIVE:return p.RTMP;default:return Q(t)}};class me{api;logger;config;subscription=new N;timeSynchronisation=new ue;experimental;statContext;vsid=$();fieldBlacklist=[];constructor(e,r){this.statContext=e,this.config={...r.config??{},requestRetryCount:1};const s=new W;this.experimental={error$:s};const o=new ne({apiKey:te,apiBaseUrl:B[r.apiEnv],apiEnv:r.apiEnv,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new re({apiTransport:o,refreshAuthToken:r.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,error$:s}),this.logger=new he({api:this.api,error$:s}),this.subscription.add(V(window,"beforeunload").subscribe(()=>this.logger.flush(!0)))}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let r;return new N().add(e.events.started$.subscribe(()=>{this.logStarted({position:e.info.position$.getValue()})})).add(e.events.looped$.subscribe(()=>{this.resetViewSession(),this.logStarted({position:e.info.position$.getValue()})})).add(e.events.seeked$.subscribe(()=>{this.logSeek()})).add(e.events.willPause$.subscribe(()=>{this.logPause({position:e.info.position$.getValue()})})).add(e.events.willResume$.subscribe(()=>{this.logPlay()})).add(e.events.managedError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.fatalError$.subscribe(({id:s})=>{this.logError({errorType:s})})).add(e.events.inited$.subscribe(()=>{this.logInited()})).add(e.events.canplay$.subscribe(s=>{this.logReady({time:s})})).add(e.events.firstBytes$.subscribe(s=>{this.logFirstBytes({time:s})})).add(e.events.firstFrame$.subscribe(s=>{this.logFirstFrame({time:s})})).add(e.events.watchCoverageRecord$.subscribe(s=>{this.logWatchCoverageRecord(s)})).add(e.events.watchCoverageLive$.subscribe(s=>{this.logWatchCoverageLive(s)})).add(e.info.isStalled$.subscribe(s=>{s?r=_():(k(r)&&this.logEmptyBuffer({duration:_()-r}),r=void 0)})).add(e.events.ended$.subscribe(()=>{const s=e.info.throughputEstimation$.getValue();k(s)&&this.logDownloadSpeed({speed:s/8})})).add(e.info.hostname$.subscribe(s=>{this.updateContext({cdnHostname:s})})).add(e.info.httpConnectionType$.subscribe(s=>{this.updateContext({connectionType:de(s)})})).add(e.info.httpConnectionReused$.subscribe(s=>{this.updateContext({connectionReused:s})})).add(e.info.currentQuality$.subscribe(s=>{this.updateContext({quality:ce(s)})})).add(e.info.currentFormat$.subscribe(s=>{this.updateContext({contentType:le(s)})})).add(e.info.chromecastState$.subscribe(s=>{this.updateContext({destination:s===j.CONNECTED?w.CHROMECAST:w.SCREEN})}))}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=$()}setFieldBlacklist(e=[]){this.fieldBlacklist=e}logInited(){this.log({operation:"init"})}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(e){this.log({operation:"play",param:String(Math.round(e.position))})}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(){this.log({operation:"seek"})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"error",param:e.errorType})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`}),this.logger.flush(!0)}logWatchCoverageLive(e){const r=e.start+this.timeSynchronisation.getOffset(),s=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${r}-${s}`}),this.logger.flush(!0)}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(e){this.log({operation:"download_speed",param:String(e.speed)})}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}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"})}log(e){const r=this.createLogItem(e);this.logger.log(r)}createLogItem({operation:e,param:r}){const s=this.timeSynchronisation.now(),o={vsid:this.vsid,vid:this.statContext.movieId,quality:this.statContext.quality,dst:this.statContext.destination,ct:this.statContext.contentType,aid:this.statContext.albumId,place:this.statContext.place,cdn_host:this.statContext.cdnHostname,connection_type:this.statContext.connectionType,connection_reused:this.statContext.connectionReused===!0?T.YES:this.statContext.connectionReused===!1?T.NO:void 0,stat_type:this.statContext.autoplay===!0?P.AUTO:this.statContext.autoplay===!1?P.MANUAL:void 0,vk_playlist_id:this.statContext.vkPlaylistId,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode};r!==void 0&&(o.param=r);for(const i of this.fieldBlacklist)delete o[i];return{operation:e,timestamp:s,custom:o}}}export{b as ApiEnv,S as ConnectionType,p as ContentType,me as OneStat,d as Quality,w as ScreenDestination};
|
|
6
|
+
import{ValueSubject as U,safeStorage as q,getExponentialDelay as te,ErrorCategory as b,now as m,assertNever as G,Observable as se,Subscription as R,merge as $,fromEvent as I,filterChanged as ie,map as oe,filter as M,isNullable as D,Subject as re,once as ne,combine as H,observableFrom as ae,isNonNullable as v}from"@vkontakte/videoplayer-shared/esnext.esm.js";import ue from"lodash/debounce.js";import{Surface as O,VideoQuality as E,HttpConnectionType as k,VideoFormat as f,PlaybackState as F}from"@vkontakte/videoplayer-core/esnext.esm.js";function ce(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,e[o]=t[o===19?s&3|8:s]);return e.join("")}var w;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(w||(w={}));var p;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(p||(p={}));var g;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(g||(g={}));var L;(function(t){t.AUTO="auto",t.MANUAL=""})(L||(L={}));var N;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(N||(N={}));var _;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(_||(_={}));var P;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(P||(P={}));var y;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(y||(y={}));var C;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(C||(C={}));const W="1.0.35-dev.f578f79.0",he="esnext.esm.js",de="CIOPGQJGDIHBABABA",Y={[w.PROD]:"https://api.ok.ru",[w.VK_ALIAS]:"https://api.mycdn.me",[w.VIDEOTEST]:"https://videotestapi.ok.ru/api",[w.TEST]:"https://apitest.ok.ru",[w.AUTO]:""},le="_one-stat_",K=`${le}uuid`,fe={start:1e3,factor:1.5,max:5*60*1e3,random:.1};var S;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(S||(S={}));class pe{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new U(!1);backoffTimeoutId;constructor(e){this.params=e;const i=q.get(K);i?this.uuid=String(i):(this.uuid=ce(),q.set(K,this.uuid))}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const i="log.externalLog",s=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(e)}async logRequest(e){const i="log.externalLog",s=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const n=async(a,d=this.params.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,s,o)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:b.NETWORK,message:`Unknown ${i} error`,thrown:u});return}const h=u?.error_code;switch(h){case S.PARAM_SESSION_EXPIRED:case S.PARAM_SESSION_KEY:case S.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?n(a,d-1):void 0;case S.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?n(a,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:b.EXTERNAL_API,message:`${i} error`,data:u});return}}}};return n(e)}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(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`${he}:${W}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=te(this.consequentAuthErrors,fe);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)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",i={session_data:{version:2,device_id:this.uuid,client_version:W.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(e,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 S.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 V{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,i,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:i,options:s})}removeEventListener(e,i){if(!(e in this.listeners))return;const s=this.listeners[e];for(let o=0,n=s.length;o<n;o++)if(s[o].callback===i){s.splice(o,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let o=0,n=s.length;o<n;o++){const a=s[o];try{a.callback.call(this,e)}catch(d){Promise.resolve().then(()=>{throw d})}a.options&&a.options.once&&this.removeEventListener(e.type,a.callback)}return!e.defaultPrevented}}class X extends V{constructor(){super(),this.listeners||V.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(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class ge{constructor(){Object.defineProperty(this,"signal",{value:new X,writable:!0,configurable:!0})}abort(e){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=e;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&&(ge.prototype[Symbol.toStringTag]="AbortController",X.prototype[Symbol.toStringTag]="AbortSignal");function J(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function me(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=t;if(!J({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:e,Request:n};let n=i;(n&&!n.prototype.hasOwnProperty("signal")||o)&&(n=function(h,r){let c;r&&r.signal&&(c=r.signal,delete r.signal);const l=new i(h,r);return c&&Object.defineProperty(l,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),l},n.prototype=i.prototype);const a=e;return{fetch:(u,h)=>{const r=n&&n.prototype.isPrototypeOf(u)?u.signal:h?h.signal:void 0;if(r){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(r.aborted)return Promise.reject(c);const l=new Promise((A,T)=>{r.addEventListener("abort",()=>T(c),{once:!0})});return h&&h.signal&&delete h.signal,Promise.race([l,a(u,h)])}return a(u,h)},Request:n}}const B=J({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Z=B?me({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Q=B?Z.fetch:window.fetch;B?Z.Request:window.Request;class be{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.apiEnv,this.apiBaseUrl=e.apiBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==w.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await Q(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:b.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Y[w.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:e,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:e,params:i}})}return!1}async sendRequest(e,i,s){const o=m(),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:e,params:i,sessionKey:s,time:m()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),Q(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:s})}).then(a=>{const d=Number(a.headers.get("content-length"))===0,u=new Date(a.headers.get("date")??"").getTime(),h=m()-o;if(isFinite(u)&&this.timeSynchronisation.addServerTime(u,h),!d)return a.json().then(r=>Object.prototype.hasOwnProperty.call(r,"error_msg")?Promise.reject(r):r,n)},n)}_prepareQueryParams(e){const i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const ee=3e3,Ee=ee*5;class Ae{api;error$;requestQueue=[];subscription;isPaused=!1;debouncedFlush=ue(()=>{try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:b.WTF,message:String(e)??"Unknown logger error",thrown:e})}},ee,{maxWait:Ee});constructor(e){this.api=e.api,this.error$=e.error$,this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()})}log(e){console.log(e.operation,e.custom.param,e),this.requestQueue.push(e),this.isPaused||this.debouncedFlush()}flush(e=!1){this.requestQueue.length!==0&&(this.api.authorized$.getValue()?(console.log("Sending",this.requestQueue.length,"events",this.requestQueue),e?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[]):this.api.authorize(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe()}}const _e=()=>{let t,e;try{t=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?t=!0:(t=!1,console.error(s))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!e&&document.referrer&&(e=document.referrer)}catch(s){console.error(s)}const i=e?new URL(e).hostname:void 0;return{isEmbed:t,host:i}},we=t=>t&&{[E.INVARIANT]:p.UNKNOWN,[E.Q_144P]:p.Q144P,[E.Q_240P]:p.Q240P,[E.Q_360P]:p.Q360P,[E.Q_480P]:p.Q480P,[E.Q_720P]:p.Q720P,[E.Q_1080P]:p.Q1080P,[E.Q_1440P]:p.Q1440P,[E.Q_2160P]:p.Q2160P,[E.Q_4320P]:p.UNKNOWN}[t],z=t=>t&&{[k.HTTP1]:N.HTTP1,[k.HTTP2]:N.HTTP2,[k.QUIC]:N.HTTP3}[t],Se=t=>{if(t!==void 0)switch(t){case f.MPEG:return g.MP4;case f.DASH:case f.DASH_LIVE:return g.DASH;case f.DASH_SEP:return g.DASH_SEP;case f.DASH_ONDEMAND:return g.ONDEMAND_DASH;case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return g.WEBM;case f.DASH_LIVE_CMAF:return g.ONDEMAND_DASH_LIVE;case f.HLS:case f.HLS_LIVE:return g.HLS;case f.HLS_ONDEMAND:return g.ONDEMAND_HLS;case f.HLS_LIVE_CMAF:return g.ONDEMAND_HLS_LIVE;case f.WEB_RTC_LIVE:return g.WEBRTC;default:return G(t)}},x=t=>{if(t!==void 0)switch(t){case O.NONE:case O.INLINE:return;case O.FULLSCREEN:return y.FULLSCREEN;case O.SECOND_SCREEN:return y.EXTERNAL;case O.PIP:return y.PIP;default:return G(t)}},ye=t=>{switch(t){case"slow-2g":return P.POOR;case"2g":return P.POOR;case"3g":return P.GOOD;case"4g":return P.EXCELLENT}};class Pe{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){const s=Date.now(),o=e-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 j=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Te=t=>new se(e=>{const i=new R,s=$(I(window,"beforeunload"),t.events.willDestruct$),o=new U(void 0);let n;t.info.isLive$.pipe(ie()).subscribe(A=>{n&&(n.unsubscribe(),o.next(void 0)),A?n=t.info.liveTime$.pipe(oe(T=>T&&T/1e3)).subscribe(o):n=t.info.position$.subscribe(o),i.add(n)});const{playing$:a,paused$:d}=t.events,u=t.events.willSeek$.pipe(M(()=>t.info.playbackState$.getValue()===F.PLAYING)),h=t.events.seeked$.pipe(M(()=>t.info.playbackState$.getValue()===F.PLAYING)),r=$(a,h),c=$(d,u,s,t.events.looped$);let l;return i.add(r.subscribe(()=>l=o.getValue())),i.add(c.subscribe(()=>{const A=o.getValue();D(l)||l===A||D(A)||(e.next({from:l,to:A}),l=void 0)})),i});class Ne{api;logger;config;subscription=new R;timeSynchronisation=new Pe;experimental;statContext;vsid=j();isEmbed;embedParent;uiEvents;player;seekAction$=new U(C.UNKNOWN);constructor(e,i){this.statContext=e,this.config={...i.config??{},requestRetryCount:1};const s=new re;this.experimental={error$:s};const o=new be({apiKey:de,apiBaseUrl:Y[i.apiEnv],apiEnv:i.apiEnv,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new pe({apiTransport:o,refreshAuthToken:i.refreshAuthToken,requestRetryCount:this.config.requestRetryCount,mobile:this.statContext.mobile??!1,error$:s}),this.logger=new Ae({api:this.api,error$:s});const{isEmbed:n,host:a}=_e();this.isEmbed=n,this.embedParent=a,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const i=new R,s=(r,c)=>i.add(r.subscribe(c));s(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),s(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),s(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(C.UNKNOWN)}),s(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),s(e.events.willResume$,()=>{this.logPlay()}),s(e.events.started$,()=>{this.statContext.clip&&(this.logWatchCoverageRecord({start:0,end:0}),this.logger.flush())}),s(Te(e),r=>{const c=e.info.isLive$.getValue(),l={start:r.from,end:r.to};c?this.logWatchCoverageLive(l):this.logWatchCoverageRecord(l)});let o;s(e.info.isStalled$,r=>{r?o=m():(v(o)&&this.logEmptyBuffer({duration:m()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(ne()).subscribe(()=>n=!0)),s(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const c=v(o)?m()-o:void 0;this.logCloseAtEmptyBuffer({duration:c??0}),o=void 0}else n||this.logActionStop();this.logger.flush()}),s(e.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),s(e.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let a,d,u=!1;s(e.events.firstBytes$,r=>{a=m(),this.logFirstBytes({time:r})}),s(e.events.willStart$,()=>d=m()),s(e.info.currentBuffer$,r=>{!u&&r&&r.end-r.start>0&&v(a)&&(this.logPlayerReady({duration:m()-a}),u=!0)}),s(e.events.firstFrame$,()=>{v(a)&&!u&&(this.logPlayerReady({duration:m()-a}),u=!0),v(d)&&this.logFirstFrame({time:m()-d})}),s(e.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),s(H({muted:e.info.muted$,volume:e.info.volume$}),({muted:r,volume:c})=>this.updateContext({audible:!r&&c>0})),s(e.info.currentQuality$,r=>this.updateContext({quality:we(r)})),s(e.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),s(e.info.currentFormat$,r=>this.updateContext({contentType:Se(r)}));let h;return s(e.info.hostname$,r=>{this.updateContext({cdnHostname:r,failover:h!==void 0&&h!==r}),h=r}),s(e.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),s(e.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(r)}),this.updateContext({connectionType:z(r)})}),s(e.info.httpConnectionReused$,r=>{D(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),s(e.info.surface$,r=>this.updateContext({mode:x(r)})),s(H({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:r,available:c})=>{const l=c.find(({id:A})=>A===r);this.updateContext({subtitles:l?.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;const i=new R;return this.player&&(i.add(e.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),i.add(e.actionSeek$.subscribe(this.seekAction$)),i.add(e.inPiP$.subscribe(s=>{const o=s?y.PIP:x(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),i.add(e.inFullscreen$.subscribe(s=>{const o=s?y.FULLSCREEN:x(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),this.subscription.add(i)),i}attachToAds(e){const i=new R;return i.add(e.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(e.started$.subscribe(s=>this.logAdStarted(s))).add(e.paused$.subscribe(()=>this.logAdPaused())).add(e.resumed$.subscribe(()=>this.logAdResumed())).add(e.ended$.subscribe(()=>this.logAdEnded())).add(e.skipped$.subscribe(()=>this.logAdSkipped())).add(e.clicked$.subscribe(()=>this.logAdClicked())),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}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(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){const i=e.start+this.timeSynchronisation.getOffset(),s=e.end+this.timeSynchronisation.getOffset();this.log({operation:"watch_coverage_live",param:`${i}-${s}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}subscribe(){this.subscription.add(I(window,"beforeunload").subscribe(()=>this.logger.flush(!0)));const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add($(I(e,"change"),ae(["init"])).subscribe(()=>this.updateContext({network:ye(e.effectiveType)})))}logPlayerReady(e){this.log({operation:"player_ready",param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:"action_play",param:String(Math.round(e.position))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){const i=this.createLogItem(e);this.logger.log(i)}createLogItem({operation:e,param:i,time:s}){const o=this.timeSynchronisation.now(),n=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,a=this.statContext.firstConnectionReused,d={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?_.YES:a===!1?_.NO:void 0,cached_data:this.statContext.cached===!0?_.YES:this.statContext.cached===!1?_.NO:void 0,live:this.statContext.liveEdge?_.YES:void 0,muted:this.statContext.audible===!1?_.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:_.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};return{operation:e,type:1,time:s,network:this.statContext.network,timestamp:o,custom:d}}}export{w as ApiEnv,N as ConnectionType,g as ContentType,Ne as OneStat,p as Quality,C as SeekAction};
|