@vkontakte/videoplayer-statistics 1.0.6 → 1.0.9
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/Api.d.ts +3 -1
- package/OneStat.d.ts +18 -5
- package/index.cjs.js +3 -3
- package/index.d.ts +2 -2
- package/index.esm.js +3 -3
- package/package.json +2 -2
- package/types.d.ts +10 -0
package/Api.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ContentType, Quality, ScreenDestination, StatType } from './types';
|
|
1
|
+
import { ConnectionReused, ConnectionType, ContentType, Quality, ScreenDestination, StatType } from './types';
|
|
2
2
|
import { IApiTransport } from './ApiTransport';
|
|
3
3
|
export interface ILogItem {
|
|
4
4
|
operation: string;
|
|
@@ -16,6 +16,8 @@ export interface ILogCustomData {
|
|
|
16
16
|
aid?: string;
|
|
17
17
|
place?: string;
|
|
18
18
|
cdn_host?: string;
|
|
19
|
+
connection_type?: ConnectionType;
|
|
20
|
+
connection_reused?: ConnectionReused;
|
|
19
21
|
stat_type?: StatType;
|
|
20
22
|
vk_playlist_id?: string;
|
|
21
23
|
vk_app_id?: string;
|
package/OneStat.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { IObservable,
|
|
2
|
-
import { ApiEnv, ContentType, Quality, ScreenDestination } from './types';
|
|
1
|
+
import { IError, IObservable, Milliseconds, Seconds } from '@vkontakte/videoplayer-shared';
|
|
2
|
+
import { ApiEnv, ConnectionType, ContentType, Quality, ScreenDestination } from './types';
|
|
3
3
|
export interface IOneStat {
|
|
4
4
|
/**
|
|
5
5
|
* Лучше авторизоваться сразу, чтобы избежать ситуации:
|
|
@@ -50,6 +50,10 @@ export interface IOneStat {
|
|
|
50
50
|
* Время указывается в виде UTC timestamp'ов.
|
|
51
51
|
*/
|
|
52
52
|
logWatchCoverageLive(payload: IWatchCoveragePayload): void;
|
|
53
|
+
/**
|
|
54
|
+
* Буфер пуст и пользователь видит залипший кадр.
|
|
55
|
+
*/
|
|
56
|
+
logEmptyBuffer(payload: IEmptyBufferPayload): void;
|
|
53
57
|
/**
|
|
54
58
|
* Получен первый кусок данных контента от сервера раздачи видео
|
|
55
59
|
*/
|
|
@@ -77,20 +81,26 @@ export interface IPausePayload {
|
|
|
77
81
|
/**
|
|
78
82
|
* время в секундах: сколько просмотрено от начала ролика
|
|
79
83
|
*/
|
|
80
|
-
position:
|
|
84
|
+
position: Seconds;
|
|
81
85
|
}
|
|
82
86
|
export interface IFirstBytesPayload {
|
|
83
87
|
/**
|
|
84
88
|
* время в миллисекундах: сколько прошло с момента отправки запроса за видео данными (ping)
|
|
85
89
|
*/
|
|
86
|
-
time:
|
|
90
|
+
time: Milliseconds;
|
|
87
91
|
}
|
|
88
92
|
export interface IFirstFramePayload {
|
|
89
93
|
/**
|
|
90
94
|
* время в миллисекундах: сколько прошло времени с момента нажатия на кнопку play
|
|
91
95
|
* (или инициализации плеера для случая автоплея)
|
|
92
96
|
*/
|
|
93
|
-
time:
|
|
97
|
+
time: Milliseconds;
|
|
98
|
+
}
|
|
99
|
+
export interface IEmptyBufferPayload {
|
|
100
|
+
/**
|
|
101
|
+
* время в миллисекундах которое пользователь видел застывшую картинку
|
|
102
|
+
*/
|
|
103
|
+
duration: Milliseconds;
|
|
94
104
|
}
|
|
95
105
|
export interface IErrorPayload {
|
|
96
106
|
/**
|
|
@@ -114,6 +124,8 @@ export interface IStatContext {
|
|
|
114
124
|
*/
|
|
115
125
|
place?: string;
|
|
116
126
|
cdnHostname?: string;
|
|
127
|
+
connectionType?: ConnectionType;
|
|
128
|
+
connectionReused?: boolean;
|
|
117
129
|
autoplay?: boolean;
|
|
118
130
|
}
|
|
119
131
|
export interface IConstructorParams {
|
|
@@ -145,6 +157,7 @@ export declare class OneStat implements IOneStat {
|
|
|
145
157
|
logError(payload: IErrorPayload): void;
|
|
146
158
|
logWatchCoverageRecord(payload: IWatchCoveragePayload): void;
|
|
147
159
|
logWatchCoverageLive(payload: IWatchCoveragePayload): void;
|
|
160
|
+
logEmptyBuffer(payload: IEmptyBufferPayload): void;
|
|
148
161
|
logAdSlotRequest(): void;
|
|
149
162
|
logAdStarted(sectionType: string): void;
|
|
150
163
|
logAdPaused(): void;
|
package/index.cjs.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
* Thu,
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.9
|
|
3
|
+
* Thu, 24 Feb 2022 13:30:49 GMT
|
|
4
4
|
*/
|
|
5
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("@vkontakte/videoplayer-shared");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var s=e(require("lodash/debounce"));function o(t,e,s,o){return new(s||(s=Promise))((function(i,r){function
|
|
5
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("@vkontakte/videoplayer-shared");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var s=e(require("lodash/debounce"));function o(t,e,s,o){return new(s||(s=Promise))((function(i,r){function n(t){try{h(o.next(t))}catch(t){r(t)}}function a(t){try{h(o.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?i(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(n,a)}h((o=o.apply(t,e||[])).next())}))}const i=(()=>{try{const t=Date.now().toString(),e=window.localStorage;e.setItem(t,t);const s=e.getItem(t)===t;return e.removeItem(t),s?e:null}catch(t){return null}})();var r,n,a,h,u,p,d,l={get:t=>function(t){const e=i?i.getItem("_one-stat_"+t):null;if(null===e)return null;try{return JSON.parse(e)}catch(t){return null}}(t)||null,set(t,e){!function(t,e){try{i&&i.setItem("_one-stat_"+t,JSON.stringify(e))}catch(t){}}(t,e)},remove(t){!function(t){i&&i.removeItem("_one-stat_"+t)}(t)}};exports.ApiEnv=void 0,(r=exports.ApiEnv||(exports.ApiEnv={})).PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",exports.Quality=void 0,(n=exports.Quality||(exports.Quality={})).Q144P="144",n.Q240P="240",n.Q360P="360",n.Q480P="480",n.Q720P="720",n.Q1080P="1080",n.Q1440P="1440",n.Q2160P="2160",n.Q4320P="4320",n.UNKNOWN="unknown",exports.ScreenDestination=void 0,(a=exports.ScreenDestination||(exports.ScreenDestination={})).CHROMECAST="chromecast",a.APPLE_TV="appletv",a.PIP="pip",a.HEADPHONES="externalHeadphones",a.SCREEN="",exports.ContentType=void 0,(h=exports.ContentType||(exports.ContentType={})).MP4="mp4",h.DASH="dash",h.HLS="hls",h.WEBM="webm",function(t){t.AUTO="auto",t.MANUAL=""}(u||(u={})),exports.ConnectionType=void 0,(p=exports.ConnectionType||(exports.ConnectionType={})).HTTP1="http1",p.HTTP2="http2",p.HTTP3="http3",function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"}(d||(d={}));const c={[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"};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 g{constructor(t){this.params=t;const e=l.get("uuid");e?this.uuid=String(e):(this.uuid=function(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let s,o,i=0;for(o=0;o<36;o++)8===o||13===o||18===o||23===o?e[o]="-":14===o?e[o]="4":(i<=2&&(i=33554432+16777216*Math.random()|0),s=15&i,i>>=4,e[o]=t[19===o?3&s|8:s]);return e.join("")}(),l.set("uuid",this.uuid))}authorize(t){return o(this,void 0,void 0,(function*(){return this.authToken=null!=t?t:yield this.refreshAuthToken(),this._authorize()}))}logBeacon(t){const e="log.externalLog",s=this.createLogParams(t),o=this.sessionKey;void 0!==o&&this.params.apiTransport.sendBeacon(e,s,o)||this.params.apiTransport.sendRequest(e,s,o)}logRequest(t){var e,s;return o(this,void 0,void 0,(function*(){const o="log.externalLog",i=this.createLogParams(t),r=null!==(e=this.sessionKey)&&void 0!==e?e:yield this._authorize();try{return yield this.params.apiTransport.sendRequest(o,i,r)}catch(t){switch(null===(s=t)||void 0===s?void 0:s.error_code){case m.PARAM_SESSION_EXPIRED:case m.PARAM_SESSION_KEY:case m.PARAM_SIGNATURE:{const t=yield this._authorize();return this.params.apiTransport.sendRequest(o,i,t)}case m.AUTH_LOGIN:{this.authToken=yield this.refreshAuthToken();const t=yield this._authorizeRequest();return this.params.apiTransport.sendRequest(o,i,t)}default:throw t}}}))}refreshAuthToken(){return o(this,void 0,void 0,(function*(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally((()=>{this.refreshAuthTokenPromise=void 0}))),this.refreshAuthTokenPromise}))}createLogParams(t){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:"@vkontakte/videoplayer-statistics:1.0.9",platform:"WEB",items:t.map((t=>Object.assign(Object.assign({},t),{time:0,type:1})))})}}_authorize(){var t;return o(this,void 0,void 0,(function*(){try{return yield this._authorizeRequest()}catch(e){switch(null===(t=e)||void 0===t?void 0:t.error_code){case m.AUTH_LOGIN:return this.authToken=yield this.refreshAuthToken(),this._authorizeRequest()}throw e}}))}_authorizeRequest(){return o(this,void 0,void 0,(function*(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0;const t="auth.anonymLogin",e={session_data:{version:2,device_id:this.uuid,client_version:"1.0.9".split("-")[0],client_type:"SDK_JS"}};return void 0!==this.authToken&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,e).then((s=>{if(!s)throw new Error(`Empty response. Method: ${t}, params: ${JSON.stringify(e)}`);if(!s.session_key)throw new Error(`Empty 'session_key' in response. Method: ${t}, params: ${JSON.stringify(e)}, response: ${JSON.stringify(s)}`);return this.sessionKey=s.session_key,this.sessionKey})).catch((t=>{throw this.sessionKey=void 0,t})).finally((()=>{this.authorizePromise=void 0})),this.authorizePromise}))}}class y{constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiBaseUrl=t.apiBaseUrl,"/"!==this.apiBaseUrl[this.apiBaseUrl.length-1]&&(this.apiBaseUrl+="/")}sendBeacon(t,e,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:e,sessionKey:s}),i=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});return window.navigator.sendBeacon(`${this.apiBaseUrl}fb.do`,i)}sendRequest(t,e,s){return o(this,void 0,void 0,(function*(){const o=Date.now(),i=i=>{throw this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",message:"Unhandled request error",thrown:i,data:{method:t,params:e,sessionKey:s,time:Date.now()-o}}),i};return fetch(`${this.apiBaseUrl}fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:e,sessionKey:s})}).then((t=>Number(t.headers.get("content-length"))>0?t.json().then((t=>Object.prototype.hasOwnProperty.call(t,"error_msg")?Promise.reject(t):t),i):void 0),i)}))}_prepareQueryParams(t){const e=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return void 0!==t.sessionKey&&e.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach((([t,s])=>e.append(t,"string"==typeof s?s:JSON.stringify(s)))),e}}class v{constructor(t){this.requestQueue=[],this.isPaused=!1,this.debouncedFlush=s.default((()=>this.flush()),3e3,{maxWait:15e3}),this.api=t.api}log(t){this.requestQueue.push(t),this.isPaused||this.debouncedFlush()}flush(t=!1){0!==this.requestQueue.length&&(t?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[],this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}}exports.OneStat=class{constructor(e,s){this.statContext=e;const o=new t.Subject;this.experimental={error$:o};const i=new y({apiKey:"CIOPGQJGDIHBABABA",apiBaseUrl:c[s.apiEnv],error$:o});this.api=new g({apiTransport:i,refreshAuthToken:s.refreshAuthToken}),this.logger=new v({api:this.api}),window.addEventListener("beforeunload",(()=>this.logger.flush(!0)))}updateContext(t){this.statContext=Object.assign(Object.assign({},this.statContext),t)}authorize(t){return this.api.authorize(t)}pause(){this.logger.pause()}resume(){this.logger.resume()}logStarted(){this.log({operation:"play"})}logPlay(){this.log({operation:"play_toggle"})}logPause(t){this.log({operation:"pause",param:String(Math.round(t.position))})}logSeek(){this.log({operation:"seek"})}logFirstBytes(t){this.log({operation:"first_bytes",param:String(t.time)})}logFirstFrame(t){this.log({operation:"first_frame",param:String(t.time)})}logError(t){this.log({operation:"error",param:t.errorType})}logWatchCoverageRecord(t){this.log({operation:"watch_coverage_record",param:`${t.start}-${t.end}`}),this.logger.flush(!0)}logWatchCoverageLive(t){this.log({operation:"watch_coverage_live",param:`${t.start}-${t.end}`})}logEmptyBuffer(t){this.log({operation:"empty_buffer",param:String(t.duration)})}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(t){this.log({operation:"adv",param:t})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}log(t){const e=this.crateLogItem(t);this.logger.log(e)}crateLogItem({operation:t,param:e}){const s=Date.now(),o={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:!0===this.statContext.connectionReused?d.YES:!1===this.statContext.connectionReused?d.NO:void 0,stat_type:!0===this.statContext.autoplay?u.AUTO:!1===this.statContext.autoplay?u.MANUAL:void 0,vk_playlist_id:this.statContext.vkPlaylistId,vk_app_id:this.statContext.vkAppId};return void 0!==e&&(o.param=e),{operation:t,timestamp:s,custom:o}}};
|
package/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { IOneStat, OneStat, IStatContext } from './OneStat';
|
|
2
|
-
import { ApiEnv, ContentType, ScreenDestination, Quality } from './types';
|
|
3
|
-
export { OneStat, IOneStat, IStatContext, ApiEnv, ContentType, ScreenDestination, Quality };
|
|
2
|
+
import { ApiEnv, ContentType, ScreenDestination, Quality, ConnectionType } from './types';
|
|
3
|
+
export { OneStat, IOneStat, IStatContext, ApiEnv, ContentType, ScreenDestination, Quality, ConnectionType };
|
package/index.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
* Thu,
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.9
|
|
3
|
+
* Thu, 24 Feb 2022 13:30:49 GMT
|
|
4
4
|
*/
|
|
5
|
-
import{Subject as t}from"@vkontakte/videoplayer-shared";import e from"lodash/debounce";function s(t,e,s,o){return new(s||(s=Promise))((function(i,r){function a(t){try{h(o.next(t))}catch(t){r(t)}}function n(t){try{h(o.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?i(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(a,n)}h((o=o.apply(t,e||[])).next())}))}const o=(()=>{try{const t=Date.now().toString(),e=window.localStorage;e.setItem(t,t);const s=e.getItem(t)===t;return e.removeItem(t),s?e:null}catch(t){return null}})();var i,r,a,n,h,u={get:t=>function(t){const e=o?o.getItem("_one-stat_"+t):null;if(null===e)return null;try{return JSON.parse(e)}catch(t){return null}}(t)||null,set(t,e){!function(t,e){try{o&&o.setItem("_one-stat_"+t,JSON.stringify(e))}catch(t){}}(t,e)},remove(t){!function(t){o&&o.removeItem("_one-stat_"+t)}(t)}};!function(t){t.PROD="prod",t.VIDEOTEST="videotest",t.TEST="test"}(i||(i={})),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"}(r||(r={})),function(t){t.CHROMECAST="chromecast",t.APPLE_TV="appletv",t.PIP="pip",t.HEADPHONES="externalHeadphones",t.SCREEN=""}(a||(a={})),function(t){t.MP4="mp4",t.DASH="dash",t.HLS="hls",t.WEBM="webm"}(n||(n={})),function(t){t.AUTO="auto",t.MANUAL=""}(h||(h={}));const
|
|
5
|
+
import{Subject as t}from"@vkontakte/videoplayer-shared";import e from"lodash/debounce";function s(t,e,s,o){return new(s||(s=Promise))((function(i,r){function a(t){try{h(o.next(t))}catch(t){r(t)}}function n(t){try{h(o.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?i(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(a,n)}h((o=o.apply(t,e||[])).next())}))}const o=(()=>{try{const t=Date.now().toString(),e=window.localStorage;e.setItem(t,t);const s=e.getItem(t)===t;return e.removeItem(t),s?e:null}catch(t){return null}})();var i,r,a,n,h,u,p,d={get:t=>function(t){const e=o?o.getItem("_one-stat_"+t):null;if(null===e)return null;try{return JSON.parse(e)}catch(t){return null}}(t)||null,set(t,e){!function(t,e){try{o&&o.setItem("_one-stat_"+t,JSON.stringify(e))}catch(t){}}(t,e)},remove(t){!function(t){o&&o.removeItem("_one-stat_"+t)}(t)}};!function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test"}(i||(i={})),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"}(r||(r={})),function(t){t.CHROMECAST="chromecast",t.APPLE_TV="appletv",t.PIP="pip",t.HEADPHONES="externalHeadphones",t.SCREEN=""}(a||(a={})),function(t){t.MP4="mp4",t.DASH="dash",t.HLS="hls",t.WEBM="webm"}(n||(n={})),function(t){t.AUTO="auto",t.MANUAL=""}(h||(h={})),function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"}(u||(u={})),function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"}(p||(p={}));const l={[i.PROD]:"https://api.ok.ru",[i.VK_ALIAS]:"https://api.mycdn.me",[i.VIDEOTEST]:"https://videotestapi.ok.ru/api",[i.TEST]:"https://apitest.ok.ru"};var c;!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"}(c||(c={}));class m{constructor(t){this.params=t;const e=d.get("uuid");e?this.uuid=String(e):(this.uuid=function(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let s,o,i=0;for(o=0;o<36;o++)8===o||13===o||18===o||23===o?e[o]="-":14===o?e[o]="4":(i<=2&&(i=33554432+16777216*Math.random()|0),s=15&i,i>>=4,e[o]=t[19===o?3&s|8:s]);return e.join("")}(),d.set("uuid",this.uuid))}authorize(t){return s(this,void 0,void 0,(function*(){return this.authToken=null!=t?t:yield this.refreshAuthToken(),this._authorize()}))}logBeacon(t){const e="log.externalLog",s=this.createLogParams(t),o=this.sessionKey;void 0!==o&&this.params.apiTransport.sendBeacon(e,s,o)||this.params.apiTransport.sendRequest(e,s,o)}logRequest(t){var e,o;return s(this,void 0,void 0,(function*(){const s="log.externalLog",i=this.createLogParams(t),r=null!==(e=this.sessionKey)&&void 0!==e?e:yield this._authorize();try{return yield this.params.apiTransport.sendRequest(s,i,r)}catch(t){switch(null===(o=t)||void 0===o?void 0:o.error_code){case c.PARAM_SESSION_EXPIRED:case c.PARAM_SESSION_KEY:case c.PARAM_SIGNATURE:{const t=yield this._authorize();return this.params.apiTransport.sendRequest(s,i,t)}case c.AUTH_LOGIN:{this.authToken=yield this.refreshAuthToken();const t=yield this._authorizeRequest();return this.params.apiTransport.sendRequest(s,i,t)}default:throw t}}}))}refreshAuthToken(){return s(this,void 0,void 0,(function*(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally((()=>{this.refreshAuthTokenPromise=void 0}))),this.refreshAuthTokenPromise}))}createLogParams(t){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:"@vkontakte/videoplayer-statistics:1.0.9",platform:"WEB",items:t.map((t=>Object.assign(Object.assign({},t),{time:0,type:1})))})}}_authorize(){var t;return s(this,void 0,void 0,(function*(){try{return yield this._authorizeRequest()}catch(e){switch(null===(t=e)||void 0===t?void 0:t.error_code){case c.AUTH_LOGIN:return this.authToken=yield this.refreshAuthToken(),this._authorizeRequest()}throw e}}))}_authorizeRequest(){return s(this,void 0,void 0,(function*(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0;const t="auth.anonymLogin",e={session_data:{version:2,device_id:this.uuid,client_version:"1.0.9".split("-")[0],client_type:"SDK_JS"}};return void 0!==this.authToken&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,e).then((s=>{if(!s)throw new Error(`Empty response. Method: ${t}, params: ${JSON.stringify(e)}`);if(!s.session_key)throw new Error(`Empty 'session_key' in response. Method: ${t}, params: ${JSON.stringify(e)}, response: ${JSON.stringify(s)}`);return this.sessionKey=s.session_key,this.sessionKey})).catch((t=>{throw this.sessionKey=void 0,t})).finally((()=>{this.authorizePromise=void 0})),this.authorizePromise}))}}class g{constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiBaseUrl=t.apiBaseUrl,"/"!==this.apiBaseUrl[this.apiBaseUrl.length-1]&&(this.apiBaseUrl+="/")}sendBeacon(t,e,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:e,sessionKey:s}),i=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});return window.navigator.sendBeacon(`${this.apiBaseUrl}fb.do`,i)}sendRequest(t,e,o){return s(this,void 0,void 0,(function*(){const s=Date.now(),i=i=>{throw this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",message:"Unhandled request error",thrown:i,data:{method:t,params:e,sessionKey:o,time:Date.now()-s}}),i};return fetch(`${this.apiBaseUrl}fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:e,sessionKey:o})}).then((t=>Number(t.headers.get("content-length"))>0?t.json().then((t=>Object.prototype.hasOwnProperty.call(t,"error_msg")?Promise.reject(t):t),i):void 0),i)}))}_prepareQueryParams(t){const e=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return void 0!==t.sessionKey&&e.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach((([t,s])=>e.append(t,"string"==typeof s?s:JSON.stringify(s)))),e}}class y{constructor(t){this.requestQueue=[],this.isPaused=!1,this.debouncedFlush=e((()=>this.flush()),3e3,{maxWait:15e3}),this.api=t.api}log(t){this.requestQueue.push(t),this.isPaused||this.debouncedFlush()}flush(t=!1){0!==this.requestQueue.length&&(t?this.api.logBeacon(this.requestQueue):this.api.logRequest(this.requestQueue),this.requestQueue=[],this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}}class f{constructor(e,s){this.statContext=e;const o=new t;this.experimental={error$:o};const i=new g({apiKey:"CIOPGQJGDIHBABABA",apiBaseUrl:l[s.apiEnv],error$:o});this.api=new m({apiTransport:i,refreshAuthToken:s.refreshAuthToken}),this.logger=new y({api:this.api}),window.addEventListener("beforeunload",(()=>this.logger.flush(!0)))}updateContext(t){this.statContext=Object.assign(Object.assign({},this.statContext),t)}authorize(t){return this.api.authorize(t)}pause(){this.logger.pause()}resume(){this.logger.resume()}logStarted(){this.log({operation:"play"})}logPlay(){this.log({operation:"play_toggle"})}logPause(t){this.log({operation:"pause",param:String(Math.round(t.position))})}logSeek(){this.log({operation:"seek"})}logFirstBytes(t){this.log({operation:"first_bytes",param:String(t.time)})}logFirstFrame(t){this.log({operation:"first_frame",param:String(t.time)})}logError(t){this.log({operation:"error",param:t.errorType})}logWatchCoverageRecord(t){this.log({operation:"watch_coverage_record",param:`${t.start}-${t.end}`}),this.logger.flush(!0)}logWatchCoverageLive(t){this.log({operation:"watch_coverage_live",param:`${t.start}-${t.end}`})}logEmptyBuffer(t){this.log({operation:"empty_buffer",param:String(t.duration)})}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(t){this.log({operation:"adv",param:t})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}log(t){const e=this.crateLogItem(t);this.logger.log(e)}crateLogItem({operation:t,param:e}){const s=Date.now(),o={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:!0===this.statContext.connectionReused?p.YES:!1===this.statContext.connectionReused?p.NO:void 0,stat_type:!0===this.statContext.autoplay?h.AUTO:!1===this.statContext.autoplay?h.MANUAL:void 0,vk_playlist_id:this.statContext.vkPlaylistId,vk_app_id:this.statContext.vkAppId};return void 0!==e&&(o.param=e),{operation:t,timestamp:s,custom:o}}}export{i as ApiEnv,u as ConnectionType,n as ContentType,f as OneStat,r as Quality,a as ScreenDestination};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vkontakte/videoplayer-statistics",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.9",
|
|
4
4
|
"author": "vk.com",
|
|
5
5
|
"description": "Statistics library for vk.com videoplayer",
|
|
6
6
|
"homepage": "https://vk.com",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"**/*.d.ts"
|
|
15
15
|
],
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@vkontakte/videoplayer-shared": "1.0.
|
|
17
|
+
"@vkontakte/videoplayer-shared": "1.0.7",
|
|
18
18
|
"lodash": "4.17.21"
|
|
19
19
|
}
|
|
20
20
|
}
|
package/types.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export declare enum ApiEnv {
|
|
2
2
|
PROD = "prod",
|
|
3
|
+
VK_ALIAS = "vk_alias",
|
|
3
4
|
VIDEOTEST = "videotest",
|
|
4
5
|
TEST = "test"
|
|
5
6
|
}
|
|
@@ -32,3 +33,12 @@ export declare enum StatType {
|
|
|
32
33
|
AUTO = "auto",
|
|
33
34
|
MANUAL = ""
|
|
34
35
|
}
|
|
36
|
+
export declare enum ConnectionType {
|
|
37
|
+
HTTP1 = "http1",
|
|
38
|
+
HTTP2 = "http2",
|
|
39
|
+
HTTP3 = "http3"
|
|
40
|
+
}
|
|
41
|
+
export declare enum ConnectionReused {
|
|
42
|
+
YES = 1,
|
|
43
|
+
NO = 0
|
|
44
|
+
}
|