code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
get tabs() {
return {};
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
tabs
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
constructor(options) {
this.options = options;
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
constructor
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
get urlPattern() {
return /^https:\/\/(www\.)?gitlab\.com/;
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
urlPattern
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
get searchBoxSelector() {
return '.form-input, input[id=search]';
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
searchBoxSelector
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
getTopMargin(element) {
return getFixedSearchBoxTopMargin(
document.querySelector('header.navbar'),
element,
);
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
getTopMargin
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
onChangedResults(callback) {
const containers = document.querySelectorAll(
'.projects-list, .groups-list, #content-body',
);
const observer = new MutationObserver(async (mutationsList, observer) => {
callback(true);
});
for (const container of containers) {
observer.observe(container, {
attributes: false,
childList: true,
subtree: true,
});
}
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
onChangedResults
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
getSearchResults() {
const includedElements = [
{
nodes: document.querySelectorAll('li.project-row h2 a'),
containerSelector: (n) => n.closest('li.project-row'),
highlightedElementSelector: (n) => n.closest('li.project-row'),
highlightClass: 'wsn-gitlab-focused-group-row',
},
// Org subgroups, for example:
// https://gitlab.archlinux.org/archlinux
{
nodes: document.querySelectorAll(
'ul.groups-list li.group-row a[aria-label]',
),
containerSelector: (n) => n.closest('li.group-row'),
highlightedElementSelector: (n) => n.closest('li.group-row'),
highlightClass: 'wsn-gitlab-focused-group-row',
},
// Prev/next page
{
nodes: document.querySelectorAll('li.page-item a.page-link'),
containerSelector: (n) => n.closest('li.page-item'),
highlightedElementSelector: (n) => n.closest('li.group-row'),
highlightClass: 'wsn-gitlab-focused-group-row',
},
];
return getSortedSearchResults(includedElements);
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
getSearchResults
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
get urlPattern() {
return new RegExp(this.options.customGitlabUrl);
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
urlPattern
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
getSearchEngine = (options) => {
const searchEngines = [
new GoogleSearch(options),
new BraveSearch(options),
new StartPage(options),
new YouTube(options),
new GoogleScholar(options),
new Amazon(options),
new Github(options),
new Gitlab(options),
new CustomGitlab(options),
];
// Switch over all compatible search engines
const href = window.location.href;
for (let i = 0; i < searchEngines.length; i++) {
if (href.match(searchEngines[i].urlPattern)) {
return searchEngines[i];
}
}
return null;
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
getSearchEngine
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
getSearchEngine = (options) => {
const searchEngines = [
new GoogleSearch(options),
new BraveSearch(options),
new StartPage(options),
new YouTube(options),
new GoogleScholar(options),
new Amazon(options),
new Github(options),
new Gitlab(options),
new CustomGitlab(options),
];
// Switch over all compatible search engines
const href = window.location.href;
for (let i = 0; i < searchEngines.length; i++) {
if (href.match(searchEngines[i].urlPattern)) {
return searchEngines[i];
}
}
return null;
}
|
Filter the results based on special properties
@param {*} period, filter identifier. Accepted filter are :
'a' : all results
'h' : last hour
'd' : last day
'w' : last week
'm' : last month
'y' : last year
'v' : verbatim search
null : toggle sort
|
getSearchEngine
|
javascript
|
infokiller/web-search-navigator
|
src/search_engines.js
|
https://github.com/infokiller/web-search-navigator/blob/master/src/search_engines.js
|
MIT
|
invoke(id, args) {
if (id === undefined) {
return
}
const obj = this.callbacks[id]
if (obj && isFunction(obj.callback)) {
obj.callback(args)
if (!obj.keep) {
delete this.callbacks[id]
}
}
}
|
[Container] triggerCallback -> [Service] invoke
@param {*} id
@param {*} args
|
invoke
|
javascript
|
didi/dimina
|
fe/packages/common/src/core/callback.js
|
https://github.com/didi/dimina/blob/master/fe/packages/common/src/core/callback.js
|
Apache-2.0
|
remove(id) {
if (id) {
Object.keys(this.callbacks).forEach((k) => {
if (id === k) {
delete this.callbacks[k]
}
})
}
else {
Object.entries(this.callbacks).forEach(([k, v]) => {
if (v.keep) {
delete this.callbacks[k]
}
})
}
}
|
[Container] triggerCallback -> [Service] invoke
@param {*} id
@param {*} args
|
remove
|
javascript
|
didi/dimina
|
fe/packages/common/src/core/callback.js
|
https://github.com/didi/dimina/blob/master/fe/packages/common/src/core/callback.js
|
Apache-2.0
|
function invokeAPI(apiName, { params, bridgeId }) {
window.__message.invoke({
type: 'invokeAPI',
target: 'container',
body: {
name: apiName,
bridgeId,
params,
},
})
}
|
https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxml/event.html
@param {*} methodName
@param {*} param
|
invokeAPI
|
javascript
|
didi/dimina
|
fe/packages/components/src/common/events.js
|
https://github.com/didi/dimina/blob/master/fe/packages/components/src/common/events.js
|
Apache-2.0
|
function generateColorFromName(name) {
// If name is empty, return a default color (Material Blue)
if (!name || name.length === 0) {
return '#2196F3'
}
// Use the hash code of the name as a seed for color generation
let hash = 0
for (let i = 0; i < name.length; i++) {
hash = ((hash << 5) - hash) + name.charCodeAt(i)
hash |= 0 // Convert to 32bit integer
}
// Generate HSV color with consistent hue based on name
// Use a limited range of saturation and value for visually pleasing colors
const hue = Math.abs(hash % 360)
const saturation = 0.7 + (Math.abs(hash % 3000) / 10000) // Range: 0.7-1.0
const value = 0.8 + (Math.abs(hash % 2000) / 10000) // Range: 0.8-1.0
// Convert HSV to RGB
const rgbColor = hsvToRgb(hue, saturation, value)
// Convert RGB to hex
return rgbToHex(rgbColor[0], rgbColor[1], rgbColor[2])
}
|
Generates a consistent color based on the name's hash code
@param {string} name - The name to generate a color from
@returns {string} - A hex color code
|
generateColorFromName
|
javascript
|
didi/dimina
|
fe/packages/container/src/services/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/container/src/services/index.js
|
Apache-2.0
|
function hsvToRgb(h, s, v) {
let r, g, b
const i = Math.floor(h / 60)
const f = h / 60 - i
const p = v * (1 - s)
const q = v * (1 - f * s)
const t = v * (1 - (1 - f) * s)
/* eslint-disable style/max-statements-per-line */
switch (i % 6) {
case 0: r = v; g = t; b = p; break
case 1: r = q; g = v; b = p; break
case 2: r = p; g = v; b = t; break
case 3: r = p; g = q; b = v; break
case 4: r = t; g = p; b = v; break
case 5: r = v; g = p; b = q; break
}
/* eslint-enable style/max-statements-per-line */
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
}
|
Converts HSV color values to RGB
@param {number} h - Hue (0-360)
@param {number} s - Saturation (0-1)
@param {number} v - Value (0-1)
@returns {number[]} - Array of [r, g, b] values (0-255)
|
hsvToRgb
|
javascript
|
didi/dimina
|
fe/packages/container/src/services/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/container/src/services/index.js
|
Apache-2.0
|
function rgbToHex(r, g, b) {
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`
}
|
Converts RGB values to a hex color string
@param {number} r - Red (0-255)
@param {number} g - Green (0-255)
@param {number} b - Blue (0-255)
@returns {string} - Hex color code
|
rgbToHex
|
javascript
|
didi/dimina
|
fe/packages/container/src/services/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/container/src/services/index.js
|
Apache-2.0
|
function generateLogo(app) {
const size = [60, 60]
const cvs = document.createElement('canvas')
cvs.setAttribute('width', size[0])
cvs.setAttribute('height', size[1])
const ctx = cvs.getContext('2d')
// Use the new color generation function instead of random colors
ctx.fillStyle = generateColorFromName(app.name)
ctx.fillRect(0, 0, size[0], size[1])
ctx.fillStyle = 'rgb(255,255,255)'
ctx.font = `${size[0] * 0.6}px Arial`
ctx.textBaseline = 'middle'
ctx.textAlign = 'center'
ctx.fillText(app.name.charAt(0), size[0] / 2, size[1] / 2)
return cvs.toDataURL('image/jpeg', 1)
}
|
Converts RGB values to a hex color string
@param {number} r - Red (0-255)
@param {number} g - Green (0-255)
@param {number} b - Blue (0-255)
@returns {string} - Hex color code
|
generateLogo
|
javascript
|
didi/dimina
|
fe/packages/container/src/services/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/container/src/services/index.js
|
Apache-2.0
|
setInitialData(initialData) {
for (const [path, data] of Object.entries(initialData)) {
if (!data) {
continue
}
const module = this.staticModules[path]
if (!module) {
continue
}
module.setInitialData(data)
}
}
|
serviceResourceLoaded && renderResourceLoaded ->
[Container]resourceLoaded -> [Service]resourceLoaded -> [Service]initialDataReady -> [Container]initialDataReady -> [Render]setInitialData
@param {*} initialData
|
setInitialData
|
javascript
|
didi/dimina
|
fe/packages/render/src/core/loader.js
|
https://github.com/didi/dimina/blob/master/fe/packages/render/src/core/loader.js
|
Apache-2.0
|
getModuleByPath(path) {
return this.staticModules[path]
}
|
serviceResourceLoaded && renderResourceLoaded ->
[Container]resourceLoaded -> [Service]resourceLoaded -> [Service]initialDataReady -> [Container]initialDataReady -> [Render]setInitialData
@param {*} initialData
|
getModuleByPath
|
javascript
|
didi/dimina
|
fe/packages/render/src/core/loader.js
|
https://github.com/didi/dimina/blob/master/fe/packages/render/src/core/loader.js
|
Apache-2.0
|
isElementReady(element) {
if (!element) {
return false
}
const rect = element.getBoundingClientRect()
return rect.height > 0 || rect.width > 0
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/wxml/NodesRef.fields.html
|
isElementReady
|
javascript
|
didi/dimina
|
fe/packages/render/src/core/runtime.js
|
https://github.com/didi/dimina/blob/master/fe/packages/render/src/core/runtime.js
|
Apache-2.0
|
function getSystemInfo(opts) {
return new Promise((resolve) => {
resolve(invokeAPI('getSystemInfo', opts))
})
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/base/system/wx.getSystemInfo.html
|
getSystemInfo
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/base/system/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/base/system/index.js
|
Apache-2.0
|
function getSystemInfoSync() {
return invokeAPI('getSystemInfoSync')
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/base/system/wx.getSystemInfoSync.html
|
getSystemInfoSync
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/base/system/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/base/system/index.js
|
Apache-2.0
|
function getSystemInfoAsync(opts) {
invokeAPI('getSystemInfoAsync', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/base/system/wx.getSystemInfoAsync.html
|
getSystemInfoAsync
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/base/system/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/base/system/index.js
|
Apache-2.0
|
function makePhoneCall(opts) {
invokeAPI('makePhoneCall', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/device/phone/wx.makePhoneCall.html
|
makePhoneCall
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/device/phone/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/device/phone/index.js
|
Apache-2.0
|
function scanCode(opts) {
invokeAPI('scanCode', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/device/scan/wx.scanCode.html
|
scanCode
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/device/scan/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/device/scan/index.js
|
Apache-2.0
|
function login(opts) {
invokeAPI('login', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
|
login
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/open-api/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/open-api/index.js
|
Apache-2.0
|
function setStorageSync(...opts) {
invokeAPI('setStorageSync', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorageSync.html
|
setStorageSync
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/storage/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
|
Apache-2.0
|
function removeStorageSync(...opts) {
return invokeAPI('removeStorageSync', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorageSync.html
|
removeStorageSync
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/storage/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
|
Apache-2.0
|
function setStorage(opts) {
invokeAPI('setStorage', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorage.html
|
setStorage
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/storage/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
|
Apache-2.0
|
function getStorage(opts) {
invokeAPI('getStorage', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorage.html
|
getStorage
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/storage/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
|
Apache-2.0
|
function removeStorage(opts) {
invokeAPI('removeStorage', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorage.html
|
removeStorage
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/storage/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
|
Apache-2.0
|
function getStorageInfoSync(...opts) {
return invokeAPI('getStorageInfoSync', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageInfoSync.html
|
getStorageInfoSync
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/storage/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
|
Apache-2.0
|
function getStorageInfo(opts) {
invokeAPI('getStorageInfo', opts)
}
|
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageInfo.html
|
getStorageInfo
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/storage/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/storage/index.js
|
Apache-2.0
|
selectViewport() {
return new NodesRef(this, router.getPageInfo().id, '', true)
}
|
@param {*} selector
@param {*} moduleId
@param {*} single
@param {*} fields
@param {*} callback
|
selectViewport
|
javascript
|
didi/dimina
|
fe/packages/service/src/api/core/wxml/selector-query/index.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/api/core/wxml/selector-query/index.js
|
Apache-2.0
|
constructor(moduleInfo, extraInfo) {
this.moduleInfo = moduleInfo
this.extraInfo = extraInfo
this.type = ComponentModule.type
this.isComponent = this.extraInfo.component
this.behaviors = this.moduleInfo.behaviors
this.usingComponents = this.extraInfo.usingComponents
this.noReferenceData = filterData(this.moduleInfo.data || {})
mergeBehaviors(this.moduleInfo, this.behaviors)
}
|
@param {{data: object, lifetimes: object, pageLifetimes: object, methods: object, options: object, properties: object}} moduleInfo
|
constructor
|
javascript
|
didi/dimina
|
fe/packages/service/src/instance/component/component-module.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/instance/component/component-module.js
|
Apache-2.0
|
getProps() {
let props = serializeProps(this.moduleInfo.properties)
if (Array.isArray(this.moduleInfo.externalClasses) && this.moduleInfo.externalClasses.length > 0) {
if (!props) {
props = {}
}
for (const externalClass of this.moduleInfo.externalClasses) {
props[externalClass] = {
type: ['s'],
cls: true,
}
}
}
return props
}
|
@param {{data: object, lifetimes: object, pageLifetimes: object, methods: object, options: object, properties: object}} moduleInfo
|
getProps
|
javascript
|
didi/dimina
|
fe/packages/service/src/instance/component/component-module.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/instance/component/component-module.js
|
Apache-2.0
|
constructor(module, opts) {
this.initd = false
this.opts = opts
if (opts.targetInfo) {
this.id = opts.targetInfo.id
this.dataset = opts.targetInfo.dataset
this.__targetInfo__ = opts.targetInfo
}
this.is = opts.path
this.renderer = 'webview'
this.bridgeId = opts.bridgeId
this.behaviors = module.behaviors
this.data = cloneDeep(module.noReferenceData)
this.__isComponent__ = module.isComponent
this.__type__ = module.type
this.__id__ = this.opts.moduleId
this.__info__ = module.moduleInfo
this.__eventAttr__ = opts.eventAttr
this.__pageId__ = opts.pageId
this.__parentId__ = opts.parentId
this.#init()
}
|
https://developers.weixin.qq.com/miniprogram/dev/reference/api/Component.html
|
constructor
|
javascript
|
didi/dimina
|
fe/packages/service/src/instance/component/component.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/instance/component/component.js
|
Apache-2.0
|
setData(data) {
const fData = filterData(data)
for (const key in fData) {
set(this.data, key, fData[key])
}
if (!this.initd) {
return
}
message.send({
type: 'u',
target: 'render',
body: {
bridgeId: this.bridgeId,
moduleId: this.__id__,
data: fData,
},
})
}
|
https://developers.weixin.qq.com/miniprogram/dev/framework/performance/tips/runtime_setData.html
@param {*} data
|
setData
|
javascript
|
didi/dimina
|
fe/packages/service/src/instance/component/component.js
|
https://github.com/didi/dimina/blob/master/fe/packages/service/src/instance/component/component.js
|
Apache-2.0
|
setOption(option, value) {
this._setOption(option, value);
this._checkOptionTypes();
}
|
Set a configuration option.
@param {string} option
@param {*} value
|
setOption
|
javascript
|
DoctorMcKay/node-steam-user
|
index.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/index.js
|
MIT
|
setOptions(options) {
for (let i in options) {
this._setOption(i, options[i]);
}
this._checkOptionTypes();
}
|
Set one or more configuration options
@param {OptionsObject} options
|
setOptions
|
javascript
|
DoctorMcKay/node-steam-user
|
index.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/index.js
|
MIT
|
_checkOptionTypes() {
// We'll infer types from DefaultOptions, but stuff that's null (for example) needs to be defined explicitly
let types = {
socksProxy: 'string',
httpProxy: 'string',
localAddress: 'string',
localPort: 'number',
machineIdFormat: 'array'
};
for (let opt in DefaultOptions) {
if (types[opt]) {
// already specified
continue;
}
types[opt] = typeof DefaultOptions[opt];
}
for (let opt in this.options) {
if (!types[opt]) {
// no type specified for this option, so bail
continue;
}
let requiredType = types[opt];
let providedType = typeof this.options[opt];
if (providedType == 'object' && Array.isArray(this.options[opt])) {
providedType = 'array';
} else if (requiredType == 'number' && providedType == 'string' && !isNaN(this.options[opt])) {
providedType = 'number';
this.options[opt] = parseFloat(this.options[opt]);
}
if (this.options[opt] !== null && requiredType != providedType) {
this._warn(`Incorrect type '${providedType}' provided for option ${opt}, '${requiredType}' expected. Resetting to default value ${DefaultOptions[opt]}`);
this._setOption(opt, DefaultOptions[opt]);
}
}
}
|
Make sure that the types of all options are valid.
@private
|
_checkOptionTypes
|
javascript
|
DoctorMcKay/node-steam-user
|
index.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/index.js
|
MIT
|
_resetExponentialBackoff(backoffName, dontClearBackoffTime) {
if (this._exponentialBackoffs[backoffName]) {
this.emit('debug-verbose', `[EBO] ${dontClearBackoffTime ? 'Soft-resetting' : 'Resetting'} exponential backoff "${backoffName}"`);
clearTimeout(this._exponentialBackoffs[backoffName].timeout);
if (!dontClearBackoffTime) {
delete this._exponentialBackoffs[backoffName];
}
}
}
|
@param {string} backoffName
@param {boolean} [dontClearBackoffTime=false]
@protected
|
_resetExponentialBackoff
|
javascript
|
DoctorMcKay/node-steam-user
|
components/00-base.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/00-base.js
|
MIT
|
_exponentialBackoff(backoffName, minimumTimeout, maximumTimeout) {
return new Promise((resolve) => {
let timeout = this._exponentialBackoffs[backoffName]?.lastTimeout ?? 0;
this._resetExponentialBackoff(backoffName); // cancel any outstanding backoffs of this name
timeout *= 2;
timeout = Math.max(timeout, minimumTimeout);
timeout = Math.min(timeout, maximumTimeout);
let isImportant = IMPORTANT_BACKOFFS.includes(backoffName);
this.emit(isImportant ? 'debug' : 'debug-verbose', `[EBO] Queueing exponential backoff "${backoffName}" with timeout ${timeout}`);
this._exponentialBackoffs[backoffName] = {
lastTimeout: timeout,
timeout: setTimeout(resolve, timeout)
};
});
}
|
@param {string} backoffName
@param {number} minimumTimeout
@param {number} maximumTimeout
@return Promise<void>
@protected
|
_exponentialBackoff
|
javascript
|
DoctorMcKay/node-steam-user
|
components/00-base.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/00-base.js
|
MIT
|
_handleConnectionClose(conn) {
let connPrefix = conn.connectionType[0] + conn.connectionId;
// If the message queue is currently enabled, we need to enqueue processing of the connection close.
// Otherwise we might handle the closed connection too early, e.g. before processing ClientLogOnResponse
if (this._useMessageQueue) {
this.emit('debug', `[${connPrefix}] Connection closed, but message queue is active. Enqueueing __CLOSE__`);
this._incomingMessageQueue.push(['__CLOSE__', conn]);
return;
}
this.emit('debug', `[${connPrefix}] Handling connection close`);
if (this._loggingOff) {
// We want to bail, so call _handleLogOff now (normally it's called at the end)
this._handleLogOff(EResult.NoConnection, 'Logged off');
return;
}
this._cleanupClosedConnection();
if (!this.steamID) {
// connection closed while connecting; reconnect
if (this._lastChosenCM) {
// Blacklist this CM from subsequent connection attempts
this._ttlCache.add(`CM_DQ_${this._lastChosenCM.type}_${this._lastChosenCM.endpoint}`, 1, 1000 * 60 * 2);
}
// We save this timeout reference because it's possible that we handle connection close before we fully handle
// a logon response. In that case, we'll cancel this timeout when we handle the logon response.
// This isn't an issue in the reverse case, since a handled logon response will tear down the connection and
// remove all listeners.
this._reconnectForCloseDuringAuthTimeout = setTimeout(() => this._doConnection(), 1000);
} else {
// connection closed while we were connected; fire logoff
this._handleLogOff(EResult.NoConnection, 'NoConnection');
}
}
|
Handle the closure of our underlying connection.
@param {BaseConnection} conn
@protected
|
_handleConnectionClose
|
javascript
|
DoctorMcKay/node-steam-user
|
components/02-connection.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/02-connection.js
|
MIT
|
_cleanupClosedConnection() {
this._connecting = false;
this._loggingOff = false;
this._cancelReconnectTimers(true);
clearInterval(this._heartbeatInterval);
this._connectionClosed = true;
this._incomingMessageQueue = []; // clear the incoming message queue. If we're disconnecting, we don't care about anything else in the queue.
this._clearChangelistUpdateTimer();
}
|
Handle the closure of our underlying connection.
@param {BaseConnection} conn
@protected
|
_cleanupClosedConnection
|
javascript
|
DoctorMcKay/node-steam-user
|
components/02-connection.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/02-connection.js
|
MIT
|
_cancelReconnectTimers(dontClearBackoffTime) {
this._resetExponentialBackoff('logOn', dontClearBackoffTime);
this._resetExponentialBackoff('webLogOn', dontClearBackoffTime);
clearTimeout(this._reconnectForCloseDuringAuthTimeout);
}
|
Handle the closure of our underlying connection.
@param {BaseConnection} conn
@protected
|
_cancelReconnectTimers
|
javascript
|
DoctorMcKay/node-steam-user
|
components/02-connection.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/02-connection.js
|
MIT
|
_getProxyAgent() {
if (this.options.socksProxy && this.options.httpProxy) {
throw new Error('Cannot specify both socksProxy and httpProxy options');
}
if (this.options.socksProxy) {
return new SocksProxyAgent(this.options.socksProxy);
}
if (this.options.httpProxy) {
return StdLib.HTTP.getProxyAgent(true, this.options.httpProxy);
}
return undefined;
}
|
Handle the closure of our underlying connection.
@param {BaseConnection} conn
@protected
|
_getProxyAgent
|
javascript
|
DoctorMcKay/node-steam-user
|
components/02-connection.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/02-connection.js
|
MIT
|
static _encodeProto(proto, data) {
return proto.encode(data).finish();
}
|
Encode a protobuf.
@param {object} proto - The protobuf class
@param {object} data - The data to serialize
@returns {Buffer}
@protected
|
_encodeProto
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
static _decodeProto(proto, encoded) {
if (ByteBuffer.isByteBuffer(encoded)) {
encoded = encoded.toBuffer();
}
let decoded = proto.decode(encoded);
let objNoDefaults = proto.toObject(decoded, {longs: String});
let objWithDefaults = proto.toObject(decoded, {defaults: true, longs: String});
return replaceDefaults(objNoDefaults, objWithDefaults);
function replaceDefaults(noDefaults, withDefaults) {
if (Array.isArray(withDefaults)) {
return withDefaults.map((val, idx) => replaceDefaults(noDefaults[idx], val));
}
for (let i in withDefaults) {
if (!Object.hasOwnProperty.call(withDefaults, i)) {
continue;
}
if (withDefaults[i] && typeof withDefaults[i] === 'object' && !Buffer.isBuffer(withDefaults[i])) {
// Covers both object and array cases, both of which will work
// Won't replace empty arrays, but that's desired behavior
withDefaults[i] = replaceDefaults(noDefaults[i], withDefaults[i]);
} else if (typeof noDefaults[i] === 'undefined' && isReplaceableDefaultValue(withDefaults[i])) {
withDefaults[i] = null;
}
}
return withDefaults;
}
function isReplaceableDefaultValue(val) {
if (Buffer.isBuffer(val) && val.length == 0) {
// empty buffer is replaceable
return true;
}
if (Array.isArray(val)) {
// empty array is not replaceable (empty repeated fields)
return false;
}
if (val === '0') {
// Zero as a string is replaceable (64-bit integer)
return true;
}
// Anything falsy is true
return !val;
}
}
|
Decode a protobuf.
@param {object} proto - The protobuf class
@param {Buffer|ByteBuffer} encoded - The data to decode
@returns {object}
@protected
|
_decodeProto
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
function replaceDefaults(noDefaults, withDefaults) {
if (Array.isArray(withDefaults)) {
return withDefaults.map((val, idx) => replaceDefaults(noDefaults[idx], val));
}
for (let i in withDefaults) {
if (!Object.hasOwnProperty.call(withDefaults, i)) {
continue;
}
if (withDefaults[i] && typeof withDefaults[i] === 'object' && !Buffer.isBuffer(withDefaults[i])) {
// Covers both object and array cases, both of which will work
// Won't replace empty arrays, but that's desired behavior
withDefaults[i] = replaceDefaults(noDefaults[i], withDefaults[i]);
} else if (typeof noDefaults[i] === 'undefined' && isReplaceableDefaultValue(withDefaults[i])) {
withDefaults[i] = null;
}
}
return withDefaults;
}
|
Decode a protobuf.
@param {object} proto - The protobuf class
@param {Buffer|ByteBuffer} encoded - The data to decode
@returns {object}
@protected
|
replaceDefaults
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
function isReplaceableDefaultValue(val) {
if (Buffer.isBuffer(val) && val.length == 0) {
// empty buffer is replaceable
return true;
}
if (Array.isArray(val)) {
// empty array is not replaceable (empty repeated fields)
return false;
}
if (val === '0') {
// Zero as a string is replaceable (64-bit integer)
return true;
}
// Anything falsy is true
return !val;
}
|
Decode a protobuf.
@param {object} proto - The protobuf class
@param {Buffer|ByteBuffer} encoded - The data to decode
@returns {object}
@protected
|
isReplaceableDefaultValue
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
_send(emsgOrHeader, body, callback) {
// header fields: msg, proto, sourceJobID, targetJobID
let header = typeof emsgOrHeader === 'object' ? emsgOrHeader : {msg: emsgOrHeader};
let emsg = header.msg;
let canWeSend = this.steamID ||
(
this._tempSteamID &&
[EMsg.ChannelEncryptResponse, EMsg.ClientLogon, EMsg.ClientHello, EMsg.ServiceMethodCallFromClientNonAuthed].includes(emsg)
);
if (!canWeSend) {
// We're disconnected, drop it
this.emit('debug', 'Dropping outgoing message ' + emsg + ' because we\'re not logged on.');
return;
}
const Proto = protobufs[emsg];
if (Proto) {
header.proto = header.proto || {};
body = SteamUserMessages._encodeProto(Proto, body);
} else if (ByteBuffer.isByteBuffer(body)) {
body = body.toBuffer();
}
let jobIdSource = null;
if (callback) {
jobIdSource = ++this._currentJobID;
this._jobs.add(jobIdSource.toString(), callback);
}
let emsgName = EMsg[emsg] || emsg;
if ([EMsg.ServiceMethodCallFromClient, EMsg.ServiceMethodCallFromClientNonAuthed].includes(emsg) && header.proto && header.proto.target_job_name) {
emsgName = header.proto.target_job_name;
}
this.emit(VERBOSE_EMSG_LIST.includes(emsg) ? 'debug-verbose' : 'debug', 'Sending message: ' + emsgName);
// Make the header
let hdrBuf;
if (header.msg == EMsg.ChannelEncryptResponse) {
// since we're setting up the encrypted channel, we use this very minimal header
hdrBuf = ByteBuffer.allocate(4 + 8 + 8, ByteBuffer.LITTLE_ENDIAN);
hdrBuf.writeUint32(header.msg);
hdrBuf.writeUint64(header.targetJobID || JOBID_NONE);
hdrBuf.writeUint64(jobIdSource || header.sourceJobID || JOBID_NONE);
} else if (header.proto) {
// if we have a protobuf header, use that
let shouldIncludeSessionId = ![EMsg.ClientHello, EMsg.ServiceMethodCallFromClientNonAuthed].includes(header.msg);
header.proto.client_sessionid = shouldIncludeSessionId ? (this._sessionID || 0) : 0;
header.proto.steamid = shouldIncludeSessionId ? (this.steamID || this._tempSteamID).getSteamID64() : '0';
header.proto.jobid_source = jobIdSource || header.proto.jobid_source || header.sourceJobID || JOBID_NONE;
header.proto.jobid_target = header.proto.jobid_target || header.targetJobID || JOBID_NONE;
let hdrProtoBuf = SteamUserMessages._encodeProto(Schema.CMsgProtoBufHeader, header.proto);
hdrBuf = ByteBuffer.allocate(4 + 4 + hdrProtoBuf.length, ByteBuffer.LITTLE_ENDIAN);
hdrBuf.writeUint32(header.msg | PROTO_MASK);
hdrBuf.writeUint32(hdrProtoBuf.length);
hdrBuf.append(hdrProtoBuf);
} else {
// this is the standard non-protobuf extended header
hdrBuf = ByteBuffer.allocate(4 + 1 + 2 + 8 + 8 + 1 + 8 + 4, ByteBuffer.LITTLE_ENDIAN);
hdrBuf.writeUint32(header.msg);
hdrBuf.writeByte(36);
hdrBuf.writeUint16(2);
hdrBuf.writeUint64(header.targetJobID || JOBID_NONE);
hdrBuf.writeUint64(jobIdSource || header.sourceJobID || JOBID_NONE);
hdrBuf.writeByte(239);
hdrBuf.writeUint64((this.steamID || this._tempSteamID).getSteamID64());
hdrBuf.writeUint32(this._sessionID || 0);
}
let outputBuffer = Buffer.concat([hdrBuf.flip().toBuffer(), body]);
this.emit('debug-traffic-outgoing', outputBuffer, header.msg);
this._connection.send(outputBuffer);
}
|
@param {int|object} emsgOrHeader
@param {object|Buffer|ByteBuffer} body
@param {function} [callback]
@protected
|
_send
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
_handleNetMessage(buffer, conn, multiId) {
if (conn && conn != this._connection) {
let ghostConnId = conn.connectionType[0] + conn.connectionId;
let expectedConnId = this._connection ? (this._connection.connectionType[0] + this._connection.connectionId) : 'NO CONNECTION';
this.emit('debug', `Received net message from ghost connection ${ghostConnId} (expected ${expectedConnId})`);
return;
}
if (this._useMessageQueue && !multiId) {
// Multi sub-messages skip the queue because we need messages contained in a decoded multi to be processed first
this._incomingMessageQueue.push(arguments);
this.emit('debug', `Enqueued incoming message; queue size is now ${this._incomingMessageQueue.length}`);
return;
}
if (buffer === '__CLOSE__') {
// This is an enqueued connection closure
this._handleConnectionClose(conn);
return;
}
let buf = ByteBuffer.wrap(buffer, ByteBuffer.LITTLE_ENDIAN);
let rawEMsg = buf.readUint32();
let eMsg = rawEMsg & ~PROTO_MASK;
let isProtobuf = !!(rawEMsg & PROTO_MASK);
this.emit('debug-traffic-incoming', buffer, eMsg);
let header = {msg: eMsg};
if ([EMsg.ChannelEncryptRequest, EMsg.ChannelEncryptResult].includes(eMsg)) {
// for encryption setup, we just have a very small header with two fields
header.targetJobID = buf.readUint64().toString();
header.sourceJobID = buf.readUint64().toString();
} else if (isProtobuf) {
// decode the protobuf header
let headerLength = buf.readUint32();
header.proto = SteamUserMessages._decodeProto(Schema.CMsgProtoBufHeader, buf.slice(buf.offset, buf.offset + headerLength));
buf.skip(headerLength);
header.targetJobID = header.proto.jobid_target && header.proto.jobid_target.toString();
header.sourceJobID = header.proto.jobid_source && header.proto.jobid_source.toString();
header.steamID = header.proto.steamid && header.proto.steamid.toString();
header.sessionID = header.proto.client_sessionid;
} else {
// decode the extended header
buf.skip(3); // 1 byte for header size (fixed at 36), 2 bytes for header version (fixed at 2)
header.targetJobID = buf.readUint64().toString();
header.sourceJobID = buf.readUint64().toString();
buf.skip(1); // 1 byte for header canary (fixed at 239)
header.steamID = buf.readUint64().toString();
header.sessionID = buf.readUint32();
}
let sessionID = (header.proto && header.proto.client_sessionid) || header.sessionID;
let steamID = (header.proto && header.proto.steamid) || header.steamID;
let ourCurrentSteamID = this.steamID ? this.steamID.toString() : null;
if (steamID && sessionID && (sessionID != this._sessionID || steamID.toString() != ourCurrentSteamID) && steamID != 0) {
// TODO if we get a new sessionid, should we check if it matches a previously-closed session? probably not necessary...
this._sessionID = sessionID;
this.steamID = new SteamID(steamID.toString());
delete this._tempSteamID;
}
this._handleMessage(header, buf.slice(), conn, multiId);
}
|
Handles a raw binary netmessage by parsing the header and routing it appropriately
@param {Buffer|string} buffer
@param {BaseConnection} [conn]
@param {string} [multiId]
@protected
|
_handleNetMessage
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
_handleMessage(header, bodyBuf, conn, multiId) {
// Is this a multi? If yes, short-circuit and just process it now.
if (header.msg == EMsg.Multi) {
this._processMulti(header, SteamUserMessages._decodeProto(protobufs[EMsg.Multi], bodyBuf), conn);
return;
}
let msgName = EMsg[header.msg] || header.msg;
let handlerName = header.msg;
let debugPrefix = multiId ? `[${multiId}] ` : (conn ? `[${conn.connectionType[0]}${conn.connectionId}] ` : '');
let isServiceMethodMsg = [EMsg.ServiceMethod, EMsg.ServiceMethodResponse].includes(header.msg);
if (isServiceMethodMsg) {
if (header.proto && header.proto.target_job_name) {
handlerName = msgName = header.proto.target_job_name;
if (header.msg == EMsg.ServiceMethodResponse) {
handlerName += '_Response';
msgName += '_Response';
}
} else {
this.emit('debug', debugPrefix + 'Got ' + (header.msg == EMsg.ServiceMethod ? 'ServiceMethod' : 'ServiceMethodResponse') + ' without target_job_name');
return;
}
}
if (!isServiceMethodMsg && header.proto && header.proto.target_job_name) {
this.emit('debug', debugPrefix + 'Got unknown target_job_name ' + header.proto.target_job_name + ' for msg ' + msgName);
}
if (!this._handlerManager.hasHandler(handlerName) && this._jobs.get(header.targetJobID.toString()) === null) {
this.emit(VERBOSE_EMSG_LIST.includes(header.msg) ? 'debug-verbose' : 'debug', debugPrefix + 'Unhandled message: ' + msgName);
return;
}
let body = bodyBuf;
if (protobufs[handlerName]) {
body = SteamUserMessages._decodeProto(protobufs[handlerName], bodyBuf);
}
let handledMessageDebugMsg = debugPrefix + 'Handled message: ' + msgName;
if (header.msg == EMsg.ClientLogOnResponse) {
handledMessageDebugMsg += ` (${EResult[body.eresult] || body.eresult})`;
}
this.emit(VERBOSE_EMSG_LIST.includes(header.msg) ? 'debug-verbose' : 'debug', handledMessageDebugMsg);
let cb = null;
if (header.sourceJobID != JOBID_NONE) {
// this message expects a response. make a callback we can pass to the end-user.
cb = (emsgOrHeader, body) => {
// once invoked the callback should set the jobid_target
let responseHeader = typeof emsgOrHeader === 'object' ? emsgOrHeader : {msg: emsgOrHeader};
let emsg = responseHeader.msg;
if (protobufs[emsg]) {
responseHeader.proto = {jobid_target: header.sourceJobID};
} else {
responseHeader.targetJobID = header.sourceJobID;
}
this._send(responseHeader, body);
};
}
let jobCallback = this._jobs.get(header.targetJobID.toString());
if (jobCallback) {
// this is a response to something, so invoke the appropriate callback
jobCallback.call(this, body, header, cb);
} else {
this._handlerManager.emit(this, handlerName, body, header, cb);
}
}
|
Handles and routes a parsed message
@param {object} header
@param {ByteBuffer} bodyBuf
@param {BaseConnection} [conn]
@param {string} [multiId]
@protected
|
_handleMessage
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
async _processMulti(header, body, conn) {
let multiId = conn.connectionType[0] + conn.connectionId + '#' + (++this._multiCount);
this.emit('debug-verbose', `=== Processing ${body.size_unzipped ? 'gzipped multi msg' : 'multi msg'} ${multiId} (${body.message_body.length} bytes) ===`);
let payload = body.message_body;
// Enable the message queue while we're unzipping the message (or waiting until the next event loop cycle).
// This prevents any messages from getting processed out of order.
this._useMessageQueue = true;
if (body.size_unzipped) {
try {
payload = await new Promise((resolve, reject) => {
Zlib.gunzip(payload, (err, unzipped) => {
if (err) {
return reject(err);
}
resolve(unzipped);
});
});
} catch (ex) {
this.emit('error', ex);
this._disconnect(true);
return;
}
} else {
// Await a setImmediate promise to guarantee that multi msg processing always takes at least one iteration of the event loop.
// This avoids message queue processing shenanigans. Waiting until the next iteration of the event loop enables
// _handleNetMessage at the end of this method to return immediately, which will thus exit the clear-queue loop
// because the queue got re-enabled. Prevents the queue from being cleared in multiple places at once.
await new Promise(resolve => setImmediate(resolve));
}
if (!this._connection || this._connection != conn) {
this.emit('debug', `=== Bailing out on processing multi msg ${multiId} because our connection is ${!this._connection ? 'lost' : 'different'}! ===`);
return;
}
while (payload.length && (this.steamID || this._tempSteamID)) {
let subSize = payload.readUInt32LE(0);
this._handleNetMessage(payload.slice(4, 4 + subSize), conn, multiId);
payload = payload.slice(4 + subSize);
}
this.emit('debug-verbose', `=== Finished processing multi msg ${multiId}; now clearing queue of size ${this._incomingMessageQueue.length} ===`);
// Go ahead and process anything in the queue now. First disable the message queue. We don't need to worry about
// newly-received messages sneaking in ahead of the queue being cleared, since message processing is synchronous.
// If we encounter another multi msg, the message queue will get re-enabled.
this._useMessageQueue = false;
// Continue to pop items from the message queue until it's empty, or it gets re-enabled. If the message queue gets
// re-enabled, immediately stop popping items from it to avoid stuff getting out of order.
while (this._incomingMessageQueue.length > 0 && !this._useMessageQueue) {
this._handleNetMessage.apply(this, this._incomingMessageQueue.shift());
}
if (this._incomingMessageQueue.length > 0) {
this.emit('debug-verbose', `[${multiId}] Message queue processing ended early with ${this._incomingMessageQueue.length} elements remaining`);
}
}
|
@param {object} header
@param {object} body
@param {object} conn
@returns {Promise<void>}
@protected
|
_processMulti
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
_sendUnified(methodName, methodData, callback) {
let Proto = protobufs[methodName + (callback ? '_Request' : '')];
let header = {
msg: EMsg.ServiceMethodCallFromClient,
proto: {
target_job_name: methodName
}
};
this._send(header, SteamUserMessages._encodeProto(Proto, methodData), callback);
}
|
Send a unified message.
@param {string} methodName - In format Interface.Method#Version, e.g. Foo.DoThing#1
@param {object} methodData
@param {function} [callback]
@protected
|
_sendUnified
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
_getLoginSession() {
if (!this._loginSession) {
let options = {
transport: new CMAuthTransport(this),
machineId: this._logOnDetails?.machine_id
};
let customMachineName = this._logOnDetails?.machine_name || '';
if (customMachineName.length > 0) {
options.machineFriendlyName = customMachineName;
}
this._loginSession = new LoginSession(EAuthTokenPlatformType.SteamClient, options);
}
return this._loginSession;
}
|
Send a unified message.
@param {string} methodName - In format Interface.Method#Version, e.g. Foo.DoThing#1
@param {object} methodData
@param {function} [callback]
@protected
|
_getLoginSession
|
javascript
|
DoctorMcKay/node-steam-user
|
components/03-messages.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/03-messages.js
|
MIT
|
static formatCurrency(amount, currency) {
let amountString = amount.toFixed(2);
if (!CurrencyData[currency]) {
return amountString;
}
let data = CurrencyData[currency];
if (data.whole) {
amountString = amountString.replace('.00', '');
}
if (data.commas) {
amountString = amountString.replace('.', ',');
}
return (data.prepend || '') + amountString + (data.append || '');
}
|
@param {number} amount
@param {ECurrencyCode} currency
@returns {string}
|
formatCurrency
|
javascript
|
DoctorMcKay/node-steam-user
|
components/04-utility.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/04-utility.js
|
MIT
|
async _saveFile(filename, content) {
try {
if (this.storage) {
await this.storage.saveFile(filename, content);
}
} catch (ex) {
this.emit('debug', `Error saving file ${filename}: ${ex.message}`);
}
}
|
@param {string} filename
@param {Buffer|*} content
@return {Promise}
@protected
|
_saveFile
|
javascript
|
DoctorMcKay/node-steam-user
|
components/05-filestorage.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/05-filestorage.js
|
MIT
|
async _readFile(filename) {
let content = null;
try {
if (this.storage) {
content = await this.storage.readFile(filename);
}
} catch (ex) {
this.emit('debug', `Error reading file ${filename}: ${ex.message}`);
}
return content;
}
|
@param {string} filename
@returns {Promise<Buffer|null>}
@protected
|
_readFile
|
javascript
|
DoctorMcKay/node-steam-user
|
components/05-filestorage.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/05-filestorage.js
|
MIT
|
async _readFiles(filenames) {
if (!this.storage) {
return filenames.map(filename => ({filename, error: new Error('Storage system disabled')}));
}
// No need for a try/catch because readFiles can't reject
return await this.storage.readFiles(filenames);
}
|
@param {string[]} filenames
@returns {Promise<{filename: string, error?: Error, contents?: Buffer}[]>}
@protected
|
_readFiles
|
javascript
|
DoctorMcKay/node-steam-user
|
components/05-filestorage.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/05-filestorage.js
|
MIT
|
async _apiRequest(httpMethod, iface, method, version, data, cacheSeconds) {
data = data || {};
httpMethod = httpMethod.toUpperCase(); // just in case
// Pad the version with zeroes to make it 4 digits long, because Valve
version = version.toString();
while (version.length < 4) {
version = '0' + version;
}
data.format = 'vdf'; // for parity with the Steam client
let client = this._httpClient || new HttpClient({
userAgent: USER_AGENT,
httpsAgent: this._getProxyAgent(),
localAddress: this.options.localAddress,
defaultHeaders: Object.assign(getDefaultHeaders(), this.options.additionalHeaders),
defaultTimeout: 5000,
gzip: true
});
this._httpClient = client;
let url = `https://${HOSTNAME}/${iface}/${method}/v${version}/`;
let cacheKey = `API_${httpMethod}_${url}`;
let cacheValue;
if (cacheSeconds && (cacheValue = this._ttlCache.get(cacheKey))) {
this.emit('debug', `[WebAPI] Using cached value for ${cacheKey}`);
return cacheValue;
}
let headers = {};
let body = null;
if (httpMethod == 'GET') {
url += `?${buildQueryString(data)}`;
} else {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
body = buildQueryString(data);
}
let res = await client.request({
method: httpMethod,
url,
body
});
this.emit('debug', `API ${httpMethod} request to ${url}: ${res.statusCode}`);
if (res.statusCode != 200) {
throw new Error(`HTTP error ${res.statusCode}`);
}
let responseData = VDF.parse(res.textBody);
if (cacheSeconds) {
this._ttlCache.add(cacheKey, responseData, 1000 * cacheSeconds);
}
return responseData;
}
|
@param {string} httpMethod
@param {string} iface
@param {string} method
@param {number} version
@param {object} [data]
@param {number} [cacheSeconds]
@returns {Promise}
@protected
|
_apiRequest
|
javascript
|
DoctorMcKay/node-steam-user
|
components/06-webapi.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/06-webapi.js
|
MIT
|
function buildQueryString(data) {
// We can't use the querystring module's encode because we want binary data to be completely percent-encoded
let str = '';
for (let i in data) {
if (!Object.hasOwnProperty.call(data, i)) {
continue;
}
str += (str ? '&' : '') + i + '=';
if (Buffer.isBuffer(data[i])) {
str += data[i].toString('hex').replace(/../g, '%$&');
} else {
str += encodeURIComponent(data[i]);
}
}
return str;
}
|
@param {string} httpMethod
@param {string} iface
@param {string} method
@param {number} version
@param {object} [data]
@param {number} [cacheSeconds]
@returns {Promise}
@protected
|
buildQueryString
|
javascript
|
DoctorMcKay/node-steam-user
|
components/06-webapi.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/06-webapi.js
|
MIT
|
function getDefaultHeaders() {
return {
Accept: 'text/html,*/*;q=0.9',
'Accept-Encoding': 'gzip,identity,*;q=0',
'Accept-Charset': 'ISO-8859-1,utf-8,*;q=0.7'
};
}
|
@param {string} httpMethod
@param {string} iface
@param {string} method
@param {number} version
@param {object} [data]
@param {number} [cacheSeconds]
@returns {Promise}
@protected
|
getDefaultHeaders
|
javascript
|
DoctorMcKay/node-steam-user
|
components/06-webapi.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/06-webapi.js
|
MIT
|
async _sendLogOn() {
if (this._logOnDetails.account_name && this._logOnDetails.password) {
this.emit('debug', 'Logging on with account name and password; fetching a new refresh token');
let startTime = Date.now();
let authSuccess = await this._performPasswordAuth();
if (!authSuccess) {
// We would have already emitted 'error' so let's just bail now
return;
} else {
this.emit('debug', `Password auth succeeded in ${Date.now() - startTime} ms`);
}
}
// Realistically, this should never need to elapse since at this point we have already established a successful connection
// with the CM. But sometimes, Steam appears to never respond to the logon message. Valve.
this._logonMsgTimeout = setTimeout(() => {
this.emit('debug', 'Logon message timeout elapsed. Attempting relog.');
this._disconnect(true);
this._enqueueLogonAttempt();
}, 5000);
this._send(this._logOnDetails.game_server_token ? EMsg.ClientLogonGameServer : EMsg.ClientLogon, this._logOnDetails);
}
|
Send the actual ClientLogOn message.
@private
|
_sendLogOn
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
_performPasswordAuth() {
return new Promise(async (resolve) => {
this._send(EMsg.ClientHello, {protocol_version: PROTOCOL_VERSION});
let session = this._getLoginSession();
session.on('debug', (...args) => {
this.emit('debug', '[steam-session] ' + args.map(arg => typeof arg == 'object' ? JSON.stringify(arg) : arg).join(' '));
});
session.on('authenticated', () => {
this.emit('refreshToken', session.refreshToken);
this._logOnDetails.access_token = session.refreshToken;
this._logOnDetails.should_remember_password = true;
this._logOnDetails._newAuthAccountName = this._logOnDetails.account_name;
this._logOnDetails._steamid = session.steamID;
delete this._logOnDetails.account_name;
delete this._logOnDetails.password;
delete this._logOnDetails.auth_code;
delete this._logOnDetails.two_factor_code;
this._tempSteamID = session.steamID;
resolve(true);
});
session.on('error', async (err) => {
// LoginSession only emits an `error` event if there's some problem with the actual interface used to
// communicate with Steam. Errors for invalid credentials are handled elsewhere, so we only need to
// emit ServiceUnavailable here since this should be a transient error.
this.emit('debug', `steam-session error: ${err.message}`);
await this._handleLogOnResponse({eresult: EResult.ServiceUnavailable});
resolve(false);
});
session.on('timeout', async () => {
this.emit('debug', 'steam-session timeout');
await this._handleLogOnResponse({eresult: EResult.ServiceUnavailable});
resolve(false);
});
session.on('steamGuardMachineToken', () => {
this._handleNewMachineToken(session.steamGuardMachineToken);
});
let sessionStartResult = null;
try {
sessionStartResult = await session.startWithCredentials({
accountName: this._logOnDetails.account_name,
password: this._logOnDetails.password,
steamGuardMachineToken: this._machineAuthToken,
steamGuardCode: this._logOnDetails.two_factor_code || this._logOnDetails.auth_code
});
} catch (ex) {
// I don't honestly think calling cancelLoginAttempt is ever necessary here, but there's no harm in doing it
session.cancelLoginAttempt();
this.emit('debug', 'steam-session startWithCredentials exception', ex);
await this._handleLogOnResponse({eresult: ex.eresult || EResult.ServiceUnavailable});
return resolve(false);
}
if (sessionStartResult.actionRequired) {
// We need a code of some kind. Technically we could just wait for a device approval, but in the majority
// of consumer use-cases, the app seemingly hanging while waiting for this isn't desirable.
session.cancelLoginAttempt();
// We need to synthesize a LogOnResponse eresult
let logOnResponse = {};
let wantsEmailCode = sessionStartResult.validActions.find(action => action.type == EAuthSessionGuardType.EmailCode);
if (wantsEmailCode) {
logOnResponse.eresult = EResult.AccountLogonDenied;
logOnResponse.email_domain = wantsEmailCode.detail;
} else {
logOnResponse.eresult = this._logOnDetails.two_factor_code ? EResult.TwoFactorCodeMismatch : EResult.AccountLoginDeniedNeedTwoFactor;
}
await this._handleLogOnResponse(logOnResponse);
}
});
}
|
Send the actual ClientLogOn message.
@private
|
_performPasswordAuth
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
_enqueueLogonAttempt() {
this._exponentialBackoff('logOn', 1000, 60000).then(() => {
if (this.steamID || this._connecting) {
// Not sure why this happened, but we're already connected
let whyFail = this.steamID ? 'already connected' : 'already attempting to connect';
this.emit('debug', `!! Attempted to fire queued login attempt, but we're ${whyFail}`);
return;
}
this.emit('debug', 'Firing queued login attempt');
this.logOn(true);
});
}
|
Enqueue another logon attempt.
Used after we get ServiceUnavailable, TryAnotherCM, or a timeout waiting for ClientLogOnResponse.
@private
|
_enqueueLogonAttempt
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
_disconnect(suppressLogoff) {
this._clearChangelistUpdateTimer();
this._incomingMessageQueue = []; // clear the incoming message queue. If we're disconnecting, we don't care about anything else in the queue.
this.emit('debug', 'Disconnecting' + (suppressLogoff ? ' without sending logoff' : ''));
if (this.steamID && !suppressLogoff) {
this._loggingOff = true;
this._send(EMsg.ClientLogOff, {});
let timeout = setTimeout(() => {
this.emit('disconnected', 0, 'Logged off');
this._loggingOff = false;
this._connection && this._connection.end(true);
this.steamID = null;
this._cleanupClosedConnection();
}, 4000);
this.once('disconnected', (eresult) => {
clearTimeout(timeout);
this.steamID = null;
this._cleanupClosedConnection();
});
} else {
this._connection && this._connection.end(true);
this.steamID = null;
this._cleanupClosedConnection();
}
}
|
Disconnect from Steam
@param {boolean} suppressLogoff - If true, just disconnect immediately without sending a logoff message.
@private
|
_disconnect
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
_getMachineID(localFile) {
if (
(
!this._logOnDetails.account_name
&& !this._logOnDetails._steamid
)
|| this.options.machineIdType == EMachineIDType.None
) {
// No machine IDs for anonymous logons
return null;
}
// The user wants to use a random machine ID that's saved to dataDirectory
if (this.options.machineIdType == EMachineIDType.PersistentRandom) {
if (localFile) {
return localFile;
}
let file = getRandomID();
this._saveFile('machineid.bin', file);
return file;
}
// The user wants to use a machine ID that's generated off the account name
if (this.options.machineIdType == EMachineIDType.AccountNameGenerated) {
return createMachineID(
this.options.machineIdFormat[0].replace(/\{account_name\}/g, this._getAccountIdentifier()),
this.options.machineIdFormat[1].replace(/\{account_name\}/g, this._getAccountIdentifier()),
this.options.machineIdFormat[2].replace(/\{account_name\}/g, this._getAccountIdentifier())
);
}
// Default to random
return getRandomID();
function getRandomID() {
return createMachineID(Math.random().toString(), Math.random().toString(), Math.random().toString());
}
}
|
@param {Buffer} [localFile]
@returns {null|Buffer}
@private
|
_getMachineID
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
function getRandomID() {
return createMachineID(Math.random().toString(), Math.random().toString(), Math.random().toString());
}
|
@param {Buffer} [localFile]
@returns {null|Buffer}
@private
|
getRandomID
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
_getAccountIdentifier() {
return this._logOnDetails.account_name
|| this._logOnDetails._newAuthAccountName
|| this._logOnDetails._steamid.toString();
}
|
@param {Buffer} [localFile]
@returns {null|Buffer}
@private
|
_getAccountIdentifier
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
relog() {
if (!this.steamID) {
throw new Error('Cannot relog if not already connected');
}
let relogAvailable = (
this.steamID.type == SteamID.Type.ANON_USER
|| (
this.steamID.type == SteamID.Type.INDIVIDUAL
&& this._logOnDetails
&& this._logOnDetails.access_token
)
);
if (!relogAvailable) {
throw new Error('To use relog(), you must log on using a refresh token or using your account name and password');
}
this._relogging = true;
this.logOff();
}
|
@param {Buffer} [localFile]
@returns {null|Buffer}
@private
|
relog
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
_handleLogOff(result, msg) {
let fatal = true;
let nonFatalLogOffResults = [
0,
EResult.Fail,
EResult.NoConnection,
EResult.ServiceUnavailable,
EResult.TryAnotherCM
];
if (this.options.autoRelogin && nonFatalLogOffResults.includes(result)) {
fatal = false;
}
delete this.publicIP;
delete this.cellID;
this.contentServersReady = false;
this._initProperties();
this._clearChangelistUpdateTimer();
clearInterval(this._heartbeatInterval);
if (!this._relogging && fatal && !this._loggingOff) {
let e = new Error(msg);
e.eresult = result;
let steamID = this.steamID;
this._disconnect(true);
this.steamID = steamID;
this.emit('error', e);
this.steamID = null;
} else {
// Only emit "disconnected" if we were previously logged on
let wasLoggingOff = this._loggingOff; // remember this since our 'disconnected' event handler might reset it
if (this.steamID) {
this.emit('disconnected', result, msg);
}
this._disconnect(true);
// if we're manually relogging, or we got disconnected because steam went down, enqueue a reconnect
if (!wasLoggingOff || this._relogging) {
this._resetExponentialBackoff('logOn');
this._exponentialBackoff('logOn', 1000, 1000).then(() => {
this.logOn(true);
});
}
this._loggingOff = false;
this._relogging = false;
this.steamID = null;
}
}
|
@param {number} result
@param {string} msg
@private
|
_handleLogOff
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
_steamGuardPrompt(domain, lastCodeWrong, callback) {
if (this.listenerCount('steamGuard') == 0) {
// No steamGuard listeners, so prompt for one from stdin
let rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Steam Guard' + (!domain ? ' App' : '') + ' Code: ', function(code) {
rl.close();
callback(code);
});
} else {
this.emit('steamGuard', domain, callback, lastCodeWrong);
}
}
|
@param {string} domain
@param {boolean} lastCodeWrong
@param {function} callback
@private
|
_steamGuardPrompt
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
function createMachineID(val_bb3, val_ff2, val_3b3) {
// Machine IDs are binary KV objects with root key MessageObject and three hashes named BB3, FF2, and 3B3.
// I don't feel like writing a proper BinaryKV serializer, so this will work fine.
let buffer = ByteBuffer.allocate(155, ByteBuffer.LITTLE_ENDIAN);
buffer.writeByte(0); // 1 byte, total 1
buffer.writeCString('MessageObject'); // 14 bytes, total 15
buffer.writeByte(1); // 1 byte, total 16
buffer.writeCString('BB3'); // 4 bytes, total 20
buffer.writeCString(sha1(val_bb3)); // 41 bytes, total 61
buffer.writeByte(1); // 1 byte, total 62
buffer.writeCString('FF2'); // 4 bytes, total 66
buffer.writeCString(sha1(val_ff2)); // 41 bytes, total 107
buffer.writeByte(1); // 1 byte, total 108
buffer.writeCString('3B3'); // 4 bytes, total 112
buffer.writeCString(sha1(val_3b3)); // 41 bytes, total 153
buffer.writeByte(8); // 1 byte, total 154
buffer.writeByte(8); // 1 byte, total 155
return buffer.flip().toBuffer();
function sha1(input) {
let hash = Crypto.createHash('sha1');
hash.update(input, 'utf8');
return hash.digest('hex');
}
}
|
@param {string} domain
@param {boolean} lastCodeWrong
@param {function} callback
@private
|
createMachineID
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
function sha1(input) {
let hash = Crypto.createHash('sha1');
hash.update(input, 'utf8');
return hash.digest('hex');
}
|
@param {string} domain
@param {boolean} lastCodeWrong
@param {function} callback
@private
|
sha1
|
javascript
|
DoctorMcKay/node-steam-user
|
components/09-logon.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/09-logon.js
|
MIT
|
getPrivacySettings(callback) {
return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, (resolve, reject) => {
this._sendUnified('Player.GetPrivacySettings#1', {}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
if (err) {
return reject(err);
}
resolve(body.privacy_settings);
});
});
}
|
Get your account's profile privacy settings.
@param {function} [callback]
@returns {Promise<{privacy_state: int, privacy_state_inventory: int, privacy_state_gifts: int, privacy_state_ownedgames: int, privacy_state_playtime: int, privacy_state_friendslist: int}>}
|
getPrivacySettings
|
javascript
|
DoctorMcKay/node-steam-user
|
components/account.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/account.js
|
MIT
|
createEncryptedAppTicket(appid, userData, callback) {
if (typeof userData === 'function') {
callback = userData;
userData = Buffer.alloc(0);
}
return StdLib.Promises.timeoutCallbackPromise(10000, ['encryptedAppTicket'], callback, (resolve, reject) => {
this._send(EMsg.ClientRequestEncryptedAppTicket, {
app_id: appid,
userdata: userData
}, (body) => {
let err = Helpers.eresultError(body.eresult);
if (err) {
return reject(err);
}
if (body.app_id != appid) {
// Don't know if this can even happen
return reject(new Error('Steam did not send an appticket for the requested appid'));
}
if (!body.encrypted_app_ticket) {
return reject(new Error('No appticket in response'));
}
resolve({
encryptedAppTicket: SteamUserAppAuth._encodeProto(Schema.EncryptedAppTicket, body.encrypted_app_ticket)
});
});
});
}
|
Request an encrypted appticket for a particular app. The app must be set up on the Steam backend for encrypted apptickets.
@param {int} appid - The Steam AppID of the app you want a ticket for
@param {Buffer} [userData] - If the app expects some "user data", provide it here
@param {function} [callback] - First argument is "err", second is the ticket as a Buffer (on success)
@return {Promise}
|
createEncryptedAppTicket
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
getEncryptedAppTicket(appid, userData, callback) {
return this.createEncryptedAppTicket(appid, userData, callback);
}
|
Request an encrypted appticket for a particular app. The app must be set up on the Steam backend for encrypted apptickets.
@param {int} appid - The Steam AppID of the app you want a ticket for
@param {Buffer} [userData] - If the app expects some "user data", provide it here
@param {function} [callback] - First argument is "err", second is the ticket as a Buffer (on success)
@return {Promise}
@deprecated Use createEncryptedAppTicket instead
|
getEncryptedAppTicket
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
static parseEncryptedAppTicket(ticket, encryptionKey) {
return AppTicket.parseEncryptedAppTicket(ticket, encryptionKey);
}
|
@param {Buffer} ticket - The raw encrypted appticket
@param {Buffer|string} encryptionKey - The app's encryption key, either raw hex or a Buffer
@returns {object}
|
parseEncryptedAppTicket
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
static parseAppTicket(ticket, allowInvalidSignature) {
return AppTicket.parseAppTicket(ticket, allowInvalidSignature);
}
|
Parse a Steam app or session ticket and return an object containing its details. Static.
@param {Buffer|ByteBuffer} ticket - The binary appticket
@param {boolean} [allowInvalidSignature=false] - Pass true to get back data even if the ticket has no valid signature.
@returns {object|null} - object if well-formed ticket (may not be valid), or null if not well-formed
|
parseAppTicket
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
createAuthSessionTicket(appid, callback) {
return StdLib.Promises.callbackPromise(['sessionTicket'], callback, (resolve, reject) => {
// For an auth session ticket we need the following:
// 1. Length-prefixed GCTOKEN
// 2. Length-prefixed SESSIONHEADER
// 3. Length-prefixed OWNERSHIPTICKET (yes, even though the ticket itself has a length)
// The GCTOKEN and SESSIONHEADER portion is passed to ClientAuthList for reuse validation
this.getAppOwnershipTicket(appid, (err, ticket) => {
if (err) {
return reject(err);
}
let buildToken = async (err) => {
if (err) {
return reject(err);
}
let gcToken = this._gcTokens.splice(0, 1)[0];
this.emit('debug', `Using GC token ${gcToken.toString('hex')}. We now have ${this._gcTokens.length} tokens left.`);
let buffer = ByteBuffer.allocate(4 + gcToken.length + 4 + 24 + 4 + ticket.length, ByteBuffer.LITTLE_ENDIAN);
buffer.writeUint32(gcToken.length);
buffer.append(gcToken);
buffer.writeUint32(24); // length of the session header, which is always 24 bytes
buffer.writeUint32(1); // unknown 1
buffer.writeUint32(2); // unknown 2
buffer.writeUint32(StdLib.IPv4.stringToInt(this.publicIP)); // external IP
buffer.writeUint32(0); // filler
buffer.writeUint32(Date.now() - this._connectTime); // timestamp
buffer.writeUint32(++this._connectionCount); // connection count
buffer.writeUint32(ticket.length);
buffer.append(ticket);
buffer = buffer.flip().toBuffer();
try {
// We need to activate our ticket
await this.activateAuthSessionTickets(appid, buffer);
resolve({sessionTicket: buffer});
} catch (err) {
reject(err);
}
};
// Do we have any GC tokens?
if (this._gcTokens.length > 0) {
buildToken();
} else {
Helpers.onceTimeout(10000, this, '_gcTokens', buildToken);
}
});
});
}
|
Parse a Steam app or session ticket and return an object containing its details. Static.
@param {Buffer|ByteBuffer} ticket - The binary appticket
@param {boolean} [allowInvalidSignature=false] - Pass true to get back data even if the ticket has no valid signature.
@returns {object|null} - object if well-formed ticket (may not be valid), or null if not well-formed
|
createAuthSessionTicket
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
buildToken = async (err) => {
if (err) {
return reject(err);
}
let gcToken = this._gcTokens.splice(0, 1)[0];
this.emit('debug', `Using GC token ${gcToken.toString('hex')}. We now have ${this._gcTokens.length} tokens left.`);
let buffer = ByteBuffer.allocate(4 + gcToken.length + 4 + 24 + 4 + ticket.length, ByteBuffer.LITTLE_ENDIAN);
buffer.writeUint32(gcToken.length);
buffer.append(gcToken);
buffer.writeUint32(24); // length of the session header, which is always 24 bytes
buffer.writeUint32(1); // unknown 1
buffer.writeUint32(2); // unknown 2
buffer.writeUint32(StdLib.IPv4.stringToInt(this.publicIP)); // external IP
buffer.writeUint32(0); // filler
buffer.writeUint32(Date.now() - this._connectTime); // timestamp
buffer.writeUint32(++this._connectionCount); // connection count
buffer.writeUint32(ticket.length);
buffer.append(ticket);
buffer = buffer.flip().toBuffer();
try {
// We need to activate our ticket
await this.activateAuthSessionTickets(appid, buffer);
resolve({sessionTicket: buffer});
} catch (err) {
reject(err);
}
}
|
Parse a Steam app or session ticket and return an object containing its details. Static.
@param {Buffer|ByteBuffer} ticket - The binary appticket
@param {boolean} [allowInvalidSignature=false] - Pass true to get back data even if the ticket has no valid signature.
@returns {object|null} - object if well-formed ticket (may not be valid), or null if not well-formed
|
buildToken
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
buildToken = async (err) => {
if (err) {
return reject(err);
}
let gcToken = this._gcTokens.splice(0, 1)[0];
this.emit('debug', `Using GC token ${gcToken.toString('hex')}. We now have ${this._gcTokens.length} tokens left.`);
let buffer = ByteBuffer.allocate(4 + gcToken.length + 4 + 24 + 4 + ticket.length, ByteBuffer.LITTLE_ENDIAN);
buffer.writeUint32(gcToken.length);
buffer.append(gcToken);
buffer.writeUint32(24); // length of the session header, which is always 24 bytes
buffer.writeUint32(1); // unknown 1
buffer.writeUint32(2); // unknown 2
buffer.writeUint32(StdLib.IPv4.stringToInt(this.publicIP)); // external IP
buffer.writeUint32(0); // filler
buffer.writeUint32(Date.now() - this._connectTime); // timestamp
buffer.writeUint32(++this._connectionCount); // connection count
buffer.writeUint32(ticket.length);
buffer.append(ticket);
buffer = buffer.flip().toBuffer();
try {
// We need to activate our ticket
await this.activateAuthSessionTickets(appid, buffer);
resolve({sessionTicket: buffer});
} catch (err) {
reject(err);
}
}
|
Parse a Steam app or session ticket and return an object containing its details. Static.
@param {Buffer|ByteBuffer} ticket - The binary appticket
@param {boolean} [allowInvalidSignature=false] - Pass true to get back data even if the ticket has no valid signature.
@returns {object|null} - object if well-formed ticket (may not be valid), or null if not well-formed
|
buildToken
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
getAppOwnershipTicket(appid, callback) {
return StdLib.Promises.timeoutCallbackPromise(10000, ['appOwnershipTicket'], callback, async (resolve, reject) => {
// See if we have one saved
let filename = `appOwnershipTicket_${this.steamID}_${appid}.bin`;
let file = await this._readFile(filename);
if (file) {
let parsed = AppTicket.parseAppTicket(file);
// Only return the saved ticket if it has a valid signature, expires more than 6 hours from now, and has the same external IP as we have right now.
if (parsed && parsed.isValid && parsed.ownershipTicketExpires - Date.now() >= (1000 * 60 * 60 * 6) && parsed.ownershipTicketExternalIP == this.publicIP) {
return resolve({appOwnershipTicket: file});
}
}
// No saved ticket, we'll have to get a new one
this._send(EMsg.ClientGetAppOwnershipTicket, {app_id: appid}, async (body) => {
let err = Helpers.eresultError(body.eresult);
if (err) {
return reject(err);
}
if (body.app_id != appid) {
return reject(new Error('Cannot get app ownership ticket'));
}
let ticket = body.ticket;
if (ticket && ticket.length > 10 && this.options.saveAppTickets) {
await this._saveFile(filename, ticket);
}
resolve({appOwnershipTicket: ticket});
});
});
}
|
Parse a Steam app or session ticket and return an object containing its details. Static.
@param {Buffer|ByteBuffer} ticket - The binary appticket
@param {boolean} [allowInvalidSignature=false] - Pass true to get back data even if the ticket has no valid signature.
@returns {object|null} - object if well-formed ticket (may not be valid), or null if not well-formed
|
getAppOwnershipTicket
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
activateAuthSessionTickets(appid, tickets, callback) {
if (!Array.isArray(tickets)) {
tickets = [tickets];
}
return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, true, async (resolve, reject) => {
tickets.forEach((ticket, idx) => {
if (ticket instanceof Buffer) {
ticket = AppTicket.parseAppTicket(ticket);
}
if (!ticket || !ticket.isValid || !Buffer.isBuffer(ticket.authTicket)) {
let invalidReason = 'is invalid';
if (ticket.isExpired) {
invalidReason = 'is expired';
}
if (!ticket.hasValidSignature) {
invalidReason = ticket.signature ? 'has an invalid signature' : 'has no signature';
}
return reject(new Error(`Ticket ${idx} ${invalidReason}`));
}
// Make sure this is for the game we expect
if (ticket.appID != appid) {
return reject(new Error(`Ticket ${idx} is for the wrong app: ${ticket.appID}`));
}
let sid = ticket.steamID.getSteamID64();
let isOurTicket = (sid == this.steamID.getSteamID64());
let thisTicket = {
estate: isOurTicket ? 0 : 1,
steamid: isOurTicket ? 0 : sid,
gameid: ticket.appID,
h_steam_pipe: this._hSteamPipe,
ticket_crc: StdLib.Hashing.crc32(ticket.authTicket),
ticket: ticket.authTicket
};
// Check if this ticket is already active
if (this._activeAuthTickets.find(tkt => tkt.steamid == thisTicket.steamid && tkt.ticket_crc == thisTicket.ticket_crc)) {
this.emit('debug', `Not attempting to activate already active ticket ${thisTicket.ticket_crc} for ${appid}/${isOurTicket ? 'self' : sid}`);
return;
}
// If we already have an active ticket for this appid/steamid combo, remove it, but not if it's our own
if (!isOurTicket) {
let existingTicketIdx = this._activeAuthTickets.findIndex(tkt => tkt.steamid == thisTicket.steamid && tkt.gameid == thisTicket.gameid);
if (existingTicketIdx != -1) {
let existingTicket = this._activeAuthTickets[existingTicketIdx];
this.emit('debug', `Canceling existing ticket ${existingTicket.ticket_crc} for ${existingTicket.gameid}/${existingTicket.steamid}`);
this._activeAuthTickets.splice(existingTicketIdx, 1);
}
}
this._activeAuthTickets.push(thisTicket);
});
await this._sendAuthList();
resolve();
});
}
|
Parse a Steam app or session ticket and return an object containing its details. Static.
@param {Buffer|ByteBuffer} ticket - The binary appticket
@param {boolean} [allowInvalidSignature=false] - Pass true to get back data even if the ticket has no valid signature.
@returns {object|null} - object if well-formed ticket (may not be valid), or null if not well-formed
|
activateAuthSessionTickets
|
javascript
|
DoctorMcKay/node-steam-user
|
components/appauth.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/appauth.js
|
MIT
|
gamesPlayed(apps, force) {
if (!(apps instanceof Array)) {
apps = [apps];
}
let execute = async () => {
if (this._playingBlocked && force) {
await this.kickPlayingSession();
}
let processedApps = apps.map((app) => {
if (typeof app == 'string') {
app = {game_id: '15190414816125648896', game_extra_info: app};
} else if (typeof app != 'object') {
app = {game_id: app};
}
if (typeof app.game_ip_address == 'number') {
app.game_ip_address = {v4: app.game_ip_address};
}
return app;
});
this._send(EMsg.ClientGamesPlayedWithDataBlob, {games_played: processedApps});
processedApps.forEach((app) => {
if (app.game_id > Math.pow(2, 32)) {
// It's a non-Steam game.
return;
}
let appid = parseInt(app.game_id, 10);
if (!this._playingAppIds.includes(appid)) {
this.emit('appLaunched', appid);
}
});
this._playingAppIds.forEach((appid) => {
if (!processedApps.some(app => app.game_id == appid)) {
this.emit('appQuit', appid);
}
});
this._playingAppIds = processedApps.filter(app => app.game_id < Math.pow(2, 32)).map(app => parseInt(app.game_id, 10));
};
execute().catch(() => {
});
}
|
Tell Steam that you're "playing" zero or more games.
@param {array} apps - Array of integers (AppIDs) or strings (non-Steam game names) for the games you're playing. Empty to play nothing.
@param {boolean} [force=false] If true, kick any other sessions logged into this account and playing games from Steam
|
gamesPlayed
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
execute = async () => {
if (this._playingBlocked && force) {
await this.kickPlayingSession();
}
let processedApps = apps.map((app) => {
if (typeof app == 'string') {
app = {game_id: '15190414816125648896', game_extra_info: app};
} else if (typeof app != 'object') {
app = {game_id: app};
}
if (typeof app.game_ip_address == 'number') {
app.game_ip_address = {v4: app.game_ip_address};
}
return app;
});
this._send(EMsg.ClientGamesPlayedWithDataBlob, {games_played: processedApps});
processedApps.forEach((app) => {
if (app.game_id > Math.pow(2, 32)) {
// It's a non-Steam game.
return;
}
let appid = parseInt(app.game_id, 10);
if (!this._playingAppIds.includes(appid)) {
this.emit('appLaunched', appid);
}
});
this._playingAppIds.forEach((appid) => {
if (!processedApps.some(app => app.game_id == appid)) {
this.emit('appQuit', appid);
}
});
this._playingAppIds = processedApps.filter(app => app.game_id < Math.pow(2, 32)).map(app => parseInt(app.game_id, 10));
}
|
Tell Steam that you're "playing" zero or more games.
@param {array} apps - Array of integers (AppIDs) or strings (non-Steam game names) for the games you're playing. Empty to play nothing.
@param {boolean} [force=false] If true, kick any other sessions logged into this account and playing games from Steam
|
execute
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
execute = async () => {
if (this._playingBlocked && force) {
await this.kickPlayingSession();
}
let processedApps = apps.map((app) => {
if (typeof app == 'string') {
app = {game_id: '15190414816125648896', game_extra_info: app};
} else if (typeof app != 'object') {
app = {game_id: app};
}
if (typeof app.game_ip_address == 'number') {
app.game_ip_address = {v4: app.game_ip_address};
}
return app;
});
this._send(EMsg.ClientGamesPlayedWithDataBlob, {games_played: processedApps});
processedApps.forEach((app) => {
if (app.game_id > Math.pow(2, 32)) {
// It's a non-Steam game.
return;
}
let appid = parseInt(app.game_id, 10);
if (!this._playingAppIds.includes(appid)) {
this.emit('appLaunched', appid);
}
});
this._playingAppIds.forEach((appid) => {
if (!processedApps.some(app => app.game_id == appid)) {
this.emit('appQuit', appid);
}
});
this._playingAppIds = processedApps.filter(app => app.game_id < Math.pow(2, 32)).map(app => parseInt(app.game_id, 10));
}
|
Tell Steam that you're "playing" zero or more games.
@param {array} apps - Array of integers (AppIDs) or strings (non-Steam game names) for the games you're playing. Empty to play nothing.
@param {boolean} [force=false] If true, kick any other sessions logged into this account and playing games from Steam
|
execute
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
kickPlayingSession(callback) {
return StdLib.Promises.callbackPromise([], callback, true, (resolve, reject) => {
this._send(EMsg.ClientKickPlayingSession, {});
Helpers.onceTimeout(10000, this, 'playingState', (err, blocked, playingApp) => {
if (err) {
return reject(err);
} else if (blocked) {
return reject(new Error('Cannot kick other session'));
} else {
return resolve({playingApp});
}
});
});
}
|
Kick any other session logged into your account which is playing a game from Steam.
@param {function} [callback]
@returns {Promise<{playingApp: number}>}
|
kickPlayingSession
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
getPlayerCount(appid, callback) {
return StdLib.Promises.timeoutCallbackPromise(10000, ['playerCount'], callback, (resolve, reject) => {
this._send(EMsg.ClientGetNumberOfCurrentPlayersDP, {appid}, (body) => {
let err = Helpers.eresultError(body.eresult);
if (err) {
reject(err);
} else {
resolve({playerCount: body.player_count});
}
});
});
}
|
Get count of people playing a Steam app. Use appid 0 to get number of people connected to Steam.
@param {int} appid
@param {function} [callback]
@returns {Promise<{playerCount: number}>}
|
getPlayerCount
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
getProductChanges(sinceChangenumber, callback) {
let args = ['currentChangeNumber', 'appChanges', 'packageChanges'];
return StdLib.Promises.timeoutCallbackPromise(10000, args, callback, (resolve, reject) => {
this._send(EMsg.ClientPICSChangesSinceRequest, {
since_change_number: sinceChangenumber,
send_app_info_changes: true,
send_package_info_changes: true
}, (body) => {
resolve({
currentChangeNumber: body.current_change_number,
appChanges: body.app_changes,
packageChanges: body.package_changes
});
});
});
}
|
Get a list of apps or packages which have changed since a particular changenumber.
@param {int} sinceChangenumber - Changenumber to get changes since. Use 0 to get the latest changenumber, but nothing else
@param {function} [callback]
@returns {Promise<{currentChangeNumber: number, appChanges: number[], packageChanges: number[]}>}
|
getProductChanges
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
getProductInfo(apps, packages, inclTokens, callback, requestType) {
// Adds support for the previous syntax
if (typeof inclTokens !== 'boolean' && typeof inclTokens === 'function') {
requestType = callback;
callback = inclTokens;
inclTokens = false;
}
// This one actually can take a while, so allow it to go as long as 60 minutes
return StdLib.Promises.timeoutCallbackPromise(3600000, ['apps', 'packages', 'unknownApps', 'unknownPackages'], callback, (resolve, reject) => {
requestType = requestType || PICSRequestType.User;
// Steam can send us the full response in multiple responses, so we need to buffer them into one callback
let appids = [];
let packageids = [];
let response = {
apps: {},
packages: {},
unknownApps: [],
unknownPackages: []
};
apps = apps.map((app) => {
if (typeof app === 'object') {
appids.push(app.appid);
return app;
} else {
appids.push(app);
return {appid: app};
}
});
packages = packages.map((pkg) => {
if (typeof pkg === 'object') {
packageids.push(pkg.packageid);
return pkg;
} else {
packageids.push(pkg);
return {packageid: pkg};
}
});
if (inclTokens) {
packages.filter(pkg => !pkg.access_token).forEach((pkg) => {
// Check if we have a license for this package which includes a token
let license = (this.licenses || []).find(lic => lic.package_id == pkg.packageid && lic.access_token != 0);
if (license) {
this.emit('debug', `Using token "${license.access_token}" from license for package ${pkg.packageid}`);
pkg.access_token = license.access_token;
}
});
}
this._send(EMsg.ClientPICSProductInfoRequest, {apps, packages}, async (body) => {
// If we're using the PICS cache, then add the items in this response to it
if (this.options.enablePicsCache) {
let cache = this.picsCache;
cache.apps = cache.apps || {};
cache.packages = cache.packages || {};
(body.apps || []).forEach((app) => {
let appInfoVdf = app.buffer.toString('utf8');
// It seems that Steam appends a NUL byte. Unsure if this is universal or not, but to make sure
// that things work regardless of whether there's a NUL byte at the end, just remove it if it's there.
appInfoVdf = appInfoVdf.replace(/\0$/, '');
let data = {
changenumber: app.change_number,
missingToken: !!app.missing_token,
appinfo: VDF.parse(appInfoVdf).appinfo
};
if ((!cache.apps[app.appid] && requestType == PICSRequestType.Changelist) || (cache.apps[app.appid] && cache.apps[app.appid].changenumber != data.changenumber)) {
// Only emit the event if we previously didn't have the appinfo, or if the changenumber changed
this.emit('appUpdate', app.appid, data);
}
cache.apps[app.appid] = data;
app._parsedData = data;
});
(body.packages || []).forEach((pkg) => {
let data = {
changenumber: pkg.change_number,
missingToken: !!pkg.missing_token,
packageinfo: pkg.buffer ? BinaryKVParser.parse(pkg.buffer)[pkg.packageid] : null
};
if ((!cache.packages[pkg.packageid] && requestType == PICSRequestType.Changelist) || (cache.packages[pkg.packageid] && cache.packages[pkg.packageid].changenumber != data.changenumber)) {
this.emit('packageUpdate', pkg.packageid, data);
}
cache.packages[pkg.packageid] = data;
pkg._parsedData = data;
// Request info for all the apps in this package, if this request didn't originate from the license list
if (requestType != PICSRequestType.Licenses) {
let appids = (pkg.packageinfo || {}).appids || [];
this.getProductInfo(appids, [], false, null, PICSRequestType.PackageContents).catch(() => {});
}
});
}
(body.unknown_appids || []).forEach((appid) => {
response.unknownApps.push(appid);
let index = appids.indexOf(appid);
if (index != -1) {
appids.splice(index, 1);
}
});
(body.unknown_packageids || []).forEach((packageid) => {
response.unknownPackages.push(packageid);
let index = packageids.indexOf(packageid);
if (index != -1) {
packageids.splice(index, 1);
}
});
(body.apps || []).forEach((app) => {
// _parsedData will be populated if we have the PICS cache enabled.
// If we don't, we need to parse the data here.
let appInfoVdf = app.buffer.toString('utf8');
// It seems that Steam appends a NUL byte. Unsure if this is universal or not, but to make sure
// that things work regardless of whether there's a NUL byte at the end, just remove it if it's there.
appInfoVdf = appInfoVdf.replace(/\0$/, '');
response.apps[app.appid] = app._parsedData || {
changenumber: app.change_number,
missingToken: !!app.missing_token,
appinfo: VDF.parse(appInfoVdf).appinfo
};
let index = appids.indexOf(app.appid);
if (index != -1) {
appids.splice(index, 1);
}
});
(body.packages || []).forEach((pkg) => {
response.packages[pkg.packageid] = pkg._parsedData || {
changenumber: pkg.change_number,
missingToken: !!pkg.missing_token,
packageinfo: pkg.buffer ? BinaryKVParser.parse(pkg.buffer)[pkg.packageid] : null
};
let index = packageids.indexOf(pkg.packageid);
if (index != -1) {
packageids.splice(index, 1);
}
});
// appids and packageids contain the list of IDs that we're still waiting on data for
if (appids.length === 0 && packageids.length === 0) {
if (!inclTokens) {
return resolve(response);
}
// We want tokens
let tokenlessAppids = [];
let tokenlessPackages = [];
for (let appid in response.apps) {
if (response.apps[appid].missingToken) {
tokenlessAppids.push(parseInt(appid, 10));
}
}
for (let packageid in response.packages) {
if (response.packages[packageid].missingToken) {
tokenlessPackages.push(parseInt(packageid, 10));
}
}
if (tokenlessAppids.length == 0 && tokenlessPackages.length == 0) {
// No tokens needed
return resolve(response);
}
try {
let {
appTokens,
packageTokens
} = await this.getProductAccessToken(tokenlessAppids, tokenlessPackages);
let tokenApps = [];
let tokenPackages = [];
for (let appid in appTokens) {
tokenApps.push({appid: parseInt(appid, 10), access_token: appTokens[appid]});
}
for (let packageid in packageTokens) {
tokenPackages.push({
packageid: parseInt(packageid, 10),
access_token: packageTokens[packageid]
});
}
// Now we have the tokens. Request the data.
let {apps, packages} = await this.getProductInfo(tokenApps, tokenPackages, false);
for (let appid in apps) {
response.apps[appid] = apps[appid];
let index = response.unknownApps.indexOf(parseInt(appid, 10));
if (index != -1) {
response.unknownApps.splice(index, 1);
}
}
for (let packageid in packages) {
response.packages[packageid] = packages[packageid];
let index = response.unknownPackages.indexOf(parseInt(packageid, 10));
if (index != -1) {
response.unknownPackages.splice(index, 1);
}
}
resolve(response);
} catch (ex) {
return reject(ex);
}
}
});
});
}
|
Get info about some apps and/or packages from Steam.
@param {int[]|object[]} apps - Array of AppIDs. May be empty. May also contain objects with keys {appid, access_token}
@param {int[]|object[]} packages - Array of package IDs. May be empty. May also contain objects with keys {packageid, access_token}
@param {boolean} [inclTokens=false] - If true, automatically retrieve access tokens if needed
@param {function} [callback]
@param {int} [requestType] - Don't touch
@returns {Promise<{apps: Object<string, {changenumber: number, missingToken: boolean, appinfo: object}>, packages: Object<string, {changenumber: number, missingToken: boolean, packageinfo: object}>, unknownApps: number[], unknownPackages: number[]}>}
|
getProductInfo
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
getProductAccessToken(apps, packages, callback) {
let args = ['appTokens', 'packageTokens', 'appDeniedTokens', 'packageDeniedTokens'];
return StdLib.Promises.timeoutCallbackPromise(10000, args, callback, (resolve, reject) => {
this._send(EMsg.ClientPICSAccessTokenRequest, {
packageids: packages,
appids: apps
}, (body) => {
let appTokens = {};
let packageTokens = {};
(body.app_access_tokens || []).forEach((app) => {
appTokens[app.appid] = app.access_token;
});
(body.package_access_tokens || []).forEach((pkg) => {
packageTokens[pkg.packageid] = pkg.access_token;
});
resolve({
appTokens,
packageTokens,
appDeniedTokens: body.app_denied_tokens || [],
packageDeniedTokens: body.package_denied_tokens || []
});
});
});
}
|
Get access tokens for some apps and/or packages
@param {int[]} apps - Array of appids
@param {int[]} packages - Array of packageids
@param {function} [callback] - First arg is an object of (appid => access token), second is the same for packages, third is array of appids for which tokens are denied, fourth is the same for packages
@returns {Promise<{appTokens: Object<string, string>, packageTokens: Object<string, string>, appDeniedTokens: number[], packageDeniedTokens: number[]}>}
|
getProductAccessToken
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
redeemKey(key, callback) {
return StdLib.Promises.timeoutCallbackPromise(90000, ['purchaseResultDetails', 'packageList'], callback, (resolve, reject) => {
this._send(EMsg.ClientRegisterKey, {key: key}, (body) => {
let packageList = {};
let receiptDetails = BinaryKVParser.parse(body.purchase_receipt_info).MessageObject;
if (receiptDetails.LineItemCount > 0) {
receiptDetails.lineitems.forEach((pkg) => {
let packageID = pkg.PackageID || pkg.packageID || pkg.packageid;
packageList[packageID] = pkg.ItemDescription;
});
}
let err = Helpers.eresultError(body.eresult);
if (err) {
err.purchaseResultDetails = body.purchase_result_details;
err.packageList = packageList;
reject(err);
} else {
resolve({
purchaseResultDetails: body.purchase_result_details,
packageList
});
}
});
});
}
|
Redeem a product code on this account.
@param {string} key
@param {function} [callback] - Args (eresult value, SteamUser.EPurchaseResult value, object of (packageid => package names)
@returns {Promise<{purchaseResultDetails: EPurchaseResult, packageList: Object<string, string>}>}
|
redeemKey
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
getLegacyGameKey(appid, callback) {
return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, (resolve, reject) => {
let request = Buffer.alloc(4);
request.writeUInt32LE(appid);
this._send(EMsg.ClientGetLegacyGameKey, request, (body) => {
let responseAppId = body.readUint32();
if (responseAppId != appid) {
// Is this even possible?
return reject(new Error(`Received response for wrong appid ${responseAppId}`));
}
let eresult = body.readUint32();
let err = Helpers.eresultError(eresult);
if (err) {
return reject(err);
}
let keyLength = body.readUint32();
if (keyLength == 0) {
// Unsure if this is possible
return reject(new Error('No key returned'));
}
let key = body.readCString();
if (key.length != keyLength - 1) {
// keyLength includes the null terminator
return reject(new Error(`Incorrect key length: expected ${keyLength - 1} but got ${key.length}`));
}
return resolve({key});
});
});
}
|
Gets your legacy CD key for a game in your library which uses CD keys
@param {number} appid
@param {function} [callback]
@returns {Promise<{key: string}>}
|
getLegacyGameKey
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
function sortNumeric(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
}
|
Gets your legacy CD key for a game in your library which uses CD keys
@param {number} appid
@param {function} [callback]
@returns {Promise<{key: string}>}
|
sortNumeric
|
javascript
|
DoctorMcKay/node-steam-user
|
components/apps.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/apps.js
|
MIT
|
getContentServers(appid, callback) {
if (typeof appid == 'function') {
callback = appid;
appid = null;
}
return StdLib.Promises.timeoutCallbackPromise(10000, ['servers'], callback, async (resolve, reject) => {
let res;
if (this._contentServerCache && this._contentServerCache.timestamp && Date.now() - this._contentServerCache.timestamp < (1000 * 60 * 60)) {
// Cache for 1 hour
res = this._contentServerCache.response;
} else {
res = await this._apiRequest('GET', 'IContentServerDirectoryService', 'GetServersForSteamPipe', 1, {cell_id: this.cellID || 0});
}
if (!res || !res.response || !res.response.servers) {
return reject(new Error('Malformed response'));
}
this._contentServerCache = {
timestamp: Date.now(),
response: res
};
let servers = [];
for (let serverKey in res.response.servers) {
let server = res.response.servers[serverKey];
if (server.allowed_app_ids && appid && !server.allowed_app_ids.includes(appid)) {
continue;
}
if (server.type == 'CDN' || server.type == 'SteamCache') {
servers.push(server);
}
}
if (servers.length == 0) {
return reject(new Error('No content servers available'));
}
servers = servers.map((srv) => {
let processedSrv = {
type: srv.type,
sourceid: srv.source_id,
cell: srv.cell_id,
load: srv.load,
preferred_server: srv.preferred_server,
weightedload: srv.weighted_load,
NumEntriesInClientList: srv.num_entries_in_client_list,
Host: srv.host,
vhost: srv.vhost,
https_support: srv.https_support,
//usetokenauth: '1'
};
if (srv.allowed_app_ids) {
processedSrv.allowed_app_ids = srv.allowed_app_ids;
}
return processedSrv;
});
if (servers.length == 0) {
delete this._contentServerCache;
return reject(new Error('No servers found'));
}
// Return a copy of the array, not the original
return resolve({servers: JSON.parse(JSON.stringify(servers))});
});
}
|
Get the list of currently-available content servers.
@param {int} [appid] - If you know the appid you want to download, pass it here as some content servers only provide content for specific games
@param {function} [callback]
@return Promise
|
getContentServers
|
javascript
|
DoctorMcKay/node-steam-user
|
components/cdn.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/cdn.js
|
MIT
|
getDepotDecryptionKey(appID, depotID, callback) {
appID = parseInt(appID, 10);
depotID = parseInt(depotID, 10);
return StdLib.Promises.timeoutCallbackPromise(10000, ['key'], callback, async (resolve, reject) => {
// Check if it's cached locally
let filename = `depot_key_${appID}_${depotID}.bin`;
let file = await this._readFile(filename);
if (file && file.length > 4 && Math.floor(Date.now() / 1000) - file.readUInt32LE(0) < (60 * 60 * 24 * 14)) {
return resolve({key: file.slice(4)});
}
this._send(EMsg.ClientGetDepotDecryptionKey, {
depot_id: depotID,
app_id: appID
}, async (body) => {
if (body.eresult != EResult.OK) {
return reject(Helpers.eresultError(body.eresult));
}
if (body.depot_id != depotID) {
return reject(new Error('Did not receive decryption key for correct depot'));
}
let key = body.depot_encryption_key;
file = Buffer.concat([Buffer.alloc(4), key]);
file.writeUInt32LE(Math.floor(Date.now() / 1000), 0);
await this._saveFile(filename, file);
return resolve({key});
});
});
}
|
Request the decryption key for a particular depot.
@param {int} appID
@param {int} depotID
@param {function} [callback]
@return Promise
|
getDepotDecryptionKey
|
javascript
|
DoctorMcKay/node-steam-user
|
components/cdn.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/cdn.js
|
MIT
|
getCDNAuthToken(appID, depotID, hostname, callback) {
return StdLib.Promises.timeoutCallbackPromise(10000, ['token', 'expires'], callback, (resolve, reject) => {
if (this._contentServerTokens[depotID + '_' + hostname] && this._contentServerTokens[depotID + '_' + hostname].expires - Date.now() > (1000 * 60 * 60)) {
return resolve(this._contentServerTokens[depotID + '_' + hostname]);
}
this._send(EMsg.ClientGetCDNAuthToken, {
app_id: appID,
depot_id: depotID,
host_name: hostname
}, (body) => {
if (body.eresult != EResult.OK) {
return reject(Helpers.eresultError(body.eresult));
}
return resolve(this._contentServerTokens[depotID + '_' + hostname] = {
token: body.token,
expires: new Date(body.expiration_time * 1000)
});
});
});
}
|
Get an auth token for a particular CDN server.
@param {int} appID
@param {int} depotID
@param {string} hostname - The hostname of the CDN server for which we want a token
@param {function} [callback]
@return Promise
|
getCDNAuthToken
|
javascript
|
DoctorMcKay/node-steam-user
|
components/cdn.js
|
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/cdn.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.