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
deleteFriendsGroup(groupID, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, true, (resolve, reject) => { this._send(EMsg.AMClientDeleteFriendsGroup, { groupid: groupID }, (body) => { if (body.eresult != EResult.OK) { return reject(Helpers.eresultError(body.eresult)); } delete this.myFriendGroups[groupID]; return resolve(); }); }); }
Deletes a friends group (or tag) @param {int} groupID - The friends group id @param {function} [callback] @return {Promise}
deleteFriendsGroup
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
renameFriendsGroup(groupID, newName, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, true, (resolve, reject) => { this._send(EMsg.AMClientRenameFriendsGroup, { groupid: groupID, groupname: newName }, (body) => { if (body.eresult != EResult.OK) { return reject(Helpers.eresultError(body.eresult)); } this.myFriendGroups[groupID].name = newName; return resolve(); }); }); }
Rename a friends group (tag) @param {int} groupID - The friends group id @param {string} newName - The new name to update the friends group with @param {function} [callback] @return {Promise}
renameFriendsGroup
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
addFriendToGroup(groupID, userSteamID, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, true, (resolve, reject) => { let sid = Helpers.steamID(userSteamID); this._send(EMsg.AMClientAddFriendToGroup, { groupid: groupID, steamiduser: sid.getSteamID64() }, (body) => { if (body.eresult != EResult.OK) { return reject(Helpers.eresultError(body.eresult)); } this.myFriendGroups[groupID].members.push(sid); return resolve(); }); }); }
Add an user to friends group (tag) @param {int} groupID - The friends group @param {(SteamID|string)} userSteamID - The user to invite to the friends group with, as a SteamID object or a string which can parse into one @param {function} [callback] @return {Promise}
addFriendToGroup
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
removeFriendFromGroup(groupID, userSteamID, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, true, (resolve, reject) => { let sid = Helpers.steamID(userSteamID); this._send(EMsg.AMClientRemoveFriendFromGroup, { groupid: groupID, steamiduser: sid.getSteamID64() }, (body) => { if (body.eresult != EResult.OK) { return reject(Helpers.eresultError(body.eresult)); } let index = this.myFriendGroups[groupID].members.findIndex((element) => { return element.getSteamID64() === sid.getSteamID64(); }); if (index > -1) { this.myFriendGroups[groupID].members.splice(index, 1); } return resolve(); }); }); }
Remove an user to friends group (tag) @param {int} groupID - The friends group @param {(SteamID|string)} userSteamID - The user to remove from the friends group with, as a SteamID object or a string which can parse into one @param {function} [callback] @return {Promise}
removeFriendFromGroup
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
getAliases(userSteamIDs, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, ['users'], callback, (resolve, reject) => { if (!(userSteamIDs instanceof Array)) { userSteamIDs = [userSteamIDs]; } userSteamIDs = userSteamIDs.map(Helpers.steamID).map((id) => { return {steamid: id.getSteamID64()}; }); this._send(EMsg.ClientAMGetPersonaNameHistory, { id_count: userSteamIDs.length, Ids: userSteamIDs }, (body) => { let ids = {}; body.responses = body.responses || []; for (let i = 0; i < body.responses.length; i++) { if (body.responses[i].eresult != EResult.OK) { return reject(Helpers.eresultError(body.responses[i].eresult)); } ids[body.responses[i].steamid.toString()] = (body.responses[i].names || []).map((name) => { name.name_since = new Date(name.name_since * 1000); return name; }); } return resolve({users: ids}); }); }); }
Get persona name history for one or more users. @param {SteamID[]|string[]|SteamID|string} userSteamIDs - SteamIDs of users to request aliases for @param {function} [callback] @return {Promise}
getAliases
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
setNickname(steamID, nickname, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, true, (resolve, reject) => { steamID = Helpers.steamID(steamID); this._send(EMsg.AMClientSetPlayerNickname, { steamid: steamID.toString(), nickname }, (body) => { if (body.eresult != EResult.OK) { return reject(Helpers.eresultError(body.eresult)); } // Worked! if (nickname.length == 0) { delete this.myNicknames[steamID.toString()]; } else { this.myNicknames[steamID.toString()] = nickname; } return resolve(); }); }); }
Set a friend's private nickname. @param {(SteamID|string)} steamID @param {string} nickname @param {function} [callback] @return {Promise}
setNickname
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
getNicknames(callback) { return StdLib.Promises.timeoutCallbackPromise(10000, ['nicknames'], callback, true, (resolve, reject) => { this._sendUnified('Player.GetNicknameList#1', {}, (body) => { let nicks = {}; body.nicknames.forEach(player => nicks[SteamID.fromIndividualAccountID(player.accountid).getSteamID64()] = player.nickname); resolve({nicknames: nicks}); this.emit('nicknameList', nicks); this.myNicknames = nicks; }); }); }
Get the list of nicknames you've given to other users. @param {function} [callback] @return {Promise}
getNicknames
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
getAppRichPresenceLocalization(appID, language, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, (resolve, reject) => { let cacheKey = `${appID}_${language}`; let cache = this._richPresenceLocalization[cacheKey]; if (cache && Date.now() - cache.timestamp < (1000 * 60 * 60)) { // Cache for 1 hour return resolve({tokens: cache.tokens}); } if (typeof language == 'function') { callback = language; language = null; } language = language || this.options.language || 'english'; this._sendUnified('Community.GetAppRichPresenceLocalization#1', { appid: appID, language }, (body) => { if (body.appid != appID) { return reject(new Error('Did not get localizations for requested app ' + appID + ' (' + body.appID + ')')); } let tokens = {}; let foundLanguage = false; body.token_lists.forEach((list) => { if (list.language == language) { foundLanguage = true; list.tokens.forEach((token) => { tokens[token.name] = token.value; }); } }); if (!foundLanguage) { return reject(new Error('Did not get localizations for requested language ' + language)); } if (Object.keys(tokens).length > 0) { this._richPresenceLocalization[cacheKey] = { timestamp: Date.now(), tokens }; } return resolve({tokens}); }); }); }
Get the localization keys for rich presence for an app on Steam. @param {int} appID - The app you want rich presence localizations for @param {string} [language] - The full name of the language you want localizations for (e.g. "english" or "spanish"); defaults to language passed to constructor @param {function} [callback] @returns {Promise}
getAppRichPresenceLocalization
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
uploadRichPresence(appid, richPresence) { // Maybe someday in the future we'll have a proper binary KV encoder. For now, just do it by hand. let buf = new ByteBuffer(1024, ByteBuffer.LITTLE_ENDIAN); buf.writeByte(0); buf.writeCString('RP'); for (let i in richPresence) { if (!Object.hasOwnProperty.call(richPresence, i)) { continue; } buf.writeByte(1); // type string buf.writeCString(i); buf.writeCString(richPresence[i]); } buf.writeByte(8); // end buf.writeByte(8); // end again this._send({ // Header msg: EMsg.ClientRichPresenceUpload, proto: {routing_appid: appid} }, { // Request rich_presence_kv: buf.flip().toBuffer() }); }
Upload some rich presence data to Steam. @param {int} appid @param {{steam_display?, connect?}} richPresence
uploadRichPresence
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
requestRichPresence(appid, steamIDs, language, callback) { if (!Array.isArray(steamIDs)) { steamIDs = [steamIDs]; } if (typeof language == 'function') { callback = language; language = null; } return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, (resolve, reject) => { this._send({ // Header msg: EMsg.ClientRichPresenceRequest, proto: {routing_appid: appid}, }, { // Request steamid_request: steamIDs.map(sid => Helpers.steamID(sid).getSteamID64()) }, async (body) => { // Response let response = {}; body.rich_presence = body.rich_presence || []; for (let rp of body.rich_presence) { let kv = rp.rich_presence_kv; if (!kv || !rp.steamid_user) { continue; } try { let kvObj = BinaryKVParser.parse(kv); // This will throw in the event of there being no RP data (e.g. user not in game) if (kvObj && kvObj.RP) { response[rp.steamid_user] = { richPresence: kvObj.RP, localizedString: null, }; // Do this separately as it will reject if it cannot localize response[rp.steamid_user].localizedString = await this._getRPLocalizedString(appid, kvObj.RP, language); } } catch (e) { // don't care, there's nothing here } } resolve({users: response}); }); }); }
Request rich presence data of one or more users for an appid. @param {int} appid - The appid to get rich presence data for @param {SteamID[]|string[]|SteamID|string} steamIDs - SteamIDs of users to request rich presence data for @param {string} [language] - Language to get localized strings in. Defaults to language passed to constructor. @param {function} [callback] - Called or resolved with 'users' property with each key being a SteamID and value being the rich presence response if received @return Promise
requestRichPresence
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
getUserOwnedApps(steamID, options, callback) { if (typeof options == 'function') { callback = options; options = {}; } options = options || {}; return new StdLib.Promises.timeoutCallbackPromise(10000, null, callback, false, (resolve, reject) => { steamID = Helpers.steamID(steamID); this._sendUnified('Player.GetOwnedGames#1', { steamid: steamID.toString(), include_appinfo: options.includeAppInfo ?? true, include_played_free_games: options.includePlayedFreeGames || false, appids_filter: options.filterAppids || undefined, include_free_sub: options.includeFreeSub || false, skip_unvetted_apps: options.skipUnvettedApps ?? true }, (body, hdr) => { let err = Helpers.eresultError(hdr.proto); if (err) { return reject(err); } let response = { app_count: body.game_count, apps: body.games.map((app) => { if (app.img_icon_url) { app.img_icon_url = `https://steamcdn-a.akamaihd.net/steamcommunity/public/images/apps/${app.appid}/${app.img_icon_url}.jpg`; } if (app.img_logo_url) { app.img_logo_url = `https://steamcdn-a.akamaihd.net/steamcommunity/public/images/apps/${app.appid}/${app.img_logo_url}.jpg`; } return app; }) }; resolve(response); }); }); }
Get the list of a user's owned apps. @param {SteamID|string} steamID - Either a SteamID object or a string that can parse into one @param {{includePlayedFreeGames?: boolean, filterAppids?: number[], includeFreeSub?: boolean, includeAppInfo?: boolean, skipUnvettedApps?: boolean}} [options] @param {function} [callback] @returns {Promise}
getUserOwnedApps
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
getFriendsThatPlay(appID, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, null, callback, (resolve, reject) => { let buf = ByteBuffer.allocate(8, ByteBuffer.LITTLE_ENDIAN); buf.writeUint64(appID); this._send(EMsg.ClientGetFriendsWhoPlayGame, buf.flip(), (body) => { let eresult = body.readUint32(); let err = Helpers.eresultError(eresult); if (err) { return reject(err); } let steamIds = []; let responseAppid = body.readUint64().toString(); let countFriends = body.readUint32().toString(); if (responseAppid != appID) { return reject(new Error('AppID in response does not match request')); } for (let i = 0; i < countFriends; i++) { steamIds.push(new SteamID(body.readUint64().toString())); } return resolve({friends: steamIds}); }); }); }
Get a list of friends that play a specific app. @param {int} appID @param {function} [callback] @returns {Promise}
getFriendsThatPlay
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
_getRPLocalizedString(appid, tokens, language) { return new Promise(async (resolve, reject) => { if (!tokens.steam_display) { // Nothing to do here return reject(); } let localizationTokens; try { localizationTokens = (await this.getAppRichPresenceLocalization(appid, language || this.options.language)).tokens; // Normalize all localization tokens to lowercase for (let i in localizationTokens) { localizationTokens[i.toLowerCase()] = localizationTokens[i]; } } catch (ex) { // Oh well return reject(ex); } let rpTokens = JSON.parse(JSON.stringify(tokens)); // So we don't modify the original objects for (let i in rpTokens) { if (Object.hasOwnProperty.call(rpTokens, i) && localizationTokens[rpTokens[i].toLowerCase()]) { rpTokens[i] = localizationTokens[rpTokens[i].toLowerCase()]; } } let rpString = rpTokens.steam_display; // eslint-disable-next-line while (true) { let newRpString = rpString; for (let i in rpTokens) { if (Object.hasOwnProperty.call(rpTokens, i)) { newRpString = newRpString.replace(new RegExp('%' + i + '%', 'gi'), rpTokens[i]); } } (newRpString.match(/{#[^}]+}/g) || []).forEach((token) => { token = token.substring(1, token.length - 1); if (localizationTokens[token.toLowerCase()]) { newRpString = newRpString.replace(new RegExp('{' + token + '}', 'gi'), localizationTokens[token.toLowerCase()]); } }); if (newRpString == rpString) { break; } else { rpString = newRpString; } } return resolve(rpString); }); }
@param {number} appid @param {object} tokens @param {string} [language] @returns {Promise} @protected
_getRPLocalizedString
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
_processUserPersona(user) { return new Promise((resolve) => { g_ProcessPersonaSemaphore.wait(async (release) => { try { if (typeof user.last_logoff === 'number') { user.last_logoff = new Date(user.last_logoff * 1000); } if (typeof user.last_logon === 'number') { user.last_logon = new Date(user.last_logon * 1000); } if (typeof user.last_seen_online === 'number') { user.last_seen_online = new Date(user.last_seen_online * 1000); } if (typeof user.avatar_hash === 'object' && (Buffer.isBuffer(user.avatar_hash) || ByteBuffer.isByteBuffer(user.avatar_hash))) { let hash = user.avatar_hash.toString('hex'); // handle default avatar if (hash === '0000000000000000000000000000000000000000') { hash = 'fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb'; } user.avatar_url_icon = `https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/${hash.substring(0, 2)}/${hash}`; user.avatar_url_medium = `${user.avatar_url_icon}_medium.jpg`; user.avatar_url_full = `${user.avatar_url_icon}_full.jpg`; user.avatar_url_icon += '.jpg'; } // only delete rich_presence_string if we have confirmation that the user isn't in-game if ((user.rich_presence && user.rich_presence.length == 0) || user.gameid === '0') { delete user.rich_presence_string; return resolve(user); } if (!user.rich_presence) { // if we don't have rich_presence data right now, there's nothing to parse return resolve(user); } let rpTokens = {}; user.rich_presence.forEach((token) => { rpTokens[token.key] = token.value; }); if (!rpTokens.steam_display) { // Nothing to do here return resolve(user); } try { user.rich_presence_string = await this._getRPLocalizedString(user.gameid, rpTokens); } catch (ex) { delete user.rich_presence_string; } return resolve(user); } finally { // always release the lock release(); } }); }); }
@param {object} user @returns {Promise<UserPersona>} @protected
_processUserPersona
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
function processInviteToken(userSteamId, token) { let friendCode = Helpers.createFriendCode(userSteamId); token.invite_link = `https://s.team/p/${friendCode}/${token.invite_token}`; token.time_created = token.time_created ? new Date(token.time_created * 1000) : null; token.invite_limit = token.invite_limit ? parseInt(token.invite_limit, 10) : null; token.invite_duration = token.invite_duration ? parseInt(token.invite_duration, 10) : null; }
@param {object} user @returns {Promise<UserPersona>} @protected
processInviteToken
javascript
DoctorMcKay/node-steam-user
components/friends.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/friends.js
MIT
sendToGC(appid, msgType, protoBufHeader, payload, callback) { let sourceJobId = JOBID_NONE; if (typeof callback === 'function') { sourceJobId = ++this._currentGCJobID; this._jobsGC.add(sourceJobId.toString(), callback); } this.emit('debug', `Sending ${appid} GC message ${msgType}`); let header; if (protoBufHeader) { msgType = (msgType | PROTO_MASK) >>> 0; protoBufHeader.jobid_source = sourceJobId; let protoHeader = SteamUserGameCoordinator._encodeProto(Schema.CMsgProtoBufHeader, protoBufHeader); header = Buffer.alloc(8); header.writeUInt32LE(msgType, 0); header.writeInt32LE(protoHeader.length, 4); header = Buffer.concat([header, protoHeader]); } else { header = ByteBuffer.allocate(18, ByteBuffer.LITTLE_ENDIAN); header.writeUint16(1); // header version header.writeUint64(JOBID_NONE); header.writeUint64(sourceJobId); header = header.flip().toBuffer(); } this._send({ msg: EMsg.ClientToGC, proto: { routing_appid: appid } }, { appid, msgtype: msgType, payload: Buffer.concat([header, payload]) }); }
Send a message to a GC. You should be currently "in-game" for the specified app for the message to make it. @param {int} appid - The ID of the app you want to send a GC message to @param {int} msgType - The GC-specific msg ID for this message @param {object|null} protoBufHeader - An object (can be empty) containing the protobuf header for this message, or null if this is not a protobuf message. @param {Buffer|ByteBuffer} payload @param {function} [callback] - If this is a job-based message, pass a function here to get the response
sendToGC
javascript
DoctorMcKay/node-steam-user
components/gamecoordinator.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/gamecoordinator.js
MIT
serverQuery(conditions, callback) { if (typeof conditions === 'string') { conditions = {filter_text: conditions}; } if (conditions.geo_location_ip) { conditions.geo_location_ip = StdLib.IPv4.stringToInt(conditions.geo_location_ip); } return StdLib.Promises.timeoutCallbackPromise(30000, ['servers'], callback, (resolve, reject) => { this._send(EMsg.ClientGMSServerQuery, conditions, function(body) { if (body.error) { reject(new Error(body.error)); return; } // TODO add ipv6 support someday resolve({ servers: (body.servers || []).filter(server => server.server_ip && server.server_ip.v4).map((server) => { return { ip: StdLib.IPv4.intToString(server.server_ip), port: server.server_port, players: server.auth_players }; }) }); }); }); }
Query the GMS for a list of game server IPs, and their current player counts. @param {(string|{[filter_text], [geo_location_ip]})} conditions - A filter string (https://mckay.media/hEW8A) or object @param {function} [callback] @return {Promise}
serverQuery
javascript
DoctorMcKay/node-steam-user
components/gameservers.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/gameservers.js
MIT
getServerSteamIDsByIP(ips, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, ['servers'], callback, (resolve, reject) => { this._sendUnified('GameServers.GetServerSteamIDsByIP#1', { server_ips: ips }, (body) => { let servers = {}; (body.servers || []).forEach((server) => { servers[server.addr] = new SteamID(server.steamid.toString()); }); resolve({servers}); }); }); }
Get the associated SteamIDs for given server IPs. @param {string[]} ips @param {function} [callback]
getServerSteamIDsByIP
javascript
DoctorMcKay/node-steam-user
components/gameservers.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/gameservers.js
MIT
getServerIPsBySteamID(steamids, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, ['servers'], callback, (resolve, reject) => { steamids = steamids.map(Helpers.steamID); this._sendUnified('GameServers.GetServerIPsBySteamID#1', { server_steamids: steamids }, (body) => { let servers = {}; (body.servers || []).forEach((server) => { servers[server.steamid.toString()] = server.addr; }); resolve({servers}); }); }); }
Get the associated IPs for given server SteamIDs. @param {string[]|SteamID[]} steamids @param {function} [callback] @return {Promise}
getServerIPsBySteamID
javascript
DoctorMcKay/node-steam-user
components/gameservers.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/gameservers.js
MIT
markNotificationsRead(notificationIds) { this._sendUnified('SteamNotification.MarkNotificationsRead#1', { notification_ids: notificationIds }); }
Mark some notifications as read by ID @param {(string|number)[]} notificationIds - IDs of notifications to mark as read
markNotificationsRead
javascript
DoctorMcKay/node-steam-user
components/notifications.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/notifications.js
MIT
getPublishedFileDetails(ids, callback) { if (!(ids instanceof Array)) { ids = [ids]; } return StdLib.Promises.timeoutCallbackPromise(10000, ['files'], callback, (resolve, reject) => { this._sendUnified('PublishedFile.GetDetails#1', { publishedfileids: ids, includetags: true, includeadditionalpreviews: true, includechildren: true, includekvtags: true, includevotes: true, includeforsaledata: true, includemetadata: true, language: 0 }, function(body) { let results = {}; let invalidSid = SteamID.fromIndividualAccountID(0).getSteamID64(); (body.publishedfiledetails || []).forEach((item) => { if (!item.publishedfileid) { return; } for (let i in item) { if (Object.hasOwnProperty.call(item, i) && item[i] && typeof item[i] === 'object' && item[i].constructor.name == 'Long') { item[i] = item[i].toString(); } } if (typeof item.creator === 'string' && item.creator != invalidSid) { item.creator = new SteamID(item.creator); } else { item.creator = null; } if (typeof item.banner === 'string' && item.banner != invalidSid) { item.banner = new SteamID(item.banner); } else { item.banner = null; } if (typeof item.incompatible_actor === 'string' && item.incompatible_actor != invalidSid) { item.incompatible_actor = new SteamID(item.incompatible_actor); } else { item.incompatible_actor = null; } let tags = {}; (item.kvtags || []).forEach(function(tag) { tags[tag.key] = tag.value; }); item.kvtags = tags; results[item.publishedfileid] = item; }); resolve({files: results}); }); }); }
Get details for some UGC files. @param {int[]} ids @param {function} [callback] @return {Promise}
getPublishedFileDetails
javascript
DoctorMcKay/node-steam-user
components/pubfiles.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/pubfiles.js
MIT
getStoreTagNames(language, tagIDs, callback) { return StdLib.Promises.timeoutCallbackPromise(10000, ['tags'], callback, (resolve, reject) => { this._sendUnified('Store.GetLocalizedNameForTags#1', {language, tagids: tagIDs}, (body) => { if (body.tags.length == 0) { return reject(new Error('Unable to get tag data; is your language correct?')); } let tags = {}; body.tags.forEach((tag) => { tags[tag.tagid] = {name: tag.name, englishName: tag.english_name}; }); resolve({tags}); }); }); }
Get the localized names for given store tags. @param {string} language - The full name of the language you're interested in, e.g. "english" or "spanish" @param {int[]} tagIDs - The IDs of the tags you're interested in @param {function} [callback] @return {Promise}
getStoreTagNames
javascript
DoctorMcKay/node-steam-user
components/store.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/store.js
MIT
trade(steamID) { if (typeof steamID === 'string') { steamID = new SteamID(steamID); } this._send(EMsg.EconTrading_InitiateTradeRequest, {other_steamid: steamID.getSteamID64()}); }
Sends a trade request to another user. @param {SteamID|string} steamID @deprecated Trading has been removed from the Steam UI in favor of trade offers. This does still work between bots however.
trade
javascript
DoctorMcKay/node-steam-user
components/trading.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/trading.js
MIT
cancelTradeRequest(steamID) { if (typeof steamID === 'string') { steamID = new SteamID(steamID); } this._send(EMsg.EconTrading_CancelTradeRequest, {other_steamid: steamID.getSteamID64()}); }
Cancels an outstanding trade request we sent to another user. @param {SteamID|string} steamID @deprecated Trading has been removed from the Steam UI in favor of trade offers. This does still work between bots however.
cancelTradeRequest
javascript
DoctorMcKay/node-steam-user
components/trading.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/trading.js
MIT
enableTwoFactor(callback) { return StdLib.Promises.timeoutCallbackPromise(15000, null, callback, (resolve, reject) => { this._sendUnified('TwoFactor.AddAuthenticator#1', { steamid: this.steamID.getSteamID64(), authenticator_type: 1, device_identifier: SteamTotp.getDeviceID(this.steamID), sms_phone_id: '1', version: 2 }, (body) => { body.server_time = typeof body.server_time === 'string' ? parseInt(body.server_time, 10) : (body.server_time || null); body.shared_secret = body.shared_secret ? body.shared_secret.toString('base64') : null; body.identity_secret = body.identity_secret ? body.identity_secret.toString('base64') : null; body.secret_1 = body.secret_1 ? body.secret_1.toString('base64') : null; // Delete all the null keys for (let i in body) { if (Object.hasOwnProperty.call(body, i) && body[i] === null) { delete body[i]; } } resolve(body); }); }); }
Start the process to enable TOTP two-factor authentication for your account @param {function} [callback] - Called when an activation SMS has been sent. @return {Promise}
enableTwoFactor
javascript
DoctorMcKay/node-steam-user
components/twofactor.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/twofactor.js
MIT
finalizeTwoFactor(secret, activationCode, callback) { let attemptsLeft = 30; let diff = 0; let self = this; return StdLib.Promises.timeoutCallbackPromise(15000, null, callback, (resolve, reject) => { SteamTotp.getTimeOffset((err, offset, latency) => { if (err) { return reject(err); } diff = offset; finalize(); }); function finalize() { let code = SteamTotp.generateAuthCode(secret, diff); self._sendUnified('TwoFactor.FinalizeAddAuthenticator#1', { steamid: self.steamID.getSteamID64(), authenticator_code: code, authenticator_time: Math.floor(Date.now() / 1000), activation_code: activationCode }, (body) => { if (body.server_time) { diff = parseInt(body.server_time, 10) - Math.floor(Date.now() / 1000); } if (body.status == 89) { return reject(new Error('Invalid activation code')); } else if (!body.success) { return reject(new Error('Error ' + body.status)); } else if (body.want_more) { attemptsLeft--; diff += 30; if (attemptsLeft <= 0) { return reject(new Error('Failed to finalize adding authenticator after 30 attempts')); } finalize(); } else { resolve(); } }); } }); }
Finalize the process of enabling TOTP two-factor authentication @param {Buffer|string} secret - Your shared secret @param {string} activationCode - The activation code you got in your email @param {function} [callback] - Called with a single Error argument, or null on success @return {Promise}
finalizeTwoFactor
javascript
DoctorMcKay/node-steam-user
components/twofactor.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/twofactor.js
MIT
function finalize() { let code = SteamTotp.generateAuthCode(secret, diff); self._sendUnified('TwoFactor.FinalizeAddAuthenticator#1', { steamid: self.steamID.getSteamID64(), authenticator_code: code, authenticator_time: Math.floor(Date.now() / 1000), activation_code: activationCode }, (body) => { if (body.server_time) { diff = parseInt(body.server_time, 10) - Math.floor(Date.now() / 1000); } if (body.status == 89) { return reject(new Error('Invalid activation code')); } else if (!body.success) { return reject(new Error('Error ' + body.status)); } else if (body.want_more) { attemptsLeft--; diff += 30; if (attemptsLeft <= 0) { return reject(new Error('Failed to finalize adding authenticator after 30 attempts')); } finalize(); } else { resolve(); } }); }
Finalize the process of enabling TOTP two-factor authentication @param {Buffer|string} secret - Your shared secret @param {string} activationCode - The activation code you got in your email @param {function} [callback] - Called with a single Error argument, or null on success @return {Promise}
finalize
javascript
DoctorMcKay/node-steam-user
components/twofactor.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/twofactor.js
MIT
sendRequest(request) { return new Promise((resolve) => { this._user._send({ msg: this._user.steamID ? EMsg.ServiceMethodCallFromClient : EMsg.ServiceMethodCallFromClientNonAuthed, proto: { target_job_name: `${request.apiInterface}.${request.apiMethod}#${request.apiVersion}`, realm: 1 } }, request.requestData, (body, hdr) => { resolve({ result: hdr.proto.eresult, errorMessage: hdr.proto.error_message, responseData: body.toBuffer() }); }); }); }
@param {ApiRequest} request @returns {Promise<ApiResponse>}
sendRequest
javascript
DoctorMcKay/node-steam-user
components/classes/CMAuthTransport.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/classes/CMAuthTransport.js
MIT
close() { // do nothing }
@param {ApiRequest} request @returns {Promise<ApiResponse>}
close
javascript
DoctorMcKay/node-steam-user
components/classes/CMAuthTransport.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/classes/CMAuthTransport.js
MIT
constructor(user, chosenServer) { super(user); this.connectionType = 'TCP'; this.sessionKey = null; this._debug('Connecting to TCP CM: ' + chosenServer.endpoint); let cmParts = chosenServer.endpoint.split(':'); let cmHost = cmParts[0]; let cmPort = parseInt(cmParts[1], 10); if (user.options.httpProxy) { let url = new URL(user.options.httpProxy); let prox = { protocol: url.protocol, host: url.hostname, port: url.port, method: 'CONNECT', path: chosenServer.endpoint, localAddress: user.options.localAddress, localPort: user.options.localPort }; if (url.username) { prox.headers = { 'Proxy-Authorization': `Basic ${(Buffer.from(`${url.username}:${url.password || ''}`, 'utf8')).toString('base64')}` }; } let connectionEstablished = false; let req = HTTP.request(prox); req.end(); req.setTimeout(user.options.proxyTimeout || 5000); req.on('connect', (res, socket) => { if (connectionEstablished) { // somehow we're already connected, or we aborted socket.end(); return; } connectionEstablished = true; req.setTimeout(0); // disable timeout if (res.statusCode != 200) { this._fatal(new Error(`Proxy HTTP CONNECT ${res.statusCode} ${res.statusMessage}`)); return; } this.stream = socket; this._setupStream(); }); req.on('timeout', () => { connectionEstablished = true; this.user._cleanupClosedConnection(); this._fatal(new Error('Proxy connection timed out')); }); req.on('error', (err) => { connectionEstablished = true; this.user._cleanupClosedConnection(); this._fatal(err); }); } else { let socket = new Socket(); this.stream = socket; this._setupStream(); socket.connect({ port: cmPort, host: cmHost, localAddress: user.options.localAddress, localPort: user.options.localPort }); this.stream.setTimeout(this.user._connectTimeout); } }
Create a new TCP connection, and connect @param {SteamUser} user @param {CmServer} chosenServer @constructor
constructor
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/tcp.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/tcp.js
MIT
_setupStream() { this.stream.on('readable', this._readMessage.bind(this)); this.stream.on('error', (err) => this._debug('TCP connection error: ' + err.message)); // "close" will be emitted and we'll reconnect this.stream.on('end', () => this._debug('TCP connection ended')); this.stream.on('close', () => this.user._handleConnectionClose(this)); this.stream.on('connect', () => { this._debug('TCP connection established'); this.stream.setTimeout(Math.min(this.user._connectTimeout, 2000)); // give the CM max 2 seconds to send ChannelEncryptRequest }); this.stream.on('timeout', () => { this._debug('TCP connection timed out'); this.user._connectTimeout = Math.min(this.user._connectTimeout * 2, 10000); // 10 seconds max this.end(true); this.user._doConnection(); }); }
Set up the stream with event handlers @private
_setupStream
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/tcp.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/tcp.js
MIT
end(andIgnore) { if (this.stream) { this._debug('Ending connection' + (andIgnore ? ' and removing all listeners' : '')); if (andIgnore) { this.removeAllListeners(); this.stream.removeAllListeners(); this.stream.on('error', () => { }); } this.stream.end(); if (andIgnore) { this.stream.destroy(); } } else { this._debug('We wanted to end connection, but there is no stream'); } }
End the connection @param {boolean} [andIgnore=false] - Pass true to also ignore all further events from this connection
end
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/tcp.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/tcp.js
MIT
send(data) { if (this.sessionKey) { data = SteamCrypto.symmetricEncryptWithHmacIv(data, this.sessionKey); } if (!this.stream) { this._debug('Tried to send message, but there is no stream'); return; } let buf = Buffer.alloc(4 + 4 + data.length); buf.writeUInt32LE(data.length, 0); buf.write(MAGIC, 4); data.copy(buf, 8); try { this.stream.write(buf); } catch (error) { this._debug('Error writing to socket: ' + error.message); this._fatal(error); } }
Send data over the connection @param {Buffer} data
send
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/tcp.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/tcp.js
MIT
_readMessage() { if (!this._messageLength) { // We are not in the middle of a message, so the next thing on the wire should be a header let header = this.stream.read(8); if (!header) { return; // maybe we should tear down the connection here } this._messageLength = header.readUInt32LE(0); if (header.slice(4).toString('ascii') != MAGIC) { // We definitely need to tear down the connection here this._fatal(new Error('Connection out of sync')); return; } } if (!this.stream) { this._debug('Tried to read message, but there is no stream'); return; } let message; try { message = this.stream.read(this._messageLength); } catch (error) { this._debug('Error reading from socket: ' + error.message); this._fatal(error); return; } if (!message) { this._debug('Got incomplete message; expecting ' + this._messageLength + ' more bytes'); return; } delete this._messageLength; if (this.sessionKey) { try { message = SteamCrypto.symmetricDecrypt(message, this.sessionKey, true); } catch (ex) { this._fatal(new Error('Encrypted message authentication failed')); return; } } // noinspection JSAccessibilityCheck this.user._handleNetMessage(message, this); this._readMessage(); }
Try to read a message from the socket @private
_readMessage
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/tcp.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/tcp.js
MIT
_fatal(err) { if (!err.message.startsWith('Proxy')) { err.eresult = EResult.NoConnection; } this.user.emit('error', err); // noinspection JSAccessibilityCheck this.user._disconnect(true); }
There was a fatal transport error @param {Error} err @private
_fatal
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/tcp.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/tcp.js
MIT
constructor(user, chosenServer) { super(user); this.connectionType = 'WS'; let addr = chosenServer.endpoint; this._debug(`Connecting to WebSocket CM ${addr}`); this.stream = new WS13.WebSocket(`wss://${addr}/cmsocket/`, { pingInterval: 30000, proxyTimeout: this.user.options.proxyTimeout, connection: { localAddress: this.user.options.localAddress, agent: this.user._getProxyAgent() } }); // Set up the connection timeout this.stream.setTimeout(this.user._connectTimeout); this.stream.on('debug', msg => this._debug(msg, true)); this.stream.on('message', this._readMessage.bind(this)); this.stream.on('disconnected', (code, reason, initiatedByUs) => { if (this._disconnected) { return; } this._disconnected = true; this._debug(`WebSocket closed by ${initiatedByUs ? 'us' : 'remote'} with code ${code} and reason "${reason}"`); this.user._handleConnectionClose(this); }); this.stream.on('error', (err) => { if (this._disconnected) { return; } this._disconnected = true; this._debug('WebSocket disconnected with error: ' + err.message); if (err.proxyConnecting || err.constructor.name == 'SocksClientError') { // This error happened while connecting to the proxy this.user._cleanupClosedConnection(); this.user.emit('error', err); } else { this.user._handleConnectionClose(this); } }); this.stream.on('connected', () => { this._debug('WebSocket connection success; now logging in'); this.stream.setTimeout(0); // Disable timeout this.user._sendLogOn(); }); this.stream.on('timeout', () => { if (this._disconnected) { return; } this._disconnected = true; this._debug('WS connection timed out'); this.user._connectTimeout = Math.min(this.user._connectTimeout * 2, 10000); // 10 seconds max this.stream.disconnect(); this.user._doConnection(); }); }
@param {SteamUser} user @param {CmServer} chosenServer
constructor
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/websocket.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/websocket.js
MIT
end(andIgnore) { if (this.stream && [WS13.State.Connected, WS13.State.Connecting].indexOf(this.stream.state) != -1) { this._debug('Ending connection' + (andIgnore ? ' and removing all listeners' : '')); if (andIgnore) { this.stream.removeAllListeners(); this.stream.on('error', () => { }); this.stream.disconnect(); this._disconnected = true; return; } this.stream.disconnect(); } else { this._debug('We wanted to end connection, but it\'s not connected or connecting'); } }
End the connection @param {boolean} [andIgnore=false] - Pass true to also ignore all further events from this connection
end
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/websocket.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/websocket.js
MIT
send(data) { if (this._disconnected) { return; } try { this.stream.send(data); } catch (ex) { this._debug('WebSocket send error: ' + ex.message); try { this._disconnected = true; this.stream.disconnect(WS13.StatusCode.AbnormalTermination); this.user._handleConnectionClose(this); } catch (ex) { this._debug('WebSocket teardown error: ' + ex.message); } } }
Send data over the connection. @param {Buffer} data
send
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/websocket.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/websocket.js
MIT
_readMessage(type, msg) { if (type != WS13.FrameType.Data.Binary) { this._debug('Got frame with wrong data type: ' + type); return; } this.user._handleNetMessage(msg, this); }
Read a message from the WebSocket @param {int} type @param {string|Buffer} msg @private
_readMessage
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/websocket.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/websocket.js
MIT
_pingCM(addr, callback) { let host = addr.split(':')[0]; let port = parseInt(addr.split(':')[1] || '443', 10); let options = { host, port, timeout: 700, path: '/cmping/', agent: this.user._getProxyAgent() }; // The timeout option seems to not work let finished = false; let timeout = setTimeout(() => { if (finished) { return; } this._debug(`CM ${addr} timed out`, true); callback(new Error(`CM ${addr} timed out`)); finished = true; }, 700); let start = Date.now(); HTTPS.get(options, (res) => { clearTimeout(timeout); if (finished) { return; } let latency = Date.now() - start; res.on('data', () => { }); // there is no body, so just throw it away if (res.statusCode != 200) { // CM is disqualified this._debug(`CM ${addr} disqualified: HTTP error ${res.statusCode}`, true); callback(new Error(`CM ${addr} disqualified: HTTP error ${res.statusCode}`)); return; } let load = parseInt(res.headers['x-steam-cmload'], 10) || 999; this._debug(`CM ${addr} latency ${latency} ms + load ${load}`, true); callback(null, {addr, load, latency}); }).on('error', (err) => { clearTimeout(timeout); if (!finished) { this._debug(`CM ${addr} disqualified: ${err.message}`, true); callback(new Error(`CM ${addr} disqualified: ${err.message}`)); // if error, this CM is disqualified } }); }
Ping a CM and return its load and latency @param addr @param callback @private
_pingCM
javascript
DoctorMcKay/node-steam-user
components/connection_protocols/websocket.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/components/connection_protocols/websocket.js
MIT
function promptAsync(question, sensitiveInput) { return new Promise((resolve) => { let rl = createInterface({ input: process.stdin, output: sensitiveInput ? null : process.stdout, terminal: true }); if (sensitiveInput) { // We have to write the question manually if we didn't give readline an output stream process.stdout.write(`${question.trim()} [masked] `); } rl.question(question, (result) => { if (sensitiveInput) { // We have to manually print a newline process.stdout.write('\n'); } rl.close(); resolve(result); }); }); }
@param {string} question @param {boolean} [sensitiveInput=false] @return Promise<string>
promptAsync
javascript
DoctorMcKay/node-steam-user
examples/lib/collect_credentials.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/examples/lib/collect_credentials.js
MIT
function protobufTypeToJsType(type) { switch (type) { case 'double': case 'float': case 'int32': case 'uint32': case 'sint32': case 'fixed32': case 'sfixed32': return 'number'; case 'int64': case 'uint64': case 'sint64': case 'fixed64': case 'sfixed64': // 64-bit numbers are represented as strings return 'string'; case 'bool': return 'boolean'; case 'string': return 'string'; case 'bytes': return 'Buffer'; default: if (type[0] == '.') { // It's another protobuf msg, or an enum if (type[1] == 'E') { // It's an enum return type.substring(1); } return 'Proto' + type.replace(/\./g, '_'); } throw new Error(`Unknown protobuf type ${type}`); } }
\n * @typedef {object} ${resolvedName}\n`; for (let j in obj[i].fields) { let type = protobufTypeToJsType(obj[i].fields[j].type); let name = j; if (type == 'number' && ['eresult', 'eResult', 'result'].includes(name)) { type = 'EResult'; } if (OVERRIDE_TYPEDEF_TYPES[resolvedName] && OVERRIDE_TYPEDEF_TYPES[resolvedName][j]) { type = OVERRIDE_TYPEDEF_TYPES[resolvedName][j]; } switch (obj[i].fields[j].rule) { case 'repeated': type += '[]'; break; case 'required': break; default: // optional // Does this field have a default value? if (obj[i].fields[j].options && !['undefined', 'string'].includes(typeof obj[i].fields[j].options.default)) { name = `[${name}=${obj[i].fields[j].options.default}]`; } else { name = `[${name}]`; } } output += ` * @property {${type}} ${name}\n`; } output += '
protobufTypeToJsType
javascript
DoctorMcKay/node-steam-user
scripts/generate-protos.js
https://github.com/DoctorMcKay/node-steam-user/blob/master/scripts/generate-protos.js
MIT
getType = (value) => { if (value === 'auto') { return { type: value, value: 0 } } for (var i = 0; i < types.length; i++) { let type = types[i] if (type.regexp.test(value)) { return { type: type.name, value: parseFloat(value) } } } return { type: '', value: value } }
Fallback option If no suffix specified, assigning "px"
getType
javascript
euvl/vue-notification
src/parser.js
https://github.com/euvl/vue-notification/blob/master/src/parser.js
MIT
parse = (value) => { switch (typeof value) { case 'number': return { type: 'px', value } case 'string': return getType(value) default: return { type: '', value } } }
Fallback option If no suffix specified, assigning "px"
parse
javascript
euvl/vue-notification
src/parser.js
https://github.com/euvl/vue-notification/blob/master/src/parser.js
MIT
parse = (value) => { switch (typeof value) { case 'number': return { type: 'px', value } case 'string': return getType(value) default: return { type: '', value } } }
Fallback option If no suffix specified, assigning "px"
parse
javascript
euvl/vue-notification
src/parser.js
https://github.com/euvl/vue-notification/blob/master/src/parser.js
MIT
split = (value) => { if (typeof value !== 'string') { return [] } return value.split(/\s+/gi).filter(v => v) }
Splits space/tab separated string into array and cleans empty string items.
split
javascript
euvl/vue-notification
src/util.js
https://github.com/euvl/vue-notification/blob/master/src/util.js
MIT
split = (value) => { if (typeof value !== 'string') { return [] } return value.split(/\s+/gi).filter(v => v) }
Splits space/tab separated string into array and cleans empty string items.
split
javascript
euvl/vue-notification
src/util.js
https://github.com/euvl/vue-notification/blob/master/src/util.js
MIT
listToDirection = (value) => { if (typeof value === 'string') { value = split(value) } let x = null let y = null value.forEach(v => { if (directions.y.indexOf(v) !== -1) { y = v } if (directions.x.indexOf(v) !== -1) { x = v } }) return { x, y } }
Cleanes and transforms string of format "x y" into object {x, y}. Possible combinations: x - left, center, right y - top, bottom
listToDirection
javascript
euvl/vue-notification
src/util.js
https://github.com/euvl/vue-notification/blob/master/src/util.js
MIT
listToDirection = (value) => { if (typeof value === 'string') { value = split(value) } let x = null let y = null value.forEach(v => { if (directions.y.indexOf(v) !== -1) { y = v } if (directions.x.indexOf(v) !== -1) { x = v } }) return { x, y } }
Cleanes and transforms string of format "x y" into object {x, y}. Possible combinations: x - left, center, right y - top, bottom
listToDirection
javascript
euvl/vue-notification
src/util.js
https://github.com/euvl/vue-notification/blob/master/src/util.js
MIT
function Timer (callback, delay, notifItem) { let start, remaining = delay; this.pause = function() { clearTimeout(notifItem.timer); remaining -= Date.now() - start; }; this.resume = function() { start = Date.now(); clearTimeout(notifItem.timer); notifItem.timer = setTimeout(callback, remaining); }; this.resume(); }
Cleanes and transforms string of format "x y" into object {x, y}. Possible combinations: x - left, center, right y - top, bottom
Timer
javascript
euvl/vue-notification
src/util.js
https://github.com/euvl/vue-notification/blob/master/src/util.js
MIT
function registerCmdTask (name, opts) { opts = _.extend({ cmd: process.execPath, desc: '', args: [] }, opts); grunt.registerTask(name, opts.desc, function () { // adapted from http://stackoverflow.com/a/24796749 var done = this.async(); grunt.util.spawn({ cmd: opts.cmd, args: opts.args, opts: { stdio: 'inherit' } }, done); }); }
Delegate task to command line. @param {String} name - If taskname starts with npm it's run a npm script (i.e. `npm run foobar` @param {Object} d - d as in data @param {Array} d.args - arguments to pass to the d.cmd @param {String} [d.cmd = process.execPath] @param {String} [d.desc = ''] - description @param {...string} args space-separated arguments passed to the cmd
registerCmdTask
javascript
CartoDB/cartodb
Gruntfile.js
https://github.com/CartoDB/cartodb/blob/master/Gruntfile.js
BSD-3-Clause
isTooltipInsideViewport = function (bound, viewportBound, tooltipBound) { if (bound === 'top' || bound === 'left') { return viewportBound <= tooltipBound; } if (bound === 'right' || bound === 'bottom') { return viewportBound >= tooltipBound; } }
Tipsy tooltip view. - Needs an element to work. - Inits tipsy library. - Clean bastard tipsy bindings easily.
isTooltipInsideViewport
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/components/tipsy-tooltip-view.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/components/tipsy-tooltip-view.js
BSD-3-Clause
getTooltipBodyGravity = function (gravityOptions, viewportBoundaries, tooltipBoundaries) { var nonCollisioningEdges = _.filter(['e', 'w'], function (edge) { var bound = gravityOptions[edge]; return isTooltipInsideViewport(bound, viewportBoundaries[bound], tooltipBoundaries[bound]); }); if (nonCollisioningEdges.length === 1) { return nonCollisioningEdges[0]; } return ''; }
Tipsy tooltip view. - Needs an element to work. - Inits tipsy library. - Clean bastard tipsy bindings easily.
getTooltipBodyGravity
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/components/tipsy-tooltip-view.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/components/tipsy-tooltip-view.js
BSD-3-Clause
BackgroundImporter = function (options) { this.options = options || {}; this._importers = {}; this.initialize(this.options); }
Background polling manager It will pool all polling operations (imports) that happens in the Builder
BackgroundImporter
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/components/background-importer/background-importer.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/components/background-importer/background-importer.js
BSD-3-Clause
_addItem = function () { self.items.push(item); self.$list.append(item.el); item.editor.on('all', function (event) { if (event === 'change') return; // args = ["key:change", itemEditor, fieldEditor] var args = _.toArray(arguments); args[0] = 'item:' + event; args.splice(1, 0, self); // args = ["item:key:change", this=listEditor, itemEditor, fieldEditor] editors.List.prototype.trigger.apply(this, args); }, self); item.editor.on('change', function () { if (!item.addEventTriggered) { item.addEventTriggered = true; this.trigger('add', this, item.editor); } this.trigger('item:change', this, item.editor); this.trigger('change', this); }, self); item.editor.on('focus', function () { if (this.hasFocus) return; this.trigger('focus', this); }, self); item.editor.on('blur', function () { if (!this.hasFocus) return; var self = this; setTimeout(function () { if (_.find(self.items, function (item) { return item.editor.hasFocus; })) return; self.trigger('blur', self); }, 0); }, self); if (userInitiated || value) { item.addEventTriggered = true; } if (userInitiated) { self.trigger('add', self, item.editor); self.trigger('change', self); } }
Add a new item to the list @param {Mixed} [value] Value for the new item editor @param {Boolean} [userInitiated] If the item was added by the user clicking 'add' or pressing `Enter`
_addItem
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/components/form-components/editors/list/list.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/components/form-components/editors/list/list.js
BSD-3-Clause
_goToStep (step) { this.$('.js-step').removeClass('is-active'); this.$(`.js-step${step}`).addClass('is-active'); }
Cards with additional info in disabled connectors
_goToStep
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/components/modals/add-layer/content/imports/imports-selector/import-request-view.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/components/modals/add-layer/content/imports/imports-selector/import-request-view.js
BSD-3-Clause
function canChangeToPrivate (userModel, currentPrivacy, option) { return currentPrivacy !== 'PRIVATE' && option.privacy === 'PRIVATE' && userModel.hasRemainingPrivateMaps(); }
type property should match the value given from the API.
canChangeToPrivate
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/components/modals/publish/create-privacy-options.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/components/modals/publish/create-privacy-options.js
BSD-3-Clause
function canChangeToPublic (userModel, currentPrivacy, option) { return currentPrivacy !== 'PRIVATE' || currentPrivacy === 'PRIVATE' && option.privacy !== 'PRIVATE' && userModel.hasRemainingPublicMaps(); }
type property should match the value given from the API.
canChangeToPublic
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/components/modals/publish/create-privacy-options.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/components/modals/publish/create-privacy-options.js
BSD-3-Clause
createDefaultCartoDBAttrs = function (oldLayerStyle) { return { kind: 'carto', options: { interactivity: '', tile_style: (oldLayerStyle && oldLayerStyle.options.tile_style) || camshaftReference.getDefaultCartoCSSForType(), cartocss: (oldLayerStyle && oldLayerStyle.options.tile_style) || camshaftReference.getDefaultCartoCSSForType(), style_version: '2.1.1', visible: true, style_properties: (oldLayerStyle && oldLayerStyle.options.style_properties), sql_wrap: (oldLayerStyle && oldLayerStyle.options.sql_wrap) }, tooltip: oldLayerStyle ? oldLayerStyle.tooltip : {}, infowindow: oldLayerStyle ? oldLayerStyle.infowindow : {} }; }
Coordinate side-effects done on explicit interactions. @param {Object} params @param {Object} params.userModel @param {Object} params.analysisDefinitionsCollection @param {Object} params.analysisDefinitionNodesCollection @param {Object} params.widgetDefinitionsCollection @return {Object} that contains all user-actions that the user may do related to a map
createDefaultCartoDBAttrs
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/user-actions.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/user-actions.js
BSD-3-Clause
deleteOrphanedAnalyses = function () { analysisDefinitionNodesCollection .toArray() .forEach(function (nodeDefModel) { if (!layerDefinitionsCollection.anyContainsNode(nodeDefModel)) { nodeDefModel.destroy(); } }); analysisDefinitionsCollection .toArray() .forEach(function (analysisDefModel) { if (!analysisDefModel.getNodeDefinitionModel()) { analysisDefModel.destroy(); } }); }
Coordinate side-effects done on explicit interactions. @param {Object} params @param {Object} params.userModel @param {Object} params.analysisDefinitionsCollection @param {Object} params.analysisDefinitionNodesCollection @param {Object} params.widgetDefinitionsCollection @return {Object} that contains all user-actions that the user may do related to a map
deleteOrphanedAnalyses
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/user-actions.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/user-actions.js
BSD-3-Clause
restoreWidgetsFromLayer = function (affectedWidgets, layerDefModel, callback, callbackOptions) { if (!affectedWidgets || !_.isArray(affectedWidgets)) throw new Error('affectedWidgets is required'); if (!layerDefModel) throw new Error('layerDefModel is required'); if (!callback) throw new Error('callback is required'); var notification; var restoringError; var onWidgetFinished = _.after(affectedWidgets.length, function () { if (notification) { if (!restoringError) { notification.set({ status: 'success', info: _t('notifications.widgets.restored'), closable: true }); } else { Notifier.removeNotification(notification); } } callback(layerDefModel, callbackOptions); }); if (affectedWidgets.length > 0) { notification = Notifier.addNotification({ status: 'loading', info: _t('notifications.widgets.restoring'), closable: false }); // Create widgets with new source and layer_id _.each(affectedWidgets, function (attrs) { attrs.layer_id = attrs.layer_id || layerDefModel.id; widgetDefinitionsCollection.create( attrs, { wait: true, success: onWidgetFinished, error: function (e, mdl) { notification = Notifier.addNotification({ status: 'error', info: _t('notifications.widgets.error.title') + _t('notifications.widgets.error.body', { body: '', error: mdl && mdl.get('title') }), closable: true }); restoringError = true; onWidgetFinished(); } } ); }); } else { callback(layerDefModel, callbackOptions); } }
Coordinate side-effects done on explicit interactions. @param {Object} params @param {Object} params.userModel @param {Object} params.analysisDefinitionsCollection @param {Object} params.analysisDefinitionNodesCollection @param {Object} params.widgetDefinitionsCollection @return {Object} that contains all user-actions that the user may do related to a map
restoreWidgetsFromLayer
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/user-actions.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/user-actions.js
BSD-3-Clause
containsNode = function (m) { return m !== layerDefModel && m !== nodeDefModel && m.containsNode(nodeDefModel); }
Creates a new analysis node on a particular layer. It's assumed to be created on top of an existing node. @param {Object} nodeAttrs @param {Object} layerDefModel - instance of layer-definition-model @return {Object} instance of analysis-definition-node-model
containsNode
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/user-actions.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/user-actions.js
BSD-3-Clause
moveNode = function (oldNode) { var newId = nodeIds.changeLetter(oldNode.id, newLetter); var newNode = oldNode.clone(newId); var affectedWidgetsBySourceChange = widgetDefinitionsCollection.where({ source: oldNode.id }); analysisDefinitionNodesCollection.invoke('changeSourceIds', oldNode.id, newId); _.each(affectedWidgetsBySourceChange, function (m) { // Store attrs from affected widget for creating a new // instance when layer is created affectedWidgetAttrsBySourceChange.push( _.extend( _.omit(m.toJSON(), 'id', 'layer_id', 'source', 'order'), { avoidNotification: true, source: { id: newId } } ) ); // Destroy widgets pointing to that source until new layer is created m.attributes.avoidNotification = true; m.destroy(); }); return newNode; }
A layer for an existing node have different side-effects depending on the context in which the node exists. @param {string} nodeid @param {string} letter of the layer where the node change comes @param {object} cfg @param {number} cfg.at
moveNode
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/user-actions.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/user-actions.js
BSD-3-Clause
moveNodeToParentLayer = function (node) { var oldNodeId = node.id; var newId = nodeIds.prev(prevId); node.set('id', newId); // Update any depending objects' source analysisDefinitionNodesCollection.each(function (m) { if (!_.contains(toDestroy, m)) { m.changeSourceIds(oldNodeId, newId, true); } }); var maybeUpdateSource = function (m) { if (m.get('source') === oldNodeId && !_.contains(toDestroy, m)) { m.save({ source: newId }, { silent: true }); } }; layerDefinitionsCollection.each(maybeUpdateSource); widgetDefinitionsCollection.each(maybeUpdateSource); prevId = newId; return node; }
A layer for an existing node have different side-effects depending on the context in which the node exists. @param {string} nodeid @param {string} letter of the layer where the node change comes @param {object} cfg @param {number} cfg.at
moveNodeToParentLayer
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/user-actions.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/user-actions.js
BSD-3-Clause
maybeUpdateSource = function (m) { if (m.get('source') === oldNodeId && !_.contains(toDestroy, m)) { m.save({ source: newId }, { silent: true }); } }
A layer for an existing node have different side-effects depending on the context in which the node exists. @param {string} nodeid @param {string} letter of the layer where the node change comes @param {object} cfg @param {number} cfg.at
maybeUpdateSource
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/user-actions.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/user-actions.js
BSD-3-Clause
function NetworkResponseInterceptor () { this._originalAjax = $.ajax; this._successInterceptors = []; this._errorInterceptors = []; this._urlPatterns = []; }
Network Interceptors Tool to easily intercept network responses in order to override or add behaviours on top of the usual ones
NetworkResponseInterceptor
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
BSD-3-Clause
interceptErrorFn = function () { this._applyErrorInterceptors.apply(this, arguments); errorCallback && errorCallback.apply(this, arguments); }
Network Interceptors Tool to easily intercept network responses in order to override or add behaviours on top of the usual ones
interceptErrorFn
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
BSD-3-Clause
interceptErrorFn = function () { this._applyErrorInterceptors.apply(this, arguments); errorCallback && errorCallback.apply(this, arguments); }
Network Interceptors Tool to easily intercept network responses in order to override or add behaviours on top of the usual ones
interceptErrorFn
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
BSD-3-Clause
interceptSuccessFn = function () { this._applySuccessInterceptors.apply(this, arguments); successCallback && successCallback.apply(this, arguments); }
Network Interceptors Tool to easily intercept network responses in order to override or add behaviours on top of the usual ones
interceptSuccessFn
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
BSD-3-Clause
interceptSuccessFn = function () { this._applySuccessInterceptors.apply(this, arguments); successCallback && successCallback.apply(this, arguments); }
Network Interceptors Tool to easily intercept network responses in order to override or add behaviours on top of the usual ones
interceptSuccessFn
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptor.js
BSD-3-Clause
updateAnalysisQuerySchema = function () { var query = analysis.get('query'); var status = analysis.get('status'); var error = analysis.get('error'); node.querySchemaModel.set({ status: 'unfetched', query: query, ready: status === 'ready' }); node.queryGeometryModel.set({ status: 'unfetched', query: query, ready: status === 'ready' }); node.set({ status: status, error: error }); if (status === 'ready') { if (!node.__initialization) { node.trigger('queryObjectsUpdated', node); } node.__initialization = false; } }
Only manage **ANALYSIS NODES** and **ANALYSIS DEFINITION** actions between Deep-Insights (CARTO.js) and Builder
updateAnalysisQuerySchema
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/deep-insights-integration/analyses-integration.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/deep-insights-integration/analyses-integration.js
BSD-3-Clause
diDashboardHelpers = function (deepInsightsDashboard) { this._deepInsightsDashboard = deepInsightsDashboard; return this; }
Create a class for providing the Deep Insights Helpers necessary for any implementation within deep-insights-integration.
diDashboardHelpers
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/deep-insights-integration/deep-insights-helpers.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/deep-insights-integration/deep-insights-helpers.js
BSD-3-Clause
applyDefaultStyles = function () { simpleGeom = queryGeometryModel.get('simple_geom'); styleModel.setDefaultPropertiesByType('simple', simpleGeom); }
Only manage **LAYER** actions between Deep-Insights (CARTO.js) and Builder
applyDefaultStyles
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/deep-insights-integration/layers-integration.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/deep-insights-integration/layers-integration.js
BSD-3-Clause
function recreateWidget (currentTimeseries, newLayer, animated) { var persistName = currentTimeseries && currentTimeseries.get('title'); // This prevents a bug if user has a range selected and switches column newLayer.unset('customDuration'); this._createTimeseries(newLayer, animated, persistName); }
Massage some data points to the expected format of deep-insights API
recreateWidget
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/deep-insights-integration/widgets-integration.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/deep-insights-integration/widgets-integration.js
BSD-3-Clause
function getColumnType (sourceId, columnName) { var node = this._analysisDefinitionNodesCollection.get(sourceId); return node && node.querySchemaModel.getColumnType(columnName); }
Massage some data points to the expected format of deep-insights API
getColumnType
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/deep-insights-integration/widgets-integration.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/deep-insights-integration/widgets-integration.js
BSD-3-Clause
_initVueInstanceDialogs () { const root = 'root'; if (this.vueInstanceDialogs) { this.vueInstanceDialogs.$router.push({ name: root }); this.vueInstanceDialogs.$destroy(); } var self = this; const el = this.$el.context.getElementsByClassName('js-layer-dialog')[0]; const router = new Router({ base: window.location.origin + window.location.pathname, routes: [ { path: '', component: Vue.component(root, { template: ` <div style="font-family: 'Montserrat', 'Open Sans', Arial, sans-serif;"> <router-view></router-view> </div> ` }), name: 'root', children: routesToAddLayers('layer') } ] }); this.vueInstanceDialogs = new Vue({ el, router, store, i18n, provide () { const backboneViews = { backgroundPollingView: { getBackgroundPollingView: () => window.importerManager, backgroundPollingView: window.importerManager } }; const addLayer = (layer, div) => { div.innerHTML = renderLoading({ title: _t('components.modals.add-layer.adding-new-layer') }); const tablesCollection = new TablesCollection([layer], { configModel: self._configModel }); self._userActions.createLayerFromTable(tablesCollection.at(0).getTableModel(), { success: function (model) { self._userModel.updateTableCount(); self.trigger('addLayerDone'); MetricsTracker.track(MetricsTypes.CREATED_LAYER, { empty: false, layer_id: model.get('id') }); }, error: function (req, resp) { let error; if (resp.responseText.indexOf('You have reached your table quota') !== -1) { error = new ErrorDetailsView({ error: { errorCode: 8002 }, userModel: self._userModel, configModel: self._configModel }); } else { error = new ErrorView({ title: _t('components.modals.add-layer.add-layer-error') }); } div.innerHTML = ''; div.append(error.render().el); } }); }; return { backboneViews, addLayer }; }, template: '<div><router-view></router-view></div>' }); }
View to render layer definitions list
_initVueInstanceDialogs
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/layers/layers-view.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/layers/layers-view.js
BSD-3-Clause
provide () { const backboneViews = { backgroundPollingView: { getBackgroundPollingView: () => window.importerManager, backgroundPollingView: window.importerManager } }; const addLayer = (layer, div) => { div.innerHTML = renderLoading({ title: _t('components.modals.add-layer.adding-new-layer') }); const tablesCollection = new TablesCollection([layer], { configModel: self._configModel }); self._userActions.createLayerFromTable(tablesCollection.at(0).getTableModel(), { success: function (model) { self._userModel.updateTableCount(); self.trigger('addLayerDone'); MetricsTracker.track(MetricsTypes.CREATED_LAYER, { empty: false, layer_id: model.get('id') }); }, error: function (req, resp) { let error; if (resp.responseText.indexOf('You have reached your table quota') !== -1) { error = new ErrorDetailsView({ error: { errorCode: 8002 }, userModel: self._userModel, configModel: self._configModel }); } else { error = new ErrorView({ title: _t('components.modals.add-layer.add-layer-error') }); } div.innerHTML = ''; div.append(error.render().el); } }); }; return { backboneViews, addLayer }; }
View to render layer definitions list
provide
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/layers/layers-view.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/layers/layers-view.js
BSD-3-Clause
addLayer = (layer, div) => { div.innerHTML = renderLoading({ title: _t('components.modals.add-layer.adding-new-layer') }); const tablesCollection = new TablesCollection([layer], { configModel: self._configModel }); self._userActions.createLayerFromTable(tablesCollection.at(0).getTableModel(), { success: function (model) { self._userModel.updateTableCount(); self.trigger('addLayerDone'); MetricsTracker.track(MetricsTypes.CREATED_LAYER, { empty: false, layer_id: model.get('id') }); }, error: function (req, resp) { let error; if (resp.responseText.indexOf('You have reached your table quota') !== -1) { error = new ErrorDetailsView({ error: { errorCode: 8002 }, userModel: self._userModel, configModel: self._configModel }); } else { error = new ErrorView({ title: _t('components.modals.add-layer.add-layer-error') }); } div.innerHTML = ''; div.append(error.render().el); } }); }
View to render layer definitions list
addLayer
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/layers/layers-view.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/layers/layers-view.js
BSD-3-Clause
addLayer = (layer, div) => { div.innerHTML = renderLoading({ title: _t('components.modals.add-layer.adding-new-layer') }); const tablesCollection = new TablesCollection([layer], { configModel: self._configModel }); self._userActions.createLayerFromTable(tablesCollection.at(0).getTableModel(), { success: function (model) { self._userModel.updateTableCount(); self.trigger('addLayerDone'); MetricsTracker.track(MetricsTypes.CREATED_LAYER, { empty: false, layer_id: model.get('id') }); }, error: function (req, resp) { let error; if (resp.responseText.indexOf('You have reached your table quota') !== -1) { error = new ErrorDetailsView({ error: { errorCode: 8002 }, userModel: self._userModel, configModel: self._configModel }); } else { error = new ErrorView({ title: _t('components.modals.add-layer.add-layer-error') }); } div.innerHTML = ''; div.append(error.render().el); } }); }
View to render layer definitions list
addLayer
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/layers/layers-view.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/layers/layers-view.js
BSD-3-Clause
onStatusChange = function () { if (queryGeometryModel.get('status') === 'fetching') return; queryGeometryModel.off('change:status', onStatusChange); self._appendNodeOption(nodeDefModel); cb(); }
@param {String} val val from select option
onStatusChange
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/layers/layer-content-views/analyses/analysis-source-options-model.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/layers/layer-content-views/analyses/analysis-source-options-model.js
BSD-3-Clause
function generateStyle (style, geometryType, mapContext, configModel) { if (style.type === 'none') { return { cartoCSS: CONFIG.GENERIC_STYLE, sql: null, layerType: 'CartoDB' }; } if (style.type !== 'simple' && geometryType !== 'point') { throw new Error('aggregated styling does not work with ' + geometryType); } // pre style conversion // some styles need some conversion, for example aggregated based on // torque need to move from aggregation to animated properties var conversion = styleConversion[style.type]; var properties; if (conversion) { properties = conversion(style.properties, configModel); if (properties) { style.properties = properties; } } // override geometryType for aggregated styles var geometryMapping = AggregatedFactory[style.type]; if (geometryMapping) { geometryType = geometryMapping.geometryType[geometryType]; } if (!geometryType) { throw new Error('geometry type not supported for ' + style.type); } var layerType = style.type === 'heatmap' || style.type === 'animation' ? 'torque' : 'CartoDB'; return { cartoCSS: generateCartoCSS(style, geometryType, configModel), sql: generateSQL(style, geometryType, mapContext), layerType: layerType }; }
given a styleDefinition object and the geometry type generates the query wrapper and the
generateStyle
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/style/style-converter.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/style/style-converter.js
BSD-3-Clause
function _isInvalidCategory (category) { return category.length === 0 || typeof category === 'undefined'; }
given a styleDefinition object and the geometry type generates the query wrapper and the
_isInvalidCategory
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/style/style-converter.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/style/style-converter.js
BSD-3-Clause
function StyleManager (layerDefinitionsCollection, map, configModel) { this.layerDefinitionsCollection = layerDefinitionsCollection; this.map = map; this._configModel = configModel; this._initBinds(); }
this class manages the changes in layerdef styles and generate the proper cartocss and sql
StyleManager
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/style/style-manager.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/style/style-manager.js
BSD-3-Clause
function _generate (layerDef) { return function () { self.generate(layerDef); }; }
this class manages the changes in layerdef styles and generate the proper cartocss and sql
_generate
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/style/style-manager.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/style/style-manager.js
BSD-3-Clause
function _bind (layerDef) { if (layerDef && layerDef.styleModel) { layerDef.styleModel.bind('change', _generate(layerDef), this); layerDef.bind('change:autoStyle', _generate(layerDef), this); } }
this class manages the changes in layerdef styles and generate the proper cartocss and sql
_bind
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/style/style-manager.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/style/style-manager.js
BSD-3-Clause
function _unbind (layerDef) { if (layerDef.styleModel) { layerDef.styleModel.unbind('change', _generate(layerDef), this); layerDef.unbind('change:autoStyle', _generate(layerDef), this); } }
this class manages the changes in layerdef styles and generate the proper cartocss and sql
_unbind
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/style/style-manager.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/style/style-manager.js
BSD-3-Clause
function _bindAll () { this.layerDefinitionsCollection.each(_bind, this); }
this class manages the changes in layerdef styles and generate the proper cartocss and sql
_bindAll
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/style/style-manager.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/style/style-manager.js
BSD-3-Clause
F = function (querySchemaModel) { this._querySchemaModel = querySchemaModel; }
Object to generate column options for a current state of a query schema model
F
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/editor/widgets/widgets-form/widgets-form-column-options-factory.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/editor/widgets/widgets-form/widgets-form-column-options-factory.js
BSD-3-Clause
EmbedIntegrations = function (opts) { checkAndBuildOpts(opts, REQUIRED_OPTS, this); this._getWidgets().each(function (model) { this._bindWidgetChanges(model); }, this); LegendManager.trackLegends(this._getLayers()); }
Integration between embed view with cartodb.js and deep-insights.
EmbedIntegrations
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/embed/embed-integrations.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/embed/embed-integrations.js
BSD-3-Clause
function fetchModel (model) { return new Promise(function (resolve, reject) { var subscribeToFinalStatus = false; if (model.shouldFetch()) { model.fetch(); subscribeToFinalStatus = true; } else if (!model.isInFinalStatus()) { subscribeToFinalStatus = true; } else { resolve(); } if (subscribeToFinalStatus) { model.once('inFinalStatus', function () { resolve(); }); } }); }
Fetch all query objects (querySchemaModel, queryGeometryModel, queryRowsCollection) if necessary
fetchModel
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/fetch-all-query-objects.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/fetch-all-query-objects.js
BSD-3-Clause
GAPusher = function (opts) { var ga = window.ga; opts = opts || {}; if (ga) { ga(opts.eventName || 'send', { hitType: opts.hitType, eventCategory: opts.eventCategory, eventAction: opts.eventAction, eventLabel: opts.eventLabel }); } }
Send events to Google Analytics if it is available - https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits
GAPusher
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/ga-pusher.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/ga-pusher.js
BSD-3-Clause
MagicPositioner = function (params) { if (!params.parentView) throw new Error('parentView within params is required'); if (!_.isNumber(params.posX)) throw new Error('posX within params is required'); if (!_.isNumber(params.posY)) throw new Error('posY within params is required'); var $parentView = params.parentView; var parentViewHeight = $parentView.outerHeight(); var parentViewWidth = $parentView.outerWidth(); var posX = params.posX; var posY = params.posY; var offsetX = params.offsetX || 0; var offsetY = params.offsetY || 0; var elementWidth = params.elementWidth || MIN_WIDTH; var elementHeight = params.elementHeight || MIN_HEIGHT; var cssProps = DEFAULT_VALUES; if ((posX - elementWidth) > MIN_GAP) { cssProps.left = 'auto'; cssProps.right = (parentViewWidth - posX + offsetX) + 'px'; } else if ((posX + elementWidth) > elementWidth) { cssProps.right = 'auto'; cssProps.left = (posX + offsetX) + 'px'; } if ((posY + elementHeight) < parentViewHeight) { cssProps.bottom = 'auto'; cssProps.top = (posY + offsetY) + 'px'; } else if ((posY + elementHeight) > parentViewHeight) { cssProps.top = 'auto'; cssProps.bottom = (parentViewHeight - posY + offsetY) + 'px'; } return cssProps; }
Would you like to know where to open a context menu? Just provide: @param {Object} options.parentView Parent element view @param {Number} options.posX Position X of the context menu @param {Number} options.posY Position Y of the context menu @param {Number} options.elementWidth (optional) Context menu width @param {Number} options.elementHeight (optional) Context menu height @param {Number} options.offsetX (optional) Context menu offsetX @param {Number} options.offsetY (optional) Context menu offsetY By default, it will try to positionate to the right (inside) and to the top (below).
MagicPositioner
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/magic-positioner.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/magic-positioner.js
BSD-3-Clause
function isLinuxMiddleOrRightClick (ev) { return ev.which === 2 || ev.which === 3; }
Check if Linux user used right/middle click at the time of the event @param ev {Event} @returns {boolean}
isLinuxMiddleOrRightClick
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/navigate-through-router.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/navigate-through-router.js
BSD-3-Clause
function isMacCmdKeyPressed (ev) { return ev.metaKey; }
Check if Mac user used CMD key at the time of the event Mac user used CMD key at the time of the event. @param ev {Event} @returns {boolean}
isMacCmdKeyPressed
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/navigate-through-router.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/navigate-through-router.js
BSD-3-Clause
function isCtrlKeyPressed (ev) { return ev.ctrlKey; }
Check if Mac user used CMD key at the time of the event Mac user used CMD key at the time of the event. @param ev {Event} @returns {boolean}
isCtrlKeyPressed
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/navigate-through-router.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/navigate-through-router.js
BSD-3-Clause
function searchRecursiveByType (v, t) { var res = []; var i; var r; for (i in v) { if (v[i] instanceof t) { res.push(v[i]); } else if (typeof v[i] === 'object') { r = searchRecursiveByType(v[i], t); if (r.length) { res = res.concat(r); } } } return res; }
return the error list, empty if there were no errors
searchRecursiveByType
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/parser-css.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/parser-css.js
BSD-3-Clause
function searchRecursiveByType (v, t) { var res = []; var i; var r; for (i in v) { if (v[i] instanceof t) { res.push(v[i]); } else if (typeof v[i] === 'object') { r = searchRecursiveByType(v[i], t); if (r.length) { res = res.concat(r); } } } return res; }
return the error list, empty if there were no errors
searchRecursiveByType
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/parser-css.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/parser-css.js
BSD-3-Clause
method = function (self, rule) { var colors = self._colorsFromRule(rule); return _.map(colors, function (color) { return color.rgb; }); }
return a list of colors used in cartocss
method
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/parser-css.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/parser-css.js
BSD-3-Clause
method = function (self, rule) { var imageFillRule = rules['image-filters']; var colors = self._colorsFromRule(imageFillRule); return _.map(colors, function (f) { return f.rgb; }); }
return a list of colors used in cartocss
method
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/parser-css.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/parser-css.js
BSD-3-Clause
method = function (self, rule) { return _.map(self._varsFromRule(rule), function (f) { return f.value; }); }
return a list of variables used in cartocss
method
javascript
CartoDB/cartodb
lib/assets/javascripts/builder/helpers/parser-css.js
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/builder/helpers/parser-css.js
BSD-3-Clause