id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
7,600 | segmentio/analytics.js | analytics.js | toCamelCase | function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
} | javascript | function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
} | [
"function",
"toCamelCase",
"(",
"string",
")",
"{",
"return",
"toSpace",
"(",
"string",
")",
".",
"replace",
"(",
"/",
"\\s(\\w)",
"/",
"g",
",",
"function",
"(",
"matches",
",",
"letter",
")",
"{",
"return",
"letter",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
";",
"}"
] | Convert a `string` to camel case.
@param {String} string
@return {String} | [
"Convert",
"a",
"string",
"to",
"camel",
"case",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L12734-L12738 |
7,601 | segmentio/analytics.js | analytics.js | path | function path(properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
} | javascript | function path(properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
} | [
"function",
"path",
"(",
"properties",
",",
"options",
")",
"{",
"if",
"(",
"!",
"properties",
")",
"return",
";",
"var",
"str",
"=",
"properties",
".",
"path",
";",
"if",
"(",
"options",
".",
"includeSearch",
"&&",
"properties",
".",
"search",
")",
"str",
"+=",
"properties",
".",
"search",
";",
"return",
"str",
";",
"}"
] | Return the path based on `properties` and `options`.
@param {Object} properties
@param {Object} options
@return {string|undefined} | [
"Return",
"the",
"path",
"based",
"on",
"properties",
"and",
"options",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L13320-L13325 |
7,602 | segmentio/analytics.js | analytics.js | metrics | function metrics(obj, data) {
var dimensions = data.dimensions;
var metrics = data.metrics;
var names = keys(metrics).concat(keys(dimensions));
var ret = {};
for (var i = 0; i < names.length; ++i) {
var name = names[i];
var key = metrics[name] || dimensions[name];
var value = dot(obj, name) || obj[name];
if (value == null) continue;
ret[key] = value;
}
return ret;
} | javascript | function metrics(obj, data) {
var dimensions = data.dimensions;
var metrics = data.metrics;
var names = keys(metrics).concat(keys(dimensions));
var ret = {};
for (var i = 0; i < names.length; ++i) {
var name = names[i];
var key = metrics[name] || dimensions[name];
var value = dot(obj, name) || obj[name];
if (value == null) continue;
ret[key] = value;
}
return ret;
} | [
"function",
"metrics",
"(",
"obj",
",",
"data",
")",
"{",
"var",
"dimensions",
"=",
"data",
".",
"dimensions",
";",
"var",
"metrics",
"=",
"data",
".",
"metrics",
";",
"var",
"names",
"=",
"keys",
"(",
"metrics",
")",
".",
"concat",
"(",
"keys",
"(",
"dimensions",
")",
")",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"names",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"name",
"=",
"names",
"[",
"i",
"]",
";",
"var",
"key",
"=",
"metrics",
"[",
"name",
"]",
"||",
"dimensions",
"[",
"name",
"]",
";",
"var",
"value",
"=",
"dot",
"(",
"obj",
",",
"name",
")",
"||",
"obj",
"[",
"name",
"]",
";",
"if",
"(",
"value",
"==",
"null",
")",
"continue",
";",
"ret",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"return",
"ret",
";",
"}"
] | Map google's custom dimensions & metrics with `obj`.
Example:
metrics({ revenue: 1.9 }, { { metrics : { revenue: 'metric8' } });
// => { metric8: 1.9 }
metrics({ revenue: 1.9 }, {});
// => {}
@param {Object} obj
@param {Object} data
@return {Object|null}
@api private | [
"Map",
"google",
"s",
"custom",
"dimensions",
"&",
"metrics",
"with",
"obj",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L13356-L13371 |
7,603 | segmentio/analytics.js | analytics.js | enhancedEcommerceTrackProduct | function enhancedEcommerceTrackProduct(track) {
var props = track.properties();
window.ga('ec:addProduct', {
id: track.id() || track.sku(),
name: track.name(),
category: track.category(),
quantity: track.quantity(),
price: track.price(),
brand: props.brand,
variant: props.variant,
currency: track.currency()
});
} | javascript | function enhancedEcommerceTrackProduct(track) {
var props = track.properties();
window.ga('ec:addProduct', {
id: track.id() || track.sku(),
name: track.name(),
category: track.category(),
quantity: track.quantity(),
price: track.price(),
brand: props.brand,
variant: props.variant,
currency: track.currency()
});
} | [
"function",
"enhancedEcommerceTrackProduct",
"(",
"track",
")",
"{",
"var",
"props",
"=",
"track",
".",
"properties",
"(",
")",
";",
"window",
".",
"ga",
"(",
"'ec:addProduct'",
",",
"{",
"id",
":",
"track",
".",
"id",
"(",
")",
"||",
"track",
".",
"sku",
"(",
")",
",",
"name",
":",
"track",
".",
"name",
"(",
")",
",",
"category",
":",
"track",
".",
"category",
"(",
")",
",",
"quantity",
":",
"track",
".",
"quantity",
"(",
")",
",",
"price",
":",
"track",
".",
"price",
"(",
")",
",",
"brand",
":",
"props",
".",
"brand",
",",
"variant",
":",
"props",
".",
"variant",
",",
"currency",
":",
"track",
".",
"currency",
"(",
")",
"}",
")",
";",
"}"
] | Enhanced ecommerce track product.
Simple helper so that we don't repeat `ec:addProduct` everywhere.
@api private
@param {Track} track | [
"Enhanced",
"ecommerce",
"track",
"product",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L13674-L13687 |
7,604 | segmentio/analytics.js | analytics.js | enhancedEcommerceProductAction | function enhancedEcommerceProductAction(track, action, data) {
enhancedEcommerceTrackProduct(track);
window.ga('ec:setAction', action, data || {});
} | javascript | function enhancedEcommerceProductAction(track, action, data) {
enhancedEcommerceTrackProduct(track);
window.ga('ec:setAction', action, data || {});
} | [
"function",
"enhancedEcommerceProductAction",
"(",
"track",
",",
"action",
",",
"data",
")",
"{",
"enhancedEcommerceTrackProduct",
"(",
"track",
")",
";",
"window",
".",
"ga",
"(",
"'ec:setAction'",
",",
"action",
",",
"data",
"||",
"{",
"}",
")",
";",
"}"
] | Set `action` on `track` with `data`.
@api private
@param {Track} track
@param {String} action
@param {Object} data | [
"Set",
"action",
"on",
"track",
"with",
"data",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L13698-L13701 |
7,605 | segmentio/analytics.js | analytics.js | extractCheckoutOptions | function extractCheckoutOptions(props) {
var options = [
props.paymentMethod,
props.shippingMethod
];
// Remove all nulls, empty strings, zeroes, and join with commas.
var valid = select(options, function(e) {return e; });
return valid.length > 0 ? valid.join(', ') : null;
} | javascript | function extractCheckoutOptions(props) {
var options = [
props.paymentMethod,
props.shippingMethod
];
// Remove all nulls, empty strings, zeroes, and join with commas.
var valid = select(options, function(e) {return e; });
return valid.length > 0 ? valid.join(', ') : null;
} | [
"function",
"extractCheckoutOptions",
"(",
"props",
")",
"{",
"var",
"options",
"=",
"[",
"props",
".",
"paymentMethod",
",",
"props",
".",
"shippingMethod",
"]",
";",
"// Remove all nulls, empty strings, zeroes, and join with commas.",
"var",
"valid",
"=",
"select",
"(",
"options",
",",
"function",
"(",
"e",
")",
"{",
"return",
"e",
";",
"}",
")",
";",
"return",
"valid",
".",
"length",
">",
"0",
"?",
"valid",
".",
"join",
"(",
"', '",
")",
":",
"null",
";",
"}"
] | Extracts checkout options.
@api private
@param {Object} props
@return {string|null} | [
"Extracts",
"checkout",
"options",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L13711-L13720 |
7,606 | segmentio/analytics.js | analytics.js | createProductTrack | function createProductTrack(track, properties) {
properties.currency = properties.currency || track.currency();
return new Track({ properties: properties });
} | javascript | function createProductTrack(track, properties) {
properties.currency = properties.currency || track.currency();
return new Track({ properties: properties });
} | [
"function",
"createProductTrack",
"(",
"track",
",",
"properties",
")",
"{",
"properties",
".",
"currency",
"=",
"properties",
".",
"currency",
"||",
"track",
".",
"currency",
"(",
")",
";",
"return",
"new",
"Track",
"(",
"{",
"properties",
":",
"properties",
"}",
")",
";",
"}"
] | Creates a track out of product properties.
@api private
@param {Track} track
@param {Object} properties
@return {Track} | [
"Creates",
"a",
"track",
"out",
"of",
"product",
"properties",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L13731-L13734 |
7,607 | segmentio/analytics.js | analytics.js | push | function push() {
window._gs = window._gs || function() {
window._gs.q.push(arguments);
};
window._gs.q = window._gs.q || [];
window._gs.apply(null, arguments);
} | javascript | function push() {
window._gs = window._gs || function() {
window._gs.q.push(arguments);
};
window._gs.q = window._gs.q || [];
window._gs.apply(null, arguments);
} | [
"function",
"push",
"(",
")",
"{",
"window",
".",
"_gs",
"=",
"window",
".",
"_gs",
"||",
"function",
"(",
")",
"{",
"window",
".",
"_gs",
".",
"q",
".",
"push",
"(",
"arguments",
")",
";",
"}",
";",
"window",
".",
"_gs",
".",
"q",
"=",
"window",
".",
"_gs",
".",
"q",
"||",
"[",
"]",
";",
"window",
".",
"_gs",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"}"
] | Push to `_gs.q`.
@api private
@param {...*} args | [
"Push",
"to",
"_gs",
".",
"q",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L14041-L14047 |
7,608 | segmentio/analytics.js | analytics.js | omit | function omit(keys, object){
var ret = {};
for (var item in object) {
ret[item] = object[item];
}
for (var i = 0; i < keys.length; i++) {
delete ret[keys[i]];
}
return ret;
} | javascript | function omit(keys, object){
var ret = {};
for (var item in object) {
ret[item] = object[item];
}
for (var i = 0; i < keys.length; i++) {
delete ret[keys[i]];
}
return ret;
} | [
"function",
"omit",
"(",
"keys",
",",
"object",
")",
"{",
"var",
"ret",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"item",
"in",
"object",
")",
"{",
"ret",
"[",
"item",
"]",
"=",
"object",
"[",
"item",
"]",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"delete",
"ret",
"[",
"keys",
"[",
"i",
"]",
"]",
";",
"}",
"return",
"ret",
";",
"}"
] | Return a copy of the object without the specified keys.
@param {Array} keys
@param {Object} object
@return {Object} | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"without",
"the",
"specified",
"keys",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L14065-L14076 |
7,609 | segmentio/analytics.js | analytics.js | pick | function pick(obj){
var keys = [].slice.call(arguments, 1);
var ret = {};
for (var i = 0, key; key = keys[i]; i++) {
if (key in obj) ret[key] = obj[key];
}
return ret;
} | javascript | function pick(obj){
var keys = [].slice.call(arguments, 1);
var ret = {};
for (var i = 0, key; key = keys[i]; i++) {
if (key in obj) ret[key] = obj[key];
}
return ret;
} | [
"function",
"pick",
"(",
"obj",
")",
"{",
"var",
"keys",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"key",
";",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"i",
"++",
")",
"{",
"if",
"(",
"key",
"in",
"obj",
")",
"ret",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
"return",
"ret",
";",
"}"
] | Pick keys from an `obj`.
@param {Object} obj
@param {Strings} keys...
@return {Object} | [
"Pick",
"keys",
"from",
"an",
"obj",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L14094-L14103 |
7,610 | segmentio/analytics.js | analytics.js | prefix | function prefix(event, properties) {
var prefixed = {};
each(properties, function(key, val) {
if (key === 'Billing Amount') {
prefixed[key] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
} | javascript | function prefix(event, properties) {
var prefixed = {};
each(properties, function(key, val) {
if (key === 'Billing Amount') {
prefixed[key] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
} | [
"function",
"prefix",
"(",
"event",
",",
"properties",
")",
"{",
"var",
"prefixed",
"=",
"{",
"}",
";",
"each",
"(",
"properties",
",",
"function",
"(",
"key",
",",
"val",
")",
"{",
"if",
"(",
"key",
"===",
"'Billing Amount'",
")",
"{",
"prefixed",
"[",
"key",
"]",
"=",
"val",
";",
"}",
"else",
"{",
"prefixed",
"[",
"event",
"+",
"' - '",
"+",
"key",
"]",
"=",
"val",
";",
"}",
"}",
")",
";",
"return",
"prefixed",
";",
"}"
] | Prefix properties with the event name.
@param {String} event
@param {Object} properties
@return {Object} prefixed
@api private | [
"Prefix",
"properties",
"with",
"the",
"event",
"name",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L15282-L15292 |
7,611 | segmentio/analytics.js | analytics.js | convert | function convert(traits) {
var arr = [];
each(traits, function(key, value) {
arr.push({ name: key, value: value });
});
return arr;
} | javascript | function convert(traits) {
var arr = [];
each(traits, function(key, value) {
arr.push({ name: key, value: value });
});
return arr;
} | [
"function",
"convert",
"(",
"traits",
")",
"{",
"var",
"arr",
"=",
"[",
"]",
";",
"each",
"(",
"traits",
",",
"function",
"(",
"key",
",",
"value",
")",
"{",
"arr",
".",
"push",
"(",
"{",
"name",
":",
"key",
",",
"value",
":",
"value",
"}",
")",
";",
"}",
")",
";",
"return",
"arr",
";",
"}"
] | Convert a traits object into the format LiveChat requires.
@param {Object} traits
@return {Array} | [
"Convert",
"a",
"traits",
"object",
"into",
"the",
"format",
"LiveChat",
"requires",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L15533-L15539 |
7,612 | segmentio/analytics.js | analytics.js | lowercase | function lowercase(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < arr.length; ++i) {
ret[i] = String(arr[i]).toLowerCase();
}
return ret;
} | javascript | function lowercase(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < arr.length; ++i) {
ret[i] = String(arr[i]).toLowerCase();
}
return ret;
} | [
"function",
"lowercase",
"(",
"arr",
")",
"{",
"var",
"ret",
"=",
"new",
"Array",
"(",
"arr",
".",
"length",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"++",
"i",
")",
"{",
"ret",
"[",
"i",
"]",
"=",
"String",
"(",
"arr",
"[",
"i",
"]",
")",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Lowercase the given `arr`.
@api private
@param {Array} arr
@return {Array} | [
"Lowercase",
"the",
"given",
"arr",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L15932-L15940 |
7,613 | segmentio/analytics.js | analytics.js | ads | function ads(query){
var params = parse(query);
for (var key in params) {
for (var id in QUERYIDS) {
if (key === id) {
return {
id : params[key],
type : QUERYIDS[id]
};
}
}
}
} | javascript | function ads(query){
var params = parse(query);
for (var key in params) {
for (var id in QUERYIDS) {
if (key === id) {
return {
id : params[key],
type : QUERYIDS[id]
};
}
}
}
} | [
"function",
"ads",
"(",
"query",
")",
"{",
"var",
"params",
"=",
"parse",
"(",
"query",
")",
";",
"for",
"(",
"var",
"key",
"in",
"params",
")",
"{",
"for",
"(",
"var",
"id",
"in",
"QUERYIDS",
")",
"{",
"if",
"(",
"key",
"===",
"id",
")",
"{",
"return",
"{",
"id",
":",
"params",
"[",
"key",
"]",
",",
"type",
":",
"QUERYIDS",
"[",
"id",
"]",
"}",
";",
"}",
"}",
"}",
"}"
] | Get all ads info from the given `querystring`
@param {String} query
@return {Object}
@api private | [
"Get",
"all",
"ads",
"info",
"from",
"the",
"given",
"querystring"
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L18200-L18212 |
7,614 | segmentio/analytics.js | analytics.js | store | function store(key, value){
var length = arguments.length;
if (0 == length) return all();
if (2 <= length) return set(key, value);
if (1 != length) return;
if (null == key) return storage.clear();
if ('string' == typeof key) return get(key);
if ('object' == typeof key) return each(key, set);
} | javascript | function store(key, value){
var length = arguments.length;
if (0 == length) return all();
if (2 <= length) return set(key, value);
if (1 != length) return;
if (null == key) return storage.clear();
if ('string' == typeof key) return get(key);
if ('object' == typeof key) return each(key, set);
} | [
"function",
"store",
"(",
"key",
",",
"value",
")",
"{",
"var",
"length",
"=",
"arguments",
".",
"length",
";",
"if",
"(",
"0",
"==",
"length",
")",
"return",
"all",
"(",
")",
";",
"if",
"(",
"2",
"<=",
"length",
")",
"return",
"set",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"1",
"!=",
"length",
")",
"return",
";",
"if",
"(",
"null",
"==",
"key",
")",
"return",
"storage",
".",
"clear",
"(",
")",
";",
"if",
"(",
"'string'",
"==",
"typeof",
"key",
")",
"return",
"get",
"(",
"key",
")",
";",
"if",
"(",
"'object'",
"==",
"typeof",
"key",
")",
"return",
"each",
"(",
"key",
",",
"set",
")",
";",
"}"
] | Store the given `key`, `val`.
@param {String|Object} key
@param {Mixed} value
@return {Mixed}
@api public | [
"Store",
"the",
"given",
"key",
"val",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L18250-L18258 |
7,615 | segmentio/analytics.js | analytics.js | set | function set(key, val){
return null == val
? storage.removeItem(key)
: storage.setItem(key, JSON.stringify(val));
} | javascript | function set(key, val){
return null == val
? storage.removeItem(key)
: storage.setItem(key, JSON.stringify(val));
} | [
"function",
"set",
"(",
"key",
",",
"val",
")",
"{",
"return",
"null",
"==",
"val",
"?",
"storage",
".",
"removeItem",
"(",
"key",
")",
":",
"storage",
".",
"setItem",
"(",
"key",
",",
"JSON",
".",
"stringify",
"(",
"val",
")",
")",
";",
"}"
] | Set `key` to `val`.
@param {String} key
@param {Mixed} val | [
"Set",
"key",
"to",
"val",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L18273-L18277 |
7,616 | segmentio/analytics.js | analytics.js | all | function all(){
var len = storage.length;
var ret = {};
var key;
while (0 <= --len) {
key = storage.key(len);
ret[key] = get(key);
}
return ret;
} | javascript | function all(){
var len = storage.length;
var ret = {};
var key;
while (0 <= --len) {
key = storage.key(len);
ret[key] = get(key);
}
return ret;
} | [
"function",
"all",
"(",
")",
"{",
"var",
"len",
"=",
"storage",
".",
"length",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"var",
"key",
";",
"while",
"(",
"0",
"<=",
"--",
"len",
")",
"{",
"key",
"=",
"storage",
".",
"key",
"(",
"len",
")",
";",
"ret",
"[",
"key",
"]",
"=",
"get",
"(",
"key",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Get all.
@return {Object} | [
"Get",
"all",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L18296-L18307 |
7,617 | segmentio/analytics.js | analytics.js | set | function set (protocol) {
try {
define(window.location, 'protocol', {
get: function () { return protocol; }
});
} catch (err) {
mockedProtocol = protocol;
}
} | javascript | function set (protocol) {
try {
define(window.location, 'protocol', {
get: function () { return protocol; }
});
} catch (err) {
mockedProtocol = protocol;
}
} | [
"function",
"set",
"(",
"protocol",
")",
"{",
"try",
"{",
"define",
"(",
"window",
".",
"location",
",",
"'protocol'",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"protocol",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"mockedProtocol",
"=",
"protocol",
";",
"}",
"}"
] | Sets the protocol
@param {String} protocol | [
"Sets",
"the",
"protocol"
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L18400-L18408 |
7,618 | segmentio/analytics.js | analytics.js | formatOptions | function formatOptions(options) {
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position',
screenshotEnabled: 'screenshot_enabled',
customTicketFields: 'ticket_custom_fields'
});
} | javascript | function formatOptions(options) {
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position',
screenshotEnabled: 'screenshot_enabled',
customTicketFields: 'ticket_custom_fields'
});
} | [
"function",
"formatOptions",
"(",
"options",
")",
"{",
"return",
"alias",
"(",
"options",
",",
"{",
"forumId",
":",
"'forum_id'",
",",
"accentColor",
":",
"'accent_color'",
",",
"smartvote",
":",
"'smartvote_enabled'",
",",
"triggerColor",
":",
"'trigger_color'",
",",
"triggerBackgroundColor",
":",
"'trigger_background_color'",
",",
"triggerPosition",
":",
"'trigger_position'",
",",
"screenshotEnabled",
":",
"'screenshot_enabled'",
",",
"customTicketFields",
":",
"'ticket_custom_fields'",
"}",
")",
";",
"}"
] | Format the options for UserVoice.
@api private
@param {Object} options
@return {Object} | [
"Format",
"the",
"options",
"for",
"UserVoice",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L19716-L19727 |
7,619 | segmentio/analytics.js | analytics.js | formatClassicOptions | function formatClassicOptions(options) {
return alias(options, {
forumId: 'forum_id',
classicMode: 'mode',
primaryColor: 'primary_color',
tabPosition: 'tab_position',
tabColor: 'tab_color',
linkColor: 'link_color',
defaultMode: 'default_mode',
tabLabel: 'tab_label',
tabInverted: 'tab_inverted'
});
} | javascript | function formatClassicOptions(options) {
return alias(options, {
forumId: 'forum_id',
classicMode: 'mode',
primaryColor: 'primary_color',
tabPosition: 'tab_position',
tabColor: 'tab_color',
linkColor: 'link_color',
defaultMode: 'default_mode',
tabLabel: 'tab_label',
tabInverted: 'tab_inverted'
});
} | [
"function",
"formatClassicOptions",
"(",
"options",
")",
"{",
"return",
"alias",
"(",
"options",
",",
"{",
"forumId",
":",
"'forum_id'",
",",
"classicMode",
":",
"'mode'",
",",
"primaryColor",
":",
"'primary_color'",
",",
"tabPosition",
":",
"'tab_position'",
",",
"tabColor",
":",
"'tab_color'",
",",
"linkColor",
":",
"'link_color'",
",",
"defaultMode",
":",
"'default_mode'",
",",
"tabLabel",
":",
"'tab_label'",
",",
"tabInverted",
":",
"'tab_inverted'",
"}",
")",
";",
"}"
] | Format the classic options for UserVoice.
@api private
@param {Object} options
@return {Object} | [
"Format",
"the",
"classic",
"options",
"for",
"UserVoice",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L19737-L19749 |
7,620 | segmentio/analytics.js | analytics.js | enqueue | function enqueue(fn) {
window._vis_opt_queue = window._vis_opt_queue || [];
window._vis_opt_queue.push(fn);
} | javascript | function enqueue(fn) {
window._vis_opt_queue = window._vis_opt_queue || [];
window._vis_opt_queue.push(fn);
} | [
"function",
"enqueue",
"(",
"fn",
")",
"{",
"window",
".",
"_vis_opt_queue",
"=",
"window",
".",
"_vis_opt_queue",
"||",
"[",
"]",
";",
"window",
".",
"_vis_opt_queue",
".",
"push",
"(",
"fn",
")",
";",
"}"
] | Add a `fn` to the VWO queue, creating one if it doesn't exist.
@param {Function} fn | [
"Add",
"a",
"fn",
"to",
"the",
"VWO",
"queue",
"creating",
"one",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L20060-L20063 |
7,621 | segmentio/analytics.js | analytics.js | variation | function variation(id) {
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
} | javascript | function variation(id) {
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
} | [
"function",
"variation",
"(",
"id",
")",
"{",
"var",
"experiments",
"=",
"window",
".",
"_vwo_exp",
";",
"if",
"(",
"!",
"experiments",
")",
"return",
"null",
";",
"var",
"experiment",
"=",
"experiments",
"[",
"id",
"]",
";",
"var",
"variationId",
"=",
"experiment",
".",
"combination_chosen",
";",
"return",
"variationId",
"?",
"experiment",
".",
"comb_n",
"[",
"variationId",
"]",
":",
"null",
";",
"}"
] | Get the chosen variation's name from an experiment `id`.
http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
@param {String} id
@return {String} | [
"Get",
"the",
"chosen",
"variation",
"s",
"name",
"from",
"an",
"experiment",
"id",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L20074-L20080 |
7,622 | segmentio/analytics.js | analytics.js | push | function push(callback) {
window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || [];
window.yandex_metrika_callbacks.push(callback);
} | javascript | function push(callback) {
window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || [];
window.yandex_metrika_callbacks.push(callback);
} | [
"function",
"push",
"(",
"callback",
")",
"{",
"window",
".",
"yandex_metrika_callbacks",
"=",
"window",
".",
"yandex_metrika_callbacks",
"||",
"[",
"]",
";",
"window",
".",
"yandex_metrika_callbacks",
".",
"push",
"(",
"callback",
")",
";",
"}"
] | Push a new callback on the global Yandex queue.
@api private
@param {Function} callback | [
"Push",
"a",
"new",
"callback",
"on",
"the",
"global",
"Yandex",
"queue",
"."
] | 077efafa234d0bb4374169adb4e1ff71da39af8f | https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L20405-L20408 |
7,623 | expressjs/compression | index.js | chunkLength | function chunkLength (chunk, encoding) {
if (!chunk) {
return 0
}
return !Buffer.isBuffer(chunk)
? Buffer.byteLength(chunk, encoding)
: chunk.length
} | javascript | function chunkLength (chunk, encoding) {
if (!chunk) {
return 0
}
return !Buffer.isBuffer(chunk)
? Buffer.byteLength(chunk, encoding)
: chunk.length
} | [
"function",
"chunkLength",
"(",
"chunk",
",",
"encoding",
")",
"{",
"if",
"(",
"!",
"chunk",
")",
"{",
"return",
"0",
"}",
"return",
"!",
"Buffer",
".",
"isBuffer",
"(",
"chunk",
")",
"?",
"Buffer",
".",
"byteLength",
"(",
"chunk",
",",
"encoding",
")",
":",
"chunk",
".",
"length",
"}"
] | Get the length of a given chunk | [
"Get",
"the",
"length",
"of",
"a",
"given",
"chunk"
] | dd5055dc92fdeacad706972c4fcf3a7ff10066ef | https://github.com/expressjs/compression/blob/dd5055dc92fdeacad706972c4fcf3a7ff10066ef/index.js#L239-L247 |
7,624 | expressjs/compression | index.js | shouldCompress | function shouldCompress (req, res) {
var type = res.getHeader('Content-Type')
if (type === undefined || !compressible(type)) {
debug('%s not compressible', type)
return false
}
return true
} | javascript | function shouldCompress (req, res) {
var type = res.getHeader('Content-Type')
if (type === undefined || !compressible(type)) {
debug('%s not compressible', type)
return false
}
return true
} | [
"function",
"shouldCompress",
"(",
"req",
",",
"res",
")",
"{",
"var",
"type",
"=",
"res",
".",
"getHeader",
"(",
"'Content-Type'",
")",
"if",
"(",
"type",
"===",
"undefined",
"||",
"!",
"compressible",
"(",
"type",
")",
")",
"{",
"debug",
"(",
"'%s not compressible'",
",",
"type",
")",
"return",
"false",
"}",
"return",
"true",
"}"
] | Default filter function.
@private | [
"Default",
"filter",
"function",
"."
] | dd5055dc92fdeacad706972c4fcf3a7ff10066ef | https://github.com/expressjs/compression/blob/dd5055dc92fdeacad706972c4fcf3a7ff10066ef/index.js#L254-L263 |
7,625 | expressjs/compression | index.js | shouldTransform | function shouldTransform (req, res) {
var cacheControl = res.getHeader('Cache-Control')
// Don't compress for Cache-Control: no-transform
// https://tools.ietf.org/html/rfc7234#section-5.2.2.4
return !cacheControl ||
!cacheControlNoTransformRegExp.test(cacheControl)
} | javascript | function shouldTransform (req, res) {
var cacheControl = res.getHeader('Cache-Control')
// Don't compress for Cache-Control: no-transform
// https://tools.ietf.org/html/rfc7234#section-5.2.2.4
return !cacheControl ||
!cacheControlNoTransformRegExp.test(cacheControl)
} | [
"function",
"shouldTransform",
"(",
"req",
",",
"res",
")",
"{",
"var",
"cacheControl",
"=",
"res",
".",
"getHeader",
"(",
"'Cache-Control'",
")",
"// Don't compress for Cache-Control: no-transform",
"// https://tools.ietf.org/html/rfc7234#section-5.2.2.4",
"return",
"!",
"cacheControl",
"||",
"!",
"cacheControlNoTransformRegExp",
".",
"test",
"(",
"cacheControl",
")",
"}"
] | Determine if the entity should be transformed.
@private | [
"Determine",
"if",
"the",
"entity",
"should",
"be",
"transformed",
"."
] | dd5055dc92fdeacad706972c4fcf3a7ff10066ef | https://github.com/expressjs/compression/blob/dd5055dc92fdeacad706972c4fcf3a7ff10066ef/index.js#L270-L277 |
7,626 | expressjs/compression | index.js | toBuffer | function toBuffer (chunk, encoding) {
return !Buffer.isBuffer(chunk)
? Buffer.from(chunk, encoding)
: chunk
} | javascript | function toBuffer (chunk, encoding) {
return !Buffer.isBuffer(chunk)
? Buffer.from(chunk, encoding)
: chunk
} | [
"function",
"toBuffer",
"(",
"chunk",
",",
"encoding",
")",
"{",
"return",
"!",
"Buffer",
".",
"isBuffer",
"(",
"chunk",
")",
"?",
"Buffer",
".",
"from",
"(",
"chunk",
",",
"encoding",
")",
":",
"chunk",
"}"
] | Coerce arguments to Buffer
@private | [
"Coerce",
"arguments",
"to",
"Buffer"
] | dd5055dc92fdeacad706972c4fcf3a7ff10066ef | https://github.com/expressjs/compression/blob/dd5055dc92fdeacad706972c4fcf3a7ff10066ef/index.js#L284-L288 |
7,627 | zeit/styled-jsx | src/lib/style-transform.js | transform | function transform(hash, styles, settings = {}) {
generator = settings.generator
offset = settings.offset
filename = settings.filename
splitRules = []
stylis.set({
prefix:
typeof settings.vendorPrefixes === 'boolean'
? settings.vendorPrefixes
: true
})
stylis(hash, styles)
if (settings.splitRules) {
return splitRules
}
return splitRules.join('')
} | javascript | function transform(hash, styles, settings = {}) {
generator = settings.generator
offset = settings.offset
filename = settings.filename
splitRules = []
stylis.set({
prefix:
typeof settings.vendorPrefixes === 'boolean'
? settings.vendorPrefixes
: true
})
stylis(hash, styles)
if (settings.splitRules) {
return splitRules
}
return splitRules.join('')
} | [
"function",
"transform",
"(",
"hash",
",",
"styles",
",",
"settings",
"=",
"{",
"}",
")",
"{",
"generator",
"=",
"settings",
".",
"generator",
"offset",
"=",
"settings",
".",
"offset",
"filename",
"=",
"settings",
".",
"filename",
"splitRules",
"=",
"[",
"]",
"stylis",
".",
"set",
"(",
"{",
"prefix",
":",
"typeof",
"settings",
".",
"vendorPrefixes",
"===",
"'boolean'",
"?",
"settings",
".",
"vendorPrefixes",
":",
"true",
"}",
")",
"stylis",
"(",
"hash",
",",
"styles",
")",
"if",
"(",
"settings",
".",
"splitRules",
")",
"{",
"return",
"splitRules",
"}",
"return",
"splitRules",
".",
"join",
"(",
"''",
")",
"}"
] | Public transform function
@param {String} hash
@param {String} styles
@param {Object} settings
@return {string} | [
"Public",
"transform",
"function"
] | 00fcb7bcad9c8af91167056f93c63858d24769ba | https://github.com/zeit/styled-jsx/blob/00fcb7bcad9c8af91167056f93c63858d24769ba/src/lib/style-transform.js#L96-L116 |
7,628 | HubSpot/vex | src/vex.js | addClasses | function addClasses (el, classStr) {
if (typeof classStr !== 'string' || classStr.length === 0) {
return
}
var classes = classStr.split(' ')
for (var i = 0; i < classes.length; i++) {
var className = classes[i]
if (className.length) {
el.classList.add(className)
}
}
} | javascript | function addClasses (el, classStr) {
if (typeof classStr !== 'string' || classStr.length === 0) {
return
}
var classes = classStr.split(' ')
for (var i = 0; i < classes.length; i++) {
var className = classes[i]
if (className.length) {
el.classList.add(className)
}
}
} | [
"function",
"addClasses",
"(",
"el",
",",
"classStr",
")",
"{",
"if",
"(",
"typeof",
"classStr",
"!==",
"'string'",
"||",
"classStr",
".",
"length",
"===",
"0",
")",
"{",
"return",
"}",
"var",
"classes",
"=",
"classStr",
".",
"split",
"(",
"' '",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"classes",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"className",
"=",
"classes",
"[",
"i",
"]",
"if",
"(",
"className",
".",
"length",
")",
"{",
"el",
".",
"classList",
".",
"add",
"(",
"className",
")",
"}",
"}",
"}"
] | Utility function to add space-delimited class strings to a DOM element's classList | [
"Utility",
"function",
"to",
"add",
"space",
"-",
"delimited",
"class",
"strings",
"to",
"a",
"DOM",
"element",
"s",
"classList"
] | 0df3f63db5eebee09d284feec0895dc723e95514 | https://github.com/HubSpot/vex/blob/0df3f63db5eebee09d284feec0895dc723e95514/src/vex.js#L21-L32 |
7,629 | HubSpot/vex | src/vex.js | close | function close (vexOrId) {
var id
if (vexOrId.id) {
id = vexOrId.id
} else if (typeof vexOrId === 'string') {
id = vexOrId
} else {
throw new TypeError('close requires a vex object or id string')
}
if (!vexes[id]) {
return false
}
return vexes[id].close()
} | javascript | function close (vexOrId) {
var id
if (vexOrId.id) {
id = vexOrId.id
} else if (typeof vexOrId === 'string') {
id = vexOrId
} else {
throw new TypeError('close requires a vex object or id string')
}
if (!vexes[id]) {
return false
}
return vexes[id].close()
} | [
"function",
"close",
"(",
"vexOrId",
")",
"{",
"var",
"id",
"if",
"(",
"vexOrId",
".",
"id",
")",
"{",
"id",
"=",
"vexOrId",
".",
"id",
"}",
"else",
"if",
"(",
"typeof",
"vexOrId",
"===",
"'string'",
")",
"{",
"id",
"=",
"vexOrId",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"'close requires a vex object or id string'",
")",
"}",
"if",
"(",
"!",
"vexes",
"[",
"id",
"]",
")",
"{",
"return",
"false",
"}",
"return",
"vexes",
"[",
"id",
"]",
".",
"close",
"(",
")",
"}"
] | A top-level vex.close function to close dialogs by reference or id | [
"A",
"top",
"-",
"level",
"vex",
".",
"close",
"function",
"to",
"close",
"dialogs",
"by",
"reference",
"or",
"id"
] | 0df3f63db5eebee09d284feec0895dc723e95514 | https://github.com/HubSpot/vex/blob/0df3f63db5eebee09d284feec0895dc723e95514/src/vex.js#L253-L266 |
7,630 | algolia/instantsearch.js | scripts/release/publish.js | rollback | function rollback(newVersion) {
if (strategy === 'stable') {
// reset master
shell.exec('git reset --hard origin/master');
shell.exec('git checkout develop');
} else {
// remove last commit
shell.exec('git reset --hard HEAD~1');
}
// remove local created tag
shell.exec(`git tag -d v${newVersion}`);
process.exit(1);
} | javascript | function rollback(newVersion) {
if (strategy === 'stable') {
// reset master
shell.exec('git reset --hard origin/master');
shell.exec('git checkout develop');
} else {
// remove last commit
shell.exec('git reset --hard HEAD~1');
}
// remove local created tag
shell.exec(`git tag -d v${newVersion}`);
process.exit(1);
} | [
"function",
"rollback",
"(",
"newVersion",
")",
"{",
"if",
"(",
"strategy",
"===",
"'stable'",
")",
"{",
"// reset master",
"shell",
".",
"exec",
"(",
"'git reset --hard origin/master'",
")",
";",
"shell",
".",
"exec",
"(",
"'git checkout develop'",
")",
";",
"}",
"else",
"{",
"// remove last commit",
"shell",
".",
"exec",
"(",
"'git reset --hard HEAD~1'",
")",
";",
"}",
"// remove local created tag",
"shell",
".",
"exec",
"(",
"`",
"${",
"newVersion",
"}",
"`",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}"
] | called if process aborted before publish, nothing is pushed nor published remove local changes | [
"called",
"if",
"process",
"aborted",
"before",
"publish",
"nothing",
"is",
"pushed",
"nor",
"published",
"remove",
"local",
"changes"
] | adf8220064dd46b5b6d6b06ef0e858bf476f219b | https://github.com/algolia/instantsearch.js/blob/adf8220064dd46b5b6d6b06ef0e858bf476f219b/scripts/release/publish.js#L78-L91 |
7,631 | algolia/instantsearch.js | src/widgets/refinement-list/refinement-list.js | transformTemplates | function transformTemplates(templates) {
const allTemplates = {
...templates,
submit: templates.searchableSubmit,
reset: templates.searchableReset,
loadingIndicator: templates.searchableLoadingIndicator,
};
const {
searchableReset,
searchableSubmit,
searchableLoadingIndicator,
...transformedTemplates
} = allTemplates;
return transformedTemplates;
} | javascript | function transformTemplates(templates) {
const allTemplates = {
...templates,
submit: templates.searchableSubmit,
reset: templates.searchableReset,
loadingIndicator: templates.searchableLoadingIndicator,
};
const {
searchableReset,
searchableSubmit,
searchableLoadingIndicator,
...transformedTemplates
} = allTemplates;
return transformedTemplates;
} | [
"function",
"transformTemplates",
"(",
"templates",
")",
"{",
"const",
"allTemplates",
"=",
"{",
"...",
"templates",
",",
"submit",
":",
"templates",
".",
"searchableSubmit",
",",
"reset",
":",
"templates",
".",
"searchableReset",
",",
"loadingIndicator",
":",
"templates",
".",
"searchableLoadingIndicator",
",",
"}",
";",
"const",
"{",
"searchableReset",
",",
"searchableSubmit",
",",
"searchableLoadingIndicator",
",",
"...",
"transformedTemplates",
"}",
"=",
"allTemplates",
";",
"return",
"transformedTemplates",
";",
"}"
] | Transforms the searchable templates by removing the `searchable` prefix.
This makes them usable in the `SearchBox` component.
@param {object} templates The widget templates
@returns {object} the formatted templates | [
"Transforms",
"the",
"searchable",
"templates",
"by",
"removing",
"the",
"searchable",
"prefix",
"."
] | adf8220064dd46b5b6d6b06ef0e858bf476f219b | https://github.com/algolia/instantsearch.js/blob/adf8220064dd46b5b6d6b06ef0e858bf476f219b/src/widgets/refinement-list/refinement-list.js#L27-L43 |
7,632 | algolia/instantsearch.js | src/lib/utils/clearRefinements.js | clearRefinements | function clearRefinements({ helper, attributesToClear = [] }) {
let finalState = helper.state;
attributesToClear.forEach(attribute => {
if (attribute === '_tags') {
finalState = finalState.clearTags();
} else {
finalState = finalState.clearRefinements(attribute);
}
});
if (attributesToClear.indexOf('query') !== -1) {
finalState = finalState.setQuery('');
}
return finalState;
} | javascript | function clearRefinements({ helper, attributesToClear = [] }) {
let finalState = helper.state;
attributesToClear.forEach(attribute => {
if (attribute === '_tags') {
finalState = finalState.clearTags();
} else {
finalState = finalState.clearRefinements(attribute);
}
});
if (attributesToClear.indexOf('query') !== -1) {
finalState = finalState.setQuery('');
}
return finalState;
} | [
"function",
"clearRefinements",
"(",
"{",
"helper",
",",
"attributesToClear",
"=",
"[",
"]",
"}",
")",
"{",
"let",
"finalState",
"=",
"helper",
".",
"state",
";",
"attributesToClear",
".",
"forEach",
"(",
"attribute",
"=>",
"{",
"if",
"(",
"attribute",
"===",
"'_tags'",
")",
"{",
"finalState",
"=",
"finalState",
".",
"clearTags",
"(",
")",
";",
"}",
"else",
"{",
"finalState",
"=",
"finalState",
".",
"clearRefinements",
"(",
"attribute",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"attributesToClear",
".",
"indexOf",
"(",
"'query'",
")",
"!==",
"-",
"1",
")",
"{",
"finalState",
"=",
"finalState",
".",
"setQuery",
"(",
"''",
")",
";",
"}",
"return",
"finalState",
";",
"}"
] | Clears the refinements of a SearchParameters object based on rules provided.
The included attributes list is applied before the excluded attributes list. If the list
is not provided, this list of all the currently refined attributes is used as included attributes.
@param {object} $0 parameters
@param {Helper} $0.helper instance of the Helper
@param {string[]} [$0.attributesToClear = []] list of parameters to clear
@returns {SearchParameters} search parameters with refinements cleared | [
"Clears",
"the",
"refinements",
"of",
"a",
"SearchParameters",
"object",
"based",
"on",
"rules",
"provided",
".",
"The",
"included",
"attributes",
"list",
"is",
"applied",
"before",
"the",
"excluded",
"attributes",
"list",
".",
"If",
"the",
"list",
"is",
"not",
"provided",
"this",
"list",
"of",
"all",
"the",
"currently",
"refined",
"attributes",
"is",
"used",
"as",
"included",
"attributes",
"."
] | adf8220064dd46b5b6d6b06ef0e858bf476f219b | https://github.com/algolia/instantsearch.js/blob/adf8220064dd46b5b6d6b06ef0e858bf476f219b/src/lib/utils/clearRefinements.js#L10-L26 |
7,633 | algolia/instantsearch.js | src/lib/utils/prepareTemplateProps.js | prepareTemplateProps | function prepareTemplateProps({
defaultTemplates,
templates,
templatesConfig,
}) {
const preparedTemplates = prepareTemplates(defaultTemplates, templates);
return {
templatesConfig,
...preparedTemplates,
};
} | javascript | function prepareTemplateProps({
defaultTemplates,
templates,
templatesConfig,
}) {
const preparedTemplates = prepareTemplates(defaultTemplates, templates);
return {
templatesConfig,
...preparedTemplates,
};
} | [
"function",
"prepareTemplateProps",
"(",
"{",
"defaultTemplates",
",",
"templates",
",",
"templatesConfig",
",",
"}",
")",
"{",
"const",
"preparedTemplates",
"=",
"prepareTemplates",
"(",
"defaultTemplates",
",",
"templates",
")",
";",
"return",
"{",
"templatesConfig",
",",
"...",
"preparedTemplates",
",",
"}",
";",
"}"
] | Prepares an object to be passed to the Template widget
@param {object} unknownBecauseES6 an object with the following attributes:
- defaultTemplate
- templates
- templatesConfig
@return {object} the configuration with the attributes:
- defaultTemplate
- templates
- useCustomCompileOptions | [
"Prepares",
"an",
"object",
"to",
"be",
"passed",
"to",
"the",
"Template",
"widget"
] | adf8220064dd46b5b6d6b06ef0e858bf476f219b | https://github.com/algolia/instantsearch.js/blob/adf8220064dd46b5b6d6b06ef0e858bf476f219b/src/lib/utils/prepareTemplateProps.js#L38-L49 |
7,634 | lingui/js-lingui | scripts/build/modules.js | getDependencies | function getDependencies(bundleType, entry) {
const packageJson = require(path.dirname(require.resolve(entry)) +
"/package.json")
// Both deps and peerDeps are assumed as accessible.
return Array.from(
new Set([
...Object.keys(packageJson.dependencies || {}),
...Object.keys(packageJson.peerDependencies || {})
])
)
} | javascript | function getDependencies(bundleType, entry) {
const packageJson = require(path.dirname(require.resolve(entry)) +
"/package.json")
// Both deps and peerDeps are assumed as accessible.
return Array.from(
new Set([
...Object.keys(packageJson.dependencies || {}),
...Object.keys(packageJson.peerDependencies || {})
])
)
} | [
"function",
"getDependencies",
"(",
"bundleType",
",",
"entry",
")",
"{",
"const",
"packageJson",
"=",
"require",
"(",
"path",
".",
"dirname",
"(",
"require",
".",
"resolve",
"(",
"entry",
")",
")",
"+",
"\"/package.json\"",
")",
"// Both deps and peerDeps are assumed as accessible.",
"return",
"Array",
".",
"from",
"(",
"new",
"Set",
"(",
"[",
"...",
"Object",
".",
"keys",
"(",
"packageJson",
".",
"dependencies",
"||",
"{",
"}",
")",
",",
"...",
"Object",
".",
"keys",
"(",
"packageJson",
".",
"peerDependencies",
"||",
"{",
"}",
")",
"]",
")",
")",
"}"
] | Determines node_modules packages that are safe to assume will exist. | [
"Determines",
"node_modules",
"packages",
"that",
"are",
"safe",
"to",
"assume",
"will",
"exist",
"."
] | c9a4b151f621502349d3ee7ce1fc3e10d88f4a73 | https://github.com/lingui/js-lingui/blob/c9a4b151f621502349d3ee7ce1fc3e10d88f4a73/scripts/build/modules.js#L37-L47 |
7,635 | PolymathNetwork/polymath-core | CLI/commands/investor_portal.js | inputSymbol | async function inputSymbol(symbol) {
if (typeof symbol === 'undefined') {
STSymbol = readlineSync.question(chalk.yellow(`Enter the symbol of a registered security token or press 'Enter' to exit: `));
} else {
STSymbol = symbol;
}
if (STSymbol == "") process.exit();
STAddress = await securityTokenRegistry.methods.getSecurityTokenAddress(STSymbol).call();
if (STAddress == "0x0000000000000000000000000000000000000000") {
console.log(`Token symbol provided is not a registered Security Token. Please enter another symbol.`);
} else {
let securityTokenABI = abis.securityToken();
securityToken = new web3.eth.Contract(securityTokenABI, STAddress);
await showTokenInfo();
let gtmModule = await securityToken.methods.getModulesByName(web3.utils.toHex('GeneralTransferManager')).call();
let generalTransferManagerABI = abis.generalTransferManager();
generalTransferManager = new web3.eth.Contract(generalTransferManagerABI, gtmModule[0]);
let stoModules = await securityToken.methods.getModulesByType(gbl.constants.MODULES_TYPES.STO).call();
if (stoModules.length == 0) {
console.log(chalk.red(`There is no STO module attached to the ${STSymbol.toUpperCase()} Token. No further actions can be taken.`));
process.exit(0);
} else {
STOAddress = stoModules[0];
let stoModuleData = await securityToken.methods.getModule(STOAddress).call();
selectedSTO = web3.utils.toAscii(stoModuleData[0]).replace(/\u0000/g, '');
let interfaceSTOABI = abis.stoInterface();
currentSTO = new web3.eth.Contract(interfaceSTOABI, STOAddress);
}
}
} | javascript | async function inputSymbol(symbol) {
if (typeof symbol === 'undefined') {
STSymbol = readlineSync.question(chalk.yellow(`Enter the symbol of a registered security token or press 'Enter' to exit: `));
} else {
STSymbol = symbol;
}
if (STSymbol == "") process.exit();
STAddress = await securityTokenRegistry.methods.getSecurityTokenAddress(STSymbol).call();
if (STAddress == "0x0000000000000000000000000000000000000000") {
console.log(`Token symbol provided is not a registered Security Token. Please enter another symbol.`);
} else {
let securityTokenABI = abis.securityToken();
securityToken = new web3.eth.Contract(securityTokenABI, STAddress);
await showTokenInfo();
let gtmModule = await securityToken.methods.getModulesByName(web3.utils.toHex('GeneralTransferManager')).call();
let generalTransferManagerABI = abis.generalTransferManager();
generalTransferManager = new web3.eth.Contract(generalTransferManagerABI, gtmModule[0]);
let stoModules = await securityToken.methods.getModulesByType(gbl.constants.MODULES_TYPES.STO).call();
if (stoModules.length == 0) {
console.log(chalk.red(`There is no STO module attached to the ${STSymbol.toUpperCase()} Token. No further actions can be taken.`));
process.exit(0);
} else {
STOAddress = stoModules[0];
let stoModuleData = await securityToken.methods.getModule(STOAddress).call();
selectedSTO = web3.utils.toAscii(stoModuleData[0]).replace(/\u0000/g, '');
let interfaceSTOABI = abis.stoInterface();
currentSTO = new web3.eth.Contract(interfaceSTOABI, STOAddress);
}
}
} | [
"async",
"function",
"inputSymbol",
"(",
"symbol",
")",
"{",
"if",
"(",
"typeof",
"symbol",
"===",
"'undefined'",
")",
"{",
"STSymbol",
"=",
"readlineSync",
".",
"question",
"(",
"chalk",
".",
"yellow",
"(",
"`",
"`",
")",
")",
";",
"}",
"else",
"{",
"STSymbol",
"=",
"symbol",
";",
"}",
"if",
"(",
"STSymbol",
"==",
"\"\"",
")",
"process",
".",
"exit",
"(",
")",
";",
"STAddress",
"=",
"await",
"securityTokenRegistry",
".",
"methods",
".",
"getSecurityTokenAddress",
"(",
"STSymbol",
")",
".",
"call",
"(",
")",
";",
"if",
"(",
"STAddress",
"==",
"\"0x0000000000000000000000000000000000000000\"",
")",
"{",
"console",
".",
"log",
"(",
"`",
"`",
")",
";",
"}",
"else",
"{",
"let",
"securityTokenABI",
"=",
"abis",
".",
"securityToken",
"(",
")",
";",
"securityToken",
"=",
"new",
"web3",
".",
"eth",
".",
"Contract",
"(",
"securityTokenABI",
",",
"STAddress",
")",
";",
"await",
"showTokenInfo",
"(",
")",
";",
"let",
"gtmModule",
"=",
"await",
"securityToken",
".",
"methods",
".",
"getModulesByName",
"(",
"web3",
".",
"utils",
".",
"toHex",
"(",
"'GeneralTransferManager'",
")",
")",
".",
"call",
"(",
")",
";",
"let",
"generalTransferManagerABI",
"=",
"abis",
".",
"generalTransferManager",
"(",
")",
";",
"generalTransferManager",
"=",
"new",
"web3",
".",
"eth",
".",
"Contract",
"(",
"generalTransferManagerABI",
",",
"gtmModule",
"[",
"0",
"]",
")",
";",
"let",
"stoModules",
"=",
"await",
"securityToken",
".",
"methods",
".",
"getModulesByType",
"(",
"gbl",
".",
"constants",
".",
"MODULES_TYPES",
".",
"STO",
")",
".",
"call",
"(",
")",
";",
"if",
"(",
"stoModules",
".",
"length",
"==",
"0",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"`",
"${",
"STSymbol",
".",
"toUpperCase",
"(",
")",
"}",
"`",
")",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
"else",
"{",
"STOAddress",
"=",
"stoModules",
"[",
"0",
"]",
";",
"let",
"stoModuleData",
"=",
"await",
"securityToken",
".",
"methods",
".",
"getModule",
"(",
"STOAddress",
")",
".",
"call",
"(",
")",
";",
"selectedSTO",
"=",
"web3",
".",
"utils",
".",
"toAscii",
"(",
"stoModuleData",
"[",
"0",
"]",
")",
".",
"replace",
"(",
"/",
"\\u0000",
"/",
"g",
",",
"''",
")",
";",
"let",
"interfaceSTOABI",
"=",
"abis",
".",
"stoInterface",
"(",
")",
";",
"currentSTO",
"=",
"new",
"web3",
".",
"eth",
".",
"Contract",
"(",
"interfaceSTOABI",
",",
"STOAddress",
")",
";",
"}",
"}",
"}"
] | Input security token symbol or exit | [
"Input",
"security",
"token",
"symbol",
"or",
"exit"
] | aa635df01588f733ce95bc13fe319c7d3c858a24 | https://github.com/PolymathNetwork/polymath-core/blob/aa635df01588f733ce95bc13fe319c7d3c858a24/CLI/commands/investor_portal.js#L102-L136 |
7,636 | PolymathNetwork/polymath-core | CLI/commands/token_manager.js | addModule | async function addModule() {
let options = ['Permission Manager', 'Transfer Manager', 'Security Token Offering', 'Dividends', 'Burn'];
let index = readlineSync.keyInSelect(options, 'What type of module would you like to add?', { cancel: 'Return' });
switch (options[index]) {
case 'Permission Manager':
console.log(chalk.red(`
*********************************
This option is not yet available.
*********************************`));
break;
case 'Transfer Manager':
await transferManager.addTransferManagerModule(tokenSymbol)
break;
case 'Security Token Offering':
await stoManager.addSTOModule(tokenSymbol)
break;
case 'Dividends':
console.log(chalk.red(`
*********************************
This option is not yet available.
*********************************`));
break;
case 'Burn':
console.log(chalk.red(`
*********************************
This option is not yet available.
*********************************`));
break;
}
} | javascript | async function addModule() {
let options = ['Permission Manager', 'Transfer Manager', 'Security Token Offering', 'Dividends', 'Burn'];
let index = readlineSync.keyInSelect(options, 'What type of module would you like to add?', { cancel: 'Return' });
switch (options[index]) {
case 'Permission Manager':
console.log(chalk.red(`
*********************************
This option is not yet available.
*********************************`));
break;
case 'Transfer Manager':
await transferManager.addTransferManagerModule(tokenSymbol)
break;
case 'Security Token Offering':
await stoManager.addSTOModule(tokenSymbol)
break;
case 'Dividends':
console.log(chalk.red(`
*********************************
This option is not yet available.
*********************************`));
break;
case 'Burn':
console.log(chalk.red(`
*********************************
This option is not yet available.
*********************************`));
break;
}
} | [
"async",
"function",
"addModule",
"(",
")",
"{",
"let",
"options",
"=",
"[",
"'Permission Manager'",
",",
"'Transfer Manager'",
",",
"'Security Token Offering'",
",",
"'Dividends'",
",",
"'Burn'",
"]",
";",
"let",
"index",
"=",
"readlineSync",
".",
"keyInSelect",
"(",
"options",
",",
"'What type of module would you like to add?'",
",",
"{",
"cancel",
":",
"'Return'",
"}",
")",
";",
"switch",
"(",
"options",
"[",
"index",
"]",
")",
"{",
"case",
"'Permission Manager'",
":",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"`",
"`",
")",
")",
";",
"break",
";",
"case",
"'Transfer Manager'",
":",
"await",
"transferManager",
".",
"addTransferManagerModule",
"(",
"tokenSymbol",
")",
"break",
";",
"case",
"'Security Token Offering'",
":",
"await",
"stoManager",
".",
"addSTOModule",
"(",
"tokenSymbol",
")",
"break",
";",
"case",
"'Dividends'",
":",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"`",
"`",
")",
")",
";",
"break",
";",
"case",
"'Burn'",
":",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"`",
"`",
")",
")",
";",
"break",
";",
"}",
"}"
] | Modules a actions | [
"Modules",
"a",
"actions"
] | aa635df01588f733ce95bc13fe319c7d3c858a24 | https://github.com/PolymathNetwork/polymath-core/blob/aa635df01588f733ce95bc13fe319c7d3c858a24/CLI/commands/token_manager.js#L456-L485 |
7,637 | bestiejs/platform.js | platform.js | cleanupOS | function cleanupOS(os, pattern, label) {
// Platform tokens are defined at:
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
var data = {
'10.0': '10',
'6.4': '10 Technical Preview',
'6.3': '8.1',
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
};
// Detect Windows version from platform tokens.
if (pattern && label && /^Win/i.test(os) && !/^Windows Phone /i.test(os) &&
(data = data[/[\d.]+$/.exec(os)])) {
os = 'Windows ' + data;
}
// Correct character case and cleanup string.
os = String(os);
if (pattern && label) {
os = os.replace(RegExp(pattern, 'i'), label);
}
os = format(
os.replace(/ ce$/i, ' CE')
.replace(/\bhpw/i, 'web')
.replace(/\bMacintosh\b/, 'Mac OS')
.replace(/_PowerPC\b/i, ' OS')
.replace(/\b(OS X) [^ \d]+/i, '$1')
.replace(/\bMac (OS X)\b/, '$1')
.replace(/\/(\d)/, ' $1')
.replace(/_/g, '.')
.replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '')
.replace(/\bx86\.64\b/gi, 'x86_64')
.replace(/\b(Windows Phone) OS\b/, '$1')
.replace(/\b(Chrome OS \w+) [\d.]+\b/, '$1')
.split(' on ')[0]
);
return os;
} | javascript | function cleanupOS(os, pattern, label) {
// Platform tokens are defined at:
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
var data = {
'10.0': '10',
'6.4': '10 Technical Preview',
'6.3': '8.1',
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
};
// Detect Windows version from platform tokens.
if (pattern && label && /^Win/i.test(os) && !/^Windows Phone /i.test(os) &&
(data = data[/[\d.]+$/.exec(os)])) {
os = 'Windows ' + data;
}
// Correct character case and cleanup string.
os = String(os);
if (pattern && label) {
os = os.replace(RegExp(pattern, 'i'), label);
}
os = format(
os.replace(/ ce$/i, ' CE')
.replace(/\bhpw/i, 'web')
.replace(/\bMacintosh\b/, 'Mac OS')
.replace(/_PowerPC\b/i, ' OS')
.replace(/\b(OS X) [^ \d]+/i, '$1')
.replace(/\bMac (OS X)\b/, '$1')
.replace(/\/(\d)/, ' $1')
.replace(/_/g, '.')
.replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '')
.replace(/\bx86\.64\b/gi, 'x86_64')
.replace(/\b(Windows Phone) OS\b/, '$1')
.replace(/\b(Chrome OS \w+) [\d.]+\b/, '$1')
.split(' on ')[0]
);
return os;
} | [
"function",
"cleanupOS",
"(",
"os",
",",
"pattern",
",",
"label",
")",
"{",
"// Platform tokens are defined at:",
"// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx",
"// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx",
"var",
"data",
"=",
"{",
"'10.0'",
":",
"'10'",
",",
"'6.4'",
":",
"'10 Technical Preview'",
",",
"'6.3'",
":",
"'8.1'",
",",
"'6.2'",
":",
"'8'",
",",
"'6.1'",
":",
"'Server 2008 R2 / 7'",
",",
"'6.0'",
":",
"'Server 2008 / Vista'",
",",
"'5.2'",
":",
"'Server 2003 / XP 64-bit'",
",",
"'5.1'",
":",
"'XP'",
",",
"'5.01'",
":",
"'2000 SP1'",
",",
"'5.0'",
":",
"'2000'",
",",
"'4.0'",
":",
"'NT'",
",",
"'4.90'",
":",
"'ME'",
"}",
";",
"// Detect Windows version from platform tokens.",
"if",
"(",
"pattern",
"&&",
"label",
"&&",
"/",
"^Win",
"/",
"i",
".",
"test",
"(",
"os",
")",
"&&",
"!",
"/",
"^Windows Phone ",
"/",
"i",
".",
"test",
"(",
"os",
")",
"&&",
"(",
"data",
"=",
"data",
"[",
"/",
"[\\d.]+$",
"/",
".",
"exec",
"(",
"os",
")",
"]",
")",
")",
"{",
"os",
"=",
"'Windows '",
"+",
"data",
";",
"}",
"// Correct character case and cleanup string.",
"os",
"=",
"String",
"(",
"os",
")",
";",
"if",
"(",
"pattern",
"&&",
"label",
")",
"{",
"os",
"=",
"os",
".",
"replace",
"(",
"RegExp",
"(",
"pattern",
",",
"'i'",
")",
",",
"label",
")",
";",
"}",
"os",
"=",
"format",
"(",
"os",
".",
"replace",
"(",
"/",
" ce$",
"/",
"i",
",",
"' CE'",
")",
".",
"replace",
"(",
"/",
"\\bhpw",
"/",
"i",
",",
"'web'",
")",
".",
"replace",
"(",
"/",
"\\bMacintosh\\b",
"/",
",",
"'Mac OS'",
")",
".",
"replace",
"(",
"/",
"_PowerPC\\b",
"/",
"i",
",",
"' OS'",
")",
".",
"replace",
"(",
"/",
"\\b(OS X) [^ \\d]+",
"/",
"i",
",",
"'$1'",
")",
".",
"replace",
"(",
"/",
"\\bMac (OS X)\\b",
"/",
",",
"'$1'",
")",
".",
"replace",
"(",
"/",
"\\/(\\d)",
"/",
",",
"' $1'",
")",
".",
"replace",
"(",
"/",
"_",
"/",
"g",
",",
"'.'",
")",
".",
"replace",
"(",
"/",
"(?: BePC|[ .]*fc[ \\d.]+)$",
"/",
"i",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\bx86\\.64\\b",
"/",
"gi",
",",
"'x86_64'",
")",
".",
"replace",
"(",
"/",
"\\b(Windows Phone) OS\\b",
"/",
",",
"'$1'",
")",
".",
"replace",
"(",
"/",
"\\b(Chrome OS \\w+) [\\d.]+\\b",
"/",
",",
"'$1'",
")",
".",
"split",
"(",
"' on '",
")",
"[",
"0",
"]",
")",
";",
"return",
"os",
";",
"}"
] | A utility function to clean up the OS name.
@private
@param {string} os The OS name to clean up.
@param {string} [pattern] A `RegExp` pattern matching the OS name.
@param {string} [label] A label for the OS. | [
"A",
"utility",
"function",
"to",
"clean",
"up",
"the",
"OS",
"name",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L78-L125 |
7,638 | bestiejs/platform.js | platform.js | each | function each(object, callback) {
var index = -1,
length = object ? object.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
} | javascript | function each(object, callback) {
var index = -1,
length = object ? object.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
} | [
"function",
"each",
"(",
"object",
",",
"callback",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"object",
"?",
"object",
".",
"length",
":",
"0",
";",
"if",
"(",
"typeof",
"length",
"==",
"'number'",
"&&",
"length",
">",
"-",
"1",
"&&",
"length",
"<=",
"maxSafeInteger",
")",
"{",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"callback",
"(",
"object",
"[",
"index",
"]",
",",
"index",
",",
"object",
")",
";",
"}",
"}",
"else",
"{",
"forOwn",
"(",
"object",
",",
"callback",
")",
";",
"}",
"}"
] | An iteration utility for arrays and objects.
@private
@param {Array|Object} object The object to iterate over.
@param {Function} callback The function called per iteration. | [
"An",
"iteration",
"utility",
"for",
"arrays",
"and",
"objects",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L134-L145 |
7,639 | bestiejs/platform.js | platform.js | format | function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string)
? string
: capitalize(string);
} | javascript | function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string)
? string
: capitalize(string);
} | [
"function",
"format",
"(",
"string",
")",
"{",
"string",
"=",
"trim",
"(",
"string",
")",
";",
"return",
"/",
"^(?:webOS|i(?:OS|P))",
"/",
".",
"test",
"(",
"string",
")",
"?",
"string",
":",
"capitalize",
"(",
"string",
")",
";",
"}"
] | Trim and conditionally capitalize string values.
@private
@param {string} string The string to format.
@returns {string} The formatted string. | [
"Trim",
"and",
"conditionally",
"capitalize",
"string",
"values",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L154-L159 |
7,640 | bestiejs/platform.js | platform.js | forOwn | function forOwn(object, callback) {
for (var key in object) {
if (hasOwnProperty.call(object, key)) {
callback(object[key], key, object);
}
}
} | javascript | function forOwn(object, callback) {
for (var key in object) {
if (hasOwnProperty.call(object, key)) {
callback(object[key], key, object);
}
}
} | [
"function",
"forOwn",
"(",
"object",
",",
"callback",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"object",
")",
"{",
"if",
"(",
"hasOwnProperty",
".",
"call",
"(",
"object",
",",
"key",
")",
")",
"{",
"callback",
"(",
"object",
"[",
"key",
"]",
",",
"key",
",",
"object",
")",
";",
"}",
"}",
"}"
] | Iterates over an object's own properties, executing the `callback` for each.
@private
@param {Object} object The object to iterate over.
@param {Function} callback The function executed per own property. | [
"Iterates",
"over",
"an",
"object",
"s",
"own",
"properties",
"executing",
"the",
"callback",
"for",
"each",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L168-L174 |
7,641 | bestiejs/platform.js | platform.js | getManufacturer | function getManufacturer(guesses) {
return reduce(guesses, function(result, value, key) {
// Lookup the manufacturer by product or scan the UA for the manufacturer.
return result || (
value[product] ||
value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] ||
RegExp('\\b' + qualify(key) + '(?:\\b|\\w*\\d)', 'i').exec(ua)
) && key;
});
} | javascript | function getManufacturer(guesses) {
return reduce(guesses, function(result, value, key) {
// Lookup the manufacturer by product or scan the UA for the manufacturer.
return result || (
value[product] ||
value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] ||
RegExp('\\b' + qualify(key) + '(?:\\b|\\w*\\d)', 'i').exec(ua)
) && key;
});
} | [
"function",
"getManufacturer",
"(",
"guesses",
")",
"{",
"return",
"reduce",
"(",
"guesses",
",",
"function",
"(",
"result",
",",
"value",
",",
"key",
")",
"{",
"// Lookup the manufacturer by product or scan the UA for the manufacturer.",
"return",
"result",
"||",
"(",
"value",
"[",
"product",
"]",
"||",
"value",
"[",
"/",
"^[a-z]+(?: +[a-z]+\\b)*",
"/",
"i",
".",
"exec",
"(",
"product",
")",
"]",
"||",
"RegExp",
"(",
"'\\\\b'",
"+",
"qualify",
"(",
"key",
")",
"+",
"'(?:\\\\b|\\\\w*\\\\d)'",
",",
"'i'",
")",
".",
"exec",
"(",
"ua",
")",
")",
"&&",
"key",
";",
"}",
")",
";",
"}"
] | Picks the manufacturer from an array of guesses.
@private
@param {Array} guesses An object of guesses.
@returns {null|string} The detected manufacturer. | [
"Picks",
"the",
"manufacturer",
"from",
"an",
"array",
"of",
"guesses",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L514-L523 |
7,642 | bestiejs/platform.js | platform.js | getOS | function getOS(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua)
)) {
result = cleanupOS(result, pattern, guess.label || guess);
}
return result;
});
} | javascript | function getOS(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua)
)) {
result = cleanupOS(result, pattern, guess.label || guess);
}
return result;
});
} | [
"function",
"getOS",
"(",
"guesses",
")",
"{",
"return",
"reduce",
"(",
"guesses",
",",
"function",
"(",
"result",
",",
"guess",
")",
"{",
"var",
"pattern",
"=",
"guess",
".",
"pattern",
"||",
"qualify",
"(",
"guess",
")",
";",
"if",
"(",
"!",
"result",
"&&",
"(",
"result",
"=",
"RegExp",
"(",
"'\\\\b'",
"+",
"pattern",
"+",
"'(?:/[\\\\d.]+|[ \\\\w.]*)'",
",",
"'i'",
")",
".",
"exec",
"(",
"ua",
")",
")",
")",
"{",
"result",
"=",
"cleanupOS",
"(",
"result",
",",
"pattern",
",",
"guess",
".",
"label",
"||",
"guess",
")",
";",
"}",
"return",
"result",
";",
"}",
")",
";",
"}"
] | Picks the OS name from an array of guesses.
@private
@param {Array} guesses An array of guesses.
@returns {null|string} The detected OS name. | [
"Picks",
"the",
"OS",
"name",
"from",
"an",
"array",
"of",
"guesses",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L547-L557 |
7,643 | bestiejs/platform.js | platform.js | getProduct | function getProduct(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + ' *\\w+-[\\w]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua)
)) {
// Split by forward slash and append product version if needed.
if ((result = String((guess.label && !RegExp(pattern, 'i').test(guess.label)) ? guess.label : result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
}
// Correct character case and cleanup string.
guess = guess.label || guess;
result = format(result[0]
.replace(RegExp(pattern, 'i'), guess)
.replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ')
.replace(RegExp('(' + guess + ')[-_.]?(\\w)', 'i'), '$1 $2'));
}
return result;
});
} | javascript | function getProduct(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + ' *\\w+-[\\w]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua)
)) {
// Split by forward slash and append product version if needed.
if ((result = String((guess.label && !RegExp(pattern, 'i').test(guess.label)) ? guess.label : result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
}
// Correct character case and cleanup string.
guess = guess.label || guess;
result = format(result[0]
.replace(RegExp(pattern, 'i'), guess)
.replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ')
.replace(RegExp('(' + guess + ')[-_.]?(\\w)', 'i'), '$1 $2'));
}
return result;
});
} | [
"function",
"getProduct",
"(",
"guesses",
")",
"{",
"return",
"reduce",
"(",
"guesses",
",",
"function",
"(",
"result",
",",
"guess",
")",
"{",
"var",
"pattern",
"=",
"guess",
".",
"pattern",
"||",
"qualify",
"(",
"guess",
")",
";",
"if",
"(",
"!",
"result",
"&&",
"(",
"result",
"=",
"RegExp",
"(",
"'\\\\b'",
"+",
"pattern",
"+",
"' *\\\\d+[.\\\\w_]*'",
",",
"'i'",
")",
".",
"exec",
"(",
"ua",
")",
"||",
"RegExp",
"(",
"'\\\\b'",
"+",
"pattern",
"+",
"' *\\\\w+-[\\\\w]*'",
",",
"'i'",
")",
".",
"exec",
"(",
"ua",
")",
"||",
"RegExp",
"(",
"'\\\\b'",
"+",
"pattern",
"+",
"'(?:; *(?:[a-z]+[_-])?[a-z]+\\\\d+|[^ ();-]*)'",
",",
"'i'",
")",
".",
"exec",
"(",
"ua",
")",
")",
")",
"{",
"// Split by forward slash and append product version if needed.",
"if",
"(",
"(",
"result",
"=",
"String",
"(",
"(",
"guess",
".",
"label",
"&&",
"!",
"RegExp",
"(",
"pattern",
",",
"'i'",
")",
".",
"test",
"(",
"guess",
".",
"label",
")",
")",
"?",
"guess",
".",
"label",
":",
"result",
")",
".",
"split",
"(",
"'/'",
")",
")",
"[",
"1",
"]",
"&&",
"!",
"/",
"[\\d.]+",
"/",
".",
"test",
"(",
"result",
"[",
"0",
"]",
")",
")",
"{",
"result",
"[",
"0",
"]",
"+=",
"' '",
"+",
"result",
"[",
"1",
"]",
";",
"}",
"// Correct character case and cleanup string.",
"guess",
"=",
"guess",
".",
"label",
"||",
"guess",
";",
"result",
"=",
"format",
"(",
"result",
"[",
"0",
"]",
".",
"replace",
"(",
"RegExp",
"(",
"pattern",
",",
"'i'",
")",
",",
"guess",
")",
".",
"replace",
"(",
"RegExp",
"(",
"'; *(?:'",
"+",
"guess",
"+",
"'[_-])?'",
",",
"'i'",
")",
",",
"' '",
")",
".",
"replace",
"(",
"RegExp",
"(",
"'('",
"+",
"guess",
"+",
"')[-_.]?(\\\\w)'",
",",
"'i'",
")",
",",
"'$1 $2'",
")",
")",
";",
"}",
"return",
"result",
";",
"}",
")",
";",
"}"
] | Picks the product name from an array of guesses.
@private
@param {Array} guesses An array of guesses.
@returns {null|string} The detected product name. | [
"Picks",
"the",
"product",
"name",
"from",
"an",
"array",
"of",
"guesses",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L566-L587 |
7,644 | bestiejs/platform.js | platform.js | getVersion | function getVersion(patterns) {
return reduce(patterns, function(result, pattern) {
return result || (RegExp(pattern +
'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null;
});
} | javascript | function getVersion(patterns) {
return reduce(patterns, function(result, pattern) {
return result || (RegExp(pattern +
'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null;
});
} | [
"function",
"getVersion",
"(",
"patterns",
")",
"{",
"return",
"reduce",
"(",
"patterns",
",",
"function",
"(",
"result",
",",
"pattern",
")",
"{",
"return",
"result",
"||",
"(",
"RegExp",
"(",
"pattern",
"+",
"'(?:-[\\\\d.]+/|(?: for [\\\\w-]+)?[ /-])([\\\\d.]+[^ ();/_-]*)'",
",",
"'i'",
")",
".",
"exec",
"(",
"ua",
")",
"||",
"0",
")",
"[",
"1",
"]",
"||",
"null",
";",
"}",
")",
";",
"}"
] | Resolves the version using an array of UA patterns.
@private
@param {Array} patterns An array of UA patterns.
@returns {null|string} The detected version. | [
"Resolves",
"the",
"version",
"using",
"an",
"array",
"of",
"UA",
"patterns",
"."
] | a8816881779addd8af6d8512e0295f37f8489ec7 | https://github.com/bestiejs/platform.js/blob/a8816881779addd8af6d8512e0295f37f8489ec7/platform.js#L596-L601 |
7,645 | KhaosT/HAP-NodeJS | lib/Characteristic.js | Characteristic | function Characteristic(displayName, UUID, props) {
this.displayName = displayName;
this.UUID = UUID;
this.iid = null; // assigned by our containing Service
this.value = null;
this.status = null;
this.eventOnlyCharacteristic = false;
this.props = props || {
format: null,
unit: null,
minValue: null,
maxValue: null,
minStep: null,
perms: []
};
this.subscriptions = 0;
} | javascript | function Characteristic(displayName, UUID, props) {
this.displayName = displayName;
this.UUID = UUID;
this.iid = null; // assigned by our containing Service
this.value = null;
this.status = null;
this.eventOnlyCharacteristic = false;
this.props = props || {
format: null,
unit: null,
minValue: null,
maxValue: null,
minStep: null,
perms: []
};
this.subscriptions = 0;
} | [
"function",
"Characteristic",
"(",
"displayName",
",",
"UUID",
",",
"props",
")",
"{",
"this",
".",
"displayName",
"=",
"displayName",
";",
"this",
".",
"UUID",
"=",
"UUID",
";",
"this",
".",
"iid",
"=",
"null",
";",
"// assigned by our containing Service",
"this",
".",
"value",
"=",
"null",
";",
"this",
".",
"status",
"=",
"null",
";",
"this",
".",
"eventOnlyCharacteristic",
"=",
"false",
";",
"this",
".",
"props",
"=",
"props",
"||",
"{",
"format",
":",
"null",
",",
"unit",
":",
"null",
",",
"minValue",
":",
"null",
",",
"maxValue",
":",
"null",
",",
"minStep",
":",
"null",
",",
"perms",
":",
"[",
"]",
"}",
";",
"this",
".",
"subscriptions",
"=",
"0",
";",
"}"
] | Characteristic represents a particular typed variable that can be assigned to a Service. For instance, a
"Hue" Characteristic might store a 'float' value of type 'arcdegrees'. You could add the Hue Characteristic
to a Service in order to store that value. A particular Characteristic is distinguished from others by its
UUID. HomeKit provides a set of known Characteristic UUIDs defined in HomeKitTypes.js along with a
corresponding concrete subclass.
You can also define custom Characteristics by providing your own UUID. Custom Characteristics can be added
to any native or custom Services, but Siri will likely not be able to work with these.
Note that you can get the "value" of a Characteristic by accessing the "value" property directly, but this
is really a "cached value". If you want to fetch the latest value, which may involve doing some work, then
call getValue().
@event 'get' => function(callback(err, newValue), context) { }
Emitted when someone calls getValue() on this Characteristic and desires the latest non-cached
value. If there are any listeners to this event, one of them MUST call the callback in order
for the value to ever be delivered. The `context` object is whatever was passed in by the initiator
of this event (for instance whomever called `getValue`).
@event 'set' => function(newValue, callback(err), context) { }
Emitted when someone calls setValue() on this Characteristic with a desired new value. If there
are any listeners to this event, one of them MUST call the callback in order for this.value to
actually be set. The `context` object is whatever was passed in by the initiator of this change
(for instance, whomever called `setValue`).
@event 'change' => function({ oldValue, newValue, context }) { }
Emitted after a change in our value has occurred. The new value will also be immediately accessible
in this.value. The event object contains the new value as well as the context object originally
passed in by the initiator of this change (if known). | [
"Characteristic",
"represents",
"a",
"particular",
"typed",
"variable",
"that",
"can",
"be",
"assigned",
"to",
"a",
"Service",
".",
"For",
"instance",
"a",
"Hue",
"Characteristic",
"might",
"store",
"a",
"float",
"value",
"of",
"type",
"arcdegrees",
".",
"You",
"could",
"add",
"the",
"Hue",
"Characteristic",
"to",
"a",
"Service",
"in",
"order",
"to",
"store",
"that",
"value",
".",
"A",
"particular",
"Characteristic",
"is",
"distinguished",
"from",
"others",
"by",
"its",
"UUID",
".",
"HomeKit",
"provides",
"a",
"set",
"of",
"known",
"Characteristic",
"UUIDs",
"defined",
"in",
"HomeKitTypes",
".",
"js",
"along",
"with",
"a",
"corresponding",
"concrete",
"subclass",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/Characteristic.js#L46-L63 |
7,646 | KhaosT/HAP-NodeJS | lib/model/AccessoryInfo.js | AccessoryInfo | function AccessoryInfo(username) {
this.username = username;
this.displayName = "";
this.category = "";
this.pincode = "";
this.signSk = bufferShim.alloc(0);
this.signPk = bufferShim.alloc(0);
this.pairedClients = {}; // pairedClients[clientUsername:string] = clientPublicKey:Buffer
this.configVersion = 1;
this.configHash = "";
this.setupID = "";
this.relayEnabled = false;
this.relayState = 2;
this.relayAccessoryID = "";
this.relayAdminID = "";
this.relayPairedControllers = {};
this.accessoryBagURL = "";
} | javascript | function AccessoryInfo(username) {
this.username = username;
this.displayName = "";
this.category = "";
this.pincode = "";
this.signSk = bufferShim.alloc(0);
this.signPk = bufferShim.alloc(0);
this.pairedClients = {}; // pairedClients[clientUsername:string] = clientPublicKey:Buffer
this.configVersion = 1;
this.configHash = "";
this.setupID = "";
this.relayEnabled = false;
this.relayState = 2;
this.relayAccessoryID = "";
this.relayAdminID = "";
this.relayPairedControllers = {};
this.accessoryBagURL = "";
} | [
"function",
"AccessoryInfo",
"(",
"username",
")",
"{",
"this",
".",
"username",
"=",
"username",
";",
"this",
".",
"displayName",
"=",
"\"\"",
";",
"this",
".",
"category",
"=",
"\"\"",
";",
"this",
".",
"pincode",
"=",
"\"\"",
";",
"this",
".",
"signSk",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"signPk",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"pairedClients",
"=",
"{",
"}",
";",
"// pairedClients[clientUsername:string] = clientPublicKey:Buffer",
"this",
".",
"configVersion",
"=",
"1",
";",
"this",
".",
"configHash",
"=",
"\"\"",
";",
"this",
".",
"setupID",
"=",
"\"\"",
";",
"this",
".",
"relayEnabled",
"=",
"false",
";",
"this",
".",
"relayState",
"=",
"2",
";",
"this",
".",
"relayAccessoryID",
"=",
"\"\"",
";",
"this",
".",
"relayAdminID",
"=",
"\"\"",
";",
"this",
".",
"relayPairedControllers",
"=",
"{",
"}",
";",
"this",
".",
"accessoryBagURL",
"=",
"\"\"",
";",
"}"
] | AccessoryInfo is a model class containing a subset of Accessory data relevant to the internal HAP server,
such as encryption keys and username. It is persisted to disk. | [
"AccessoryInfo",
"is",
"a",
"model",
"class",
"containing",
"a",
"subset",
"of",
"Accessory",
"data",
"relevant",
"to",
"the",
"internal",
"HAP",
"server",
"such",
"as",
"encryption",
"keys",
"and",
"username",
".",
"It",
"is",
"persisted",
"to",
"disk",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/model/AccessoryInfo.js#L17-L36 |
7,647 | KhaosT/HAP-NodeJS | lib/util/eventedhttp.js | EventedHTTPServerConnection | function EventedHTTPServerConnection(clientSocket) {
this.sessionID = uuid.generate(clientSocket.remoteAddress + ':' + clientSocket.remotePort);
this._remoteAddress = clientSocket.remoteAddress; // cache because it becomes undefined in 'onClientSocketClose'
this._pendingClientSocketData = bufferShim.alloc(0); // data received from client before HTTP proxy is fully setup
this._fullySetup = false; // true when we are finished establishing connections
this._writingResponse = false; // true while we are composing an HTTP response (so events can wait)
this._pendingEventData = bufferShim.alloc(0); // event data waiting to be sent until after an in-progress HTTP response is being written
// clientSocket is the socket connected to the actual iOS device
this._clientSocket = clientSocket;
this._clientSocket.on('data', this._onClientSocketData.bind(this));
this._clientSocket.on('close', this._onClientSocketClose.bind(this));
this._clientSocket.on('error', this._onClientSocketError.bind(this)); // we MUST register for this event, otherwise the error will bubble up to the top and crash the node process entirely.
// serverSocket is our connection to our own internal httpServer
this._serverSocket = null; // created after httpServer 'listening' event
// create our internal HTTP server for this connection that we will proxy data to and from
this._httpServer = http.createServer();
this._httpServer.timeout = 0; // clients expect to hold connections open as long as they want
this._httpServer.keepAliveTimeout = 0; // workaround for https://github.com/nodejs/node/issues/13391
this._httpServer.on('listening', this._onHttpServerListening.bind(this));
this._httpServer.on('request', this._onHttpServerRequest.bind(this));
this._httpServer.on('error', this._onHttpServerError.bind(this));
this._httpServer.listen(0);
// an arbitrary dict that users of this class can store values in to associate with this particular connection
this._session = {
sessionID: this.sessionID
};
// a collection of event names subscribed to by this connection
this._events = {}; // this._events[eventName] = true (value is arbitrary, but must be truthy)
debug("[%s] New connection from client", this._remoteAddress);
} | javascript | function EventedHTTPServerConnection(clientSocket) {
this.sessionID = uuid.generate(clientSocket.remoteAddress + ':' + clientSocket.remotePort);
this._remoteAddress = clientSocket.remoteAddress; // cache because it becomes undefined in 'onClientSocketClose'
this._pendingClientSocketData = bufferShim.alloc(0); // data received from client before HTTP proxy is fully setup
this._fullySetup = false; // true when we are finished establishing connections
this._writingResponse = false; // true while we are composing an HTTP response (so events can wait)
this._pendingEventData = bufferShim.alloc(0); // event data waiting to be sent until after an in-progress HTTP response is being written
// clientSocket is the socket connected to the actual iOS device
this._clientSocket = clientSocket;
this._clientSocket.on('data', this._onClientSocketData.bind(this));
this._clientSocket.on('close', this._onClientSocketClose.bind(this));
this._clientSocket.on('error', this._onClientSocketError.bind(this)); // we MUST register for this event, otherwise the error will bubble up to the top and crash the node process entirely.
// serverSocket is our connection to our own internal httpServer
this._serverSocket = null; // created after httpServer 'listening' event
// create our internal HTTP server for this connection that we will proxy data to and from
this._httpServer = http.createServer();
this._httpServer.timeout = 0; // clients expect to hold connections open as long as they want
this._httpServer.keepAliveTimeout = 0; // workaround for https://github.com/nodejs/node/issues/13391
this._httpServer.on('listening', this._onHttpServerListening.bind(this));
this._httpServer.on('request', this._onHttpServerRequest.bind(this));
this._httpServer.on('error', this._onHttpServerError.bind(this));
this._httpServer.listen(0);
// an arbitrary dict that users of this class can store values in to associate with this particular connection
this._session = {
sessionID: this.sessionID
};
// a collection of event names subscribed to by this connection
this._events = {}; // this._events[eventName] = true (value is arbitrary, but must be truthy)
debug("[%s] New connection from client", this._remoteAddress);
} | [
"function",
"EventedHTTPServerConnection",
"(",
"clientSocket",
")",
"{",
"this",
".",
"sessionID",
"=",
"uuid",
".",
"generate",
"(",
"clientSocket",
".",
"remoteAddress",
"+",
"':'",
"+",
"clientSocket",
".",
"remotePort",
")",
";",
"this",
".",
"_remoteAddress",
"=",
"clientSocket",
".",
"remoteAddress",
";",
"// cache because it becomes undefined in 'onClientSocketClose'",
"this",
".",
"_pendingClientSocketData",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"// data received from client before HTTP proxy is fully setup",
"this",
".",
"_fullySetup",
"=",
"false",
";",
"// true when we are finished establishing connections",
"this",
".",
"_writingResponse",
"=",
"false",
";",
"// true while we are composing an HTTP response (so events can wait)",
"this",
".",
"_pendingEventData",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"// event data waiting to be sent until after an in-progress HTTP response is being written",
"// clientSocket is the socket connected to the actual iOS device",
"this",
".",
"_clientSocket",
"=",
"clientSocket",
";",
"this",
".",
"_clientSocket",
".",
"on",
"(",
"'data'",
",",
"this",
".",
"_onClientSocketData",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_clientSocket",
".",
"on",
"(",
"'close'",
",",
"this",
".",
"_onClientSocketClose",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_clientSocket",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"_onClientSocketError",
".",
"bind",
"(",
"this",
")",
")",
";",
"// we MUST register for this event, otherwise the error will bubble up to the top and crash the node process entirely.",
"// serverSocket is our connection to our own internal httpServer",
"this",
".",
"_serverSocket",
"=",
"null",
";",
"// created after httpServer 'listening' event",
"// create our internal HTTP server for this connection that we will proxy data to and from",
"this",
".",
"_httpServer",
"=",
"http",
".",
"createServer",
"(",
")",
";",
"this",
".",
"_httpServer",
".",
"timeout",
"=",
"0",
";",
"// clients expect to hold connections open as long as they want",
"this",
".",
"_httpServer",
".",
"keepAliveTimeout",
"=",
"0",
";",
"// workaround for https://github.com/nodejs/node/issues/13391",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'listening'",
",",
"this",
".",
"_onHttpServerListening",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'request'",
",",
"this",
".",
"_onHttpServerRequest",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"_onHttpServerError",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_httpServer",
".",
"listen",
"(",
"0",
")",
";",
"// an arbitrary dict that users of this class can store values in to associate with this particular connection",
"this",
".",
"_session",
"=",
"{",
"sessionID",
":",
"this",
".",
"sessionID",
"}",
";",
"// a collection of event names subscribed to by this connection",
"this",
".",
"_events",
"=",
"{",
"}",
";",
"// this._events[eventName] = true (value is arbitrary, but must be truthy)",
"debug",
"(",
"\"[%s] New connection from client\"",
",",
"this",
".",
"_remoteAddress",
")",
";",
"}"
] | Manages a single iOS-initiated HTTP connection during its lifetime.
@event 'request' => function(request, response) { }
@event 'decrypt' => function(data, {decrypted.data}, session) { }
@event 'encrypt' => function(data, {encrypted.data}, session) { }
@event 'close' => function() { } | [
"Manages",
"a",
"single",
"iOS",
"-",
"initiated",
"HTTP",
"connection",
"during",
"its",
"lifetime",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/util/eventedhttp.js#L113-L150 |
7,648 | KhaosT/HAP-NodeJS | lib/Service.js | Service | function Service(displayName, UUID, subtype) {
if (!UUID) throw new Error("Services must be created with a valid UUID.");
this.displayName = displayName;
this.UUID = UUID;
this.subtype = subtype;
this.iid = null; // assigned later by our containing Accessory
this.characteristics = [];
this.optionalCharacteristics = [];
this.isHiddenService = false;
this.isPrimaryService = false;
this.linkedServices = [];
// every service has an optional Characteristic.Name property - we'll set it to our displayName
// if one was given
// if you don't provide a display name, some HomeKit apps may choose to hide the device.
if (displayName) {
// create the characteristic if necessary
var nameCharacteristic =
this.getCharacteristic(Characteristic.Name) ||
this.addCharacteristic(Characteristic.Name);
nameCharacteristic.setValue(displayName);
}
} | javascript | function Service(displayName, UUID, subtype) {
if (!UUID) throw new Error("Services must be created with a valid UUID.");
this.displayName = displayName;
this.UUID = UUID;
this.subtype = subtype;
this.iid = null; // assigned later by our containing Accessory
this.characteristics = [];
this.optionalCharacteristics = [];
this.isHiddenService = false;
this.isPrimaryService = false;
this.linkedServices = [];
// every service has an optional Characteristic.Name property - we'll set it to our displayName
// if one was given
// if you don't provide a display name, some HomeKit apps may choose to hide the device.
if (displayName) {
// create the characteristic if necessary
var nameCharacteristic =
this.getCharacteristic(Characteristic.Name) ||
this.addCharacteristic(Characteristic.Name);
nameCharacteristic.setValue(displayName);
}
} | [
"function",
"Service",
"(",
"displayName",
",",
"UUID",
",",
"subtype",
")",
"{",
"if",
"(",
"!",
"UUID",
")",
"throw",
"new",
"Error",
"(",
"\"Services must be created with a valid UUID.\"",
")",
";",
"this",
".",
"displayName",
"=",
"displayName",
";",
"this",
".",
"UUID",
"=",
"UUID",
";",
"this",
".",
"subtype",
"=",
"subtype",
";",
"this",
".",
"iid",
"=",
"null",
";",
"// assigned later by our containing Accessory",
"this",
".",
"characteristics",
"=",
"[",
"]",
";",
"this",
".",
"optionalCharacteristics",
"=",
"[",
"]",
";",
"this",
".",
"isHiddenService",
"=",
"false",
";",
"this",
".",
"isPrimaryService",
"=",
"false",
";",
"this",
".",
"linkedServices",
"=",
"[",
"]",
";",
"// every service has an optional Characteristic.Name property - we'll set it to our displayName",
"// if one was given",
"// if you don't provide a display name, some HomeKit apps may choose to hide the device.",
"if",
"(",
"displayName",
")",
"{",
"// create the characteristic if necessary",
"var",
"nameCharacteristic",
"=",
"this",
".",
"getCharacteristic",
"(",
"Characteristic",
".",
"Name",
")",
"||",
"this",
".",
"addCharacteristic",
"(",
"Characteristic",
".",
"Name",
")",
";",
"nameCharacteristic",
".",
"setValue",
"(",
"displayName",
")",
";",
"}",
"}"
] | Service represents a set of grouped values necessary to provide a logical function. For instance, a
"Door Lock Mechanism" service might contain two values, one for the "desired lock state" and one for the
"current lock state". A particular Service is distinguished from others by its "type", which is a UUID.
HomeKit provides a set of known Service UUIDs defined in HomeKitTypes.js along with a corresponding
concrete subclass that you can instantiate directly to setup the necessary values. These natively-supported
Services are expected to contain a particular set of Characteristics.
Unlike Characteristics, where you cannot have two Characteristics with the same UUID in the same Service,
you can actually have multiple Services with the same UUID in a single Accessory. For instance, imagine
a Garage Door Opener with both a "security light" and a "backlight" for the display. Each light could be
a "Lightbulb" Service with the same UUID. To account for this situation, we define an extra "subtype"
property on Service, that can be a string or other string-convertible object that uniquely identifies the
Service among its peers in an Accessory. For instance, you might have `service1.subtype = 'security_light'`
for one and `service2.subtype = 'backlight'` for the other.
You can also define custom Services by providing your own UUID for the type that you generate yourself.
Custom Services can contain an arbitrary set of Characteristics, but Siri will likely not be able to
work with these.
@event 'characteristic-change' => function({characteristic, oldValue, newValue, context}) { }
Emitted after a change in the value of one of our Characteristics has occurred. | [
"Service",
"represents",
"a",
"set",
"of",
"grouped",
"values",
"necessary",
"to",
"provide",
"a",
"logical",
"function",
".",
"For",
"instance",
"a",
"Door",
"Lock",
"Mechanism",
"service",
"might",
"contain",
"two",
"values",
"one",
"for",
"the",
"desired",
"lock",
"state",
"and",
"one",
"for",
"the",
"current",
"lock",
"state",
".",
"A",
"particular",
"Service",
"is",
"distinguished",
"from",
"others",
"by",
"its",
"type",
"which",
"is",
"a",
"UUID",
".",
"HomeKit",
"provides",
"a",
"set",
"of",
"known",
"Service",
"UUIDs",
"defined",
"in",
"HomeKitTypes",
".",
"js",
"along",
"with",
"a",
"corresponding",
"concrete",
"subclass",
"that",
"you",
"can",
"instantiate",
"directly",
"to",
"setup",
"the",
"necessary",
"values",
".",
"These",
"natively",
"-",
"supported",
"Services",
"are",
"expected",
"to",
"contain",
"a",
"particular",
"set",
"of",
"Characteristics",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/Service.js#L36-L62 |
7,649 | KhaosT/HAP-NodeJS | lib/util/clone.js | clone | function clone(object, extend) {
var cloned = {};
for (var key in object) {
cloned[key] = object[key];
}
for (var key in extend) {
cloned[key] = extend[key];
}
return cloned;
} | javascript | function clone(object, extend) {
var cloned = {};
for (var key in object) {
cloned[key] = object[key];
}
for (var key in extend) {
cloned[key] = extend[key];
}
return cloned;
} | [
"function",
"clone",
"(",
"object",
",",
"extend",
")",
"{",
"var",
"cloned",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"object",
")",
"{",
"cloned",
"[",
"key",
"]",
"=",
"object",
"[",
"key",
"]",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"extend",
")",
"{",
"cloned",
"[",
"key",
"]",
"=",
"extend",
"[",
"key",
"]",
";",
"}",
"return",
"cloned",
";",
"}"
] | A simple clone function that also allows you to pass an "extend" object whose properties will be
added to the cloned copy of the original object passed. | [
"A",
"simple",
"clone",
"function",
"that",
"also",
"allows",
"you",
"to",
"pass",
"an",
"extend",
"object",
"whose",
"properties",
"will",
"be",
"added",
"to",
"the",
"cloned",
"copy",
"of",
"the",
"original",
"object",
"passed",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/util/clone.js#L12-L25 |
7,650 | KhaosT/HAP-NodeJS | lib/Accessory.js | Accessory | function Accessory(displayName, UUID) {
if (!displayName) throw new Error("Accessories must be created with a non-empty displayName.");
if (!UUID) throw new Error("Accessories must be created with a valid UUID.");
if (!uuid.isValid(UUID)) throw new Error("UUID '" + UUID + "' is not a valid UUID. Try using the provided 'generateUUID' function to create a valid UUID from any arbitrary string, like a serial number.");
this.displayName = displayName;
this.UUID = UUID;
this.aid = null; // assigned by us in assignIDs() or by a Bridge
this._isBridge = false; // true if we are a Bridge (creating a new instance of the Bridge subclass sets this to true)
this.bridged = false; // true if we are hosted "behind" a Bridge Accessory
this.bridgedAccessories = []; // If we are a Bridge, these are the Accessories we are bridging
this.reachable = true;
this.category = Accessory.Categories.OTHER;
this.services = []; // of Service
this.cameraSource = null;
this.shouldPurgeUnusedIDs = true; // Purge unused ids by default
// create our initial "Accessory Information" Service that all Accessories are expected to have
this
.addService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Name, displayName)
.setCharacteristic(Characteristic.Manufacturer, "Default-Manufacturer")
.setCharacteristic(Characteristic.Model, "Default-Model")
.setCharacteristic(Characteristic.SerialNumber, "Default-SerialNumber")
.setCharacteristic(Characteristic.FirmwareRevision, "1.0");
// sign up for when iOS attempts to "set" the Identify characteristic - this means a paired device wishes
// for us to identify ourselves (as opposed to an unpaired device - that case is handled by HAPServer 'identify' event)
this
.getService(Service.AccessoryInformation)
.getCharacteristic(Characteristic.Identify)
.on('set', function(value, callback) {
if (value) {
var paired = true;
this._identificationRequest(paired, callback);
}
}.bind(this));
} | javascript | function Accessory(displayName, UUID) {
if (!displayName) throw new Error("Accessories must be created with a non-empty displayName.");
if (!UUID) throw new Error("Accessories must be created with a valid UUID.");
if (!uuid.isValid(UUID)) throw new Error("UUID '" + UUID + "' is not a valid UUID. Try using the provided 'generateUUID' function to create a valid UUID from any arbitrary string, like a serial number.");
this.displayName = displayName;
this.UUID = UUID;
this.aid = null; // assigned by us in assignIDs() or by a Bridge
this._isBridge = false; // true if we are a Bridge (creating a new instance of the Bridge subclass sets this to true)
this.bridged = false; // true if we are hosted "behind" a Bridge Accessory
this.bridgedAccessories = []; // If we are a Bridge, these are the Accessories we are bridging
this.reachable = true;
this.category = Accessory.Categories.OTHER;
this.services = []; // of Service
this.cameraSource = null;
this.shouldPurgeUnusedIDs = true; // Purge unused ids by default
// create our initial "Accessory Information" Service that all Accessories are expected to have
this
.addService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Name, displayName)
.setCharacteristic(Characteristic.Manufacturer, "Default-Manufacturer")
.setCharacteristic(Characteristic.Model, "Default-Model")
.setCharacteristic(Characteristic.SerialNumber, "Default-SerialNumber")
.setCharacteristic(Characteristic.FirmwareRevision, "1.0");
// sign up for when iOS attempts to "set" the Identify characteristic - this means a paired device wishes
// for us to identify ourselves (as opposed to an unpaired device - that case is handled by HAPServer 'identify' event)
this
.getService(Service.AccessoryInformation)
.getCharacteristic(Characteristic.Identify)
.on('set', function(value, callback) {
if (value) {
var paired = true;
this._identificationRequest(paired, callback);
}
}.bind(this));
} | [
"function",
"Accessory",
"(",
"displayName",
",",
"UUID",
")",
"{",
"if",
"(",
"!",
"displayName",
")",
"throw",
"new",
"Error",
"(",
"\"Accessories must be created with a non-empty displayName.\"",
")",
";",
"if",
"(",
"!",
"UUID",
")",
"throw",
"new",
"Error",
"(",
"\"Accessories must be created with a valid UUID.\"",
")",
";",
"if",
"(",
"!",
"uuid",
".",
"isValid",
"(",
"UUID",
")",
")",
"throw",
"new",
"Error",
"(",
"\"UUID '\"",
"+",
"UUID",
"+",
"\"' is not a valid UUID. Try using the provided 'generateUUID' function to create a valid UUID from any arbitrary string, like a serial number.\"",
")",
";",
"this",
".",
"displayName",
"=",
"displayName",
";",
"this",
".",
"UUID",
"=",
"UUID",
";",
"this",
".",
"aid",
"=",
"null",
";",
"// assigned by us in assignIDs() or by a Bridge",
"this",
".",
"_isBridge",
"=",
"false",
";",
"// true if we are a Bridge (creating a new instance of the Bridge subclass sets this to true)",
"this",
".",
"bridged",
"=",
"false",
";",
"// true if we are hosted \"behind\" a Bridge Accessory",
"this",
".",
"bridgedAccessories",
"=",
"[",
"]",
";",
"// If we are a Bridge, these are the Accessories we are bridging",
"this",
".",
"reachable",
"=",
"true",
";",
"this",
".",
"category",
"=",
"Accessory",
".",
"Categories",
".",
"OTHER",
";",
"this",
".",
"services",
"=",
"[",
"]",
";",
"// of Service",
"this",
".",
"cameraSource",
"=",
"null",
";",
"this",
".",
"shouldPurgeUnusedIDs",
"=",
"true",
";",
"// Purge unused ids by default",
"// create our initial \"Accessory Information\" Service that all Accessories are expected to have",
"this",
".",
"addService",
"(",
"Service",
".",
"AccessoryInformation",
")",
".",
"setCharacteristic",
"(",
"Characteristic",
".",
"Name",
",",
"displayName",
")",
".",
"setCharacteristic",
"(",
"Characteristic",
".",
"Manufacturer",
",",
"\"Default-Manufacturer\"",
")",
".",
"setCharacteristic",
"(",
"Characteristic",
".",
"Model",
",",
"\"Default-Model\"",
")",
".",
"setCharacteristic",
"(",
"Characteristic",
".",
"SerialNumber",
",",
"\"Default-SerialNumber\"",
")",
".",
"setCharacteristic",
"(",
"Characteristic",
".",
"FirmwareRevision",
",",
"\"1.0\"",
")",
";",
"// sign up for when iOS attempts to \"set\" the Identify characteristic - this means a paired device wishes",
"// for us to identify ourselves (as opposed to an unpaired device - that case is handled by HAPServer 'identify' event)",
"this",
".",
"getService",
"(",
"Service",
".",
"AccessoryInformation",
")",
".",
"getCharacteristic",
"(",
"Characteristic",
".",
"Identify",
")",
".",
"on",
"(",
"'set'",
",",
"function",
"(",
"value",
",",
"callback",
")",
"{",
"if",
"(",
"value",
")",
"{",
"var",
"paired",
"=",
"true",
";",
"this",
".",
"_identificationRequest",
"(",
"paired",
",",
"callback",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Accessory is a virtual HomeKit device. It can publish an associated HAP server for iOS devices to communicate
with - or it can run behind another "Bridge" Accessory server.
Bridged Accessories in this implementation must have a UUID that is unique among all other Accessories that
are hosted by the Bridge. This UUID must be "stable" and unchanging, even when the server is restarted. This
is required so that the Bridge can provide consistent "Accessory IDs" (aid) and "Instance IDs" (iid) for all
Accessories, Services, and Characteristics for iOS clients to reference later.
@event 'identify' => function(paired, callback(err)) { }
Emitted when an iOS device wishes for this Accessory to identify itself. If `paired` is false, then
this device is currently browsing for Accessories in the system-provided "Add Accessory" screen. If
`paired` is true, then this is a device that has already paired with us. Note that if `paired` is true,
listening for this event is a shortcut for the underlying mechanism of setting the `Identify` Characteristic:
`getService(Service.AccessoryInformation).getCharacteristic(Characteristic.Identify).on('set', ...)`
You must call the callback for identification to be successful.
@event 'service-characteristic-change' => function({service, characteristic, oldValue, newValue, context}) { }
Emitted after a change in the value of one of the provided Service's Characteristics. | [
"Accessory",
"is",
"a",
"virtual",
"HomeKit",
"device",
".",
"It",
"can",
"publish",
"an",
"associated",
"HAP",
"server",
"for",
"iOS",
"devices",
"to",
"communicate",
"with",
"-",
"or",
"it",
"can",
"run",
"behind",
"another",
"Bridge",
"Accessory",
"server",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/Accessory.js#L47-L85 |
7,651 | KhaosT/HAP-NodeJS | lib/HAPServer.js | HAPServer | function HAPServer(accessoryInfo, relayServer) {
this.accessoryInfo = accessoryInfo;
this.allowInsecureRequest = false;
// internal server that does all the actual communication
this._httpServer = new EventedHTTPServer();
this._httpServer.on('listening', this._onListening.bind(this));
this._httpServer.on('request', this._onRequest.bind(this));
this._httpServer.on('encrypt', this._onEncrypt.bind(this));
this._httpServer.on('decrypt', this._onDecrypt.bind(this));
this._httpServer.on('session-close', this._onSessionClose.bind(this));
if (relayServer) {
this._relayServer = relayServer;
this._relayServer.on('request', this._onRemoteRequest.bind(this));
this._relayServer.on('encrypt', this._onEncrypt.bind(this));
this._relayServer.on('decrypt', this._onDecrypt.bind(this));
}
// so iOS is very reluctant to actually disconnect HAP connections (as in, sending a FIN packet).
// For instance, if you turn off wifi on your phone, it will not close the connection, instead
// it will leave it open and hope that it's still valid when it returns to the network. And Node,
// by itself, does not ever "discover" that the connection has been closed behind it, until a
// potentially very long system-level socket timeout (like, days). To work around this, we have
// invented a manual "keepalive" mechanism where we send "empty" events perodicially, such that
// when Node attempts to write to the socket, it discovers that it's been disconnected after
// an additional one-minute timeout (this timeout appears to be hardcoded).
this._keepAliveTimerID = setInterval(this._onKeepAliveTimerTick.bind(this), 1000 * 60 * 10); // send keepalive every 10 minutes
} | javascript | function HAPServer(accessoryInfo, relayServer) {
this.accessoryInfo = accessoryInfo;
this.allowInsecureRequest = false;
// internal server that does all the actual communication
this._httpServer = new EventedHTTPServer();
this._httpServer.on('listening', this._onListening.bind(this));
this._httpServer.on('request', this._onRequest.bind(this));
this._httpServer.on('encrypt', this._onEncrypt.bind(this));
this._httpServer.on('decrypt', this._onDecrypt.bind(this));
this._httpServer.on('session-close', this._onSessionClose.bind(this));
if (relayServer) {
this._relayServer = relayServer;
this._relayServer.on('request', this._onRemoteRequest.bind(this));
this._relayServer.on('encrypt', this._onEncrypt.bind(this));
this._relayServer.on('decrypt', this._onDecrypt.bind(this));
}
// so iOS is very reluctant to actually disconnect HAP connections (as in, sending a FIN packet).
// For instance, if you turn off wifi on your phone, it will not close the connection, instead
// it will leave it open and hope that it's still valid when it returns to the network. And Node,
// by itself, does not ever "discover" that the connection has been closed behind it, until a
// potentially very long system-level socket timeout (like, days). To work around this, we have
// invented a manual "keepalive" mechanism where we send "empty" events perodicially, such that
// when Node attempts to write to the socket, it discovers that it's been disconnected after
// an additional one-minute timeout (this timeout appears to be hardcoded).
this._keepAliveTimerID = setInterval(this._onKeepAliveTimerTick.bind(this), 1000 * 60 * 10); // send keepalive every 10 minutes
} | [
"function",
"HAPServer",
"(",
"accessoryInfo",
",",
"relayServer",
")",
"{",
"this",
".",
"accessoryInfo",
"=",
"accessoryInfo",
";",
"this",
".",
"allowInsecureRequest",
"=",
"false",
";",
"// internal server that does all the actual communication",
"this",
".",
"_httpServer",
"=",
"new",
"EventedHTTPServer",
"(",
")",
";",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'listening'",
",",
"this",
".",
"_onListening",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'request'",
",",
"this",
".",
"_onRequest",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'encrypt'",
",",
"this",
".",
"_onEncrypt",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'decrypt'",
",",
"this",
".",
"_onDecrypt",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_httpServer",
".",
"on",
"(",
"'session-close'",
",",
"this",
".",
"_onSessionClose",
".",
"bind",
"(",
"this",
")",
")",
";",
"if",
"(",
"relayServer",
")",
"{",
"this",
".",
"_relayServer",
"=",
"relayServer",
";",
"this",
".",
"_relayServer",
".",
"on",
"(",
"'request'",
",",
"this",
".",
"_onRemoteRequest",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_relayServer",
".",
"on",
"(",
"'encrypt'",
",",
"this",
".",
"_onEncrypt",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_relayServer",
".",
"on",
"(",
"'decrypt'",
",",
"this",
".",
"_onDecrypt",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"// so iOS is very reluctant to actually disconnect HAP connections (as in, sending a FIN packet).",
"// For instance, if you turn off wifi on your phone, it will not close the connection, instead",
"// it will leave it open and hope that it's still valid when it returns to the network. And Node,",
"// by itself, does not ever \"discover\" that the connection has been closed behind it, until a",
"// potentially very long system-level socket timeout (like, days). To work around this, we have",
"// invented a manual \"keepalive\" mechanism where we send \"empty\" events perodicially, such that",
"// when Node attempts to write to the socket, it discovers that it's been disconnected after",
"// an additional one-minute timeout (this timeout appears to be hardcoded).",
"this",
".",
"_keepAliveTimerID",
"=",
"setInterval",
"(",
"this",
".",
"_onKeepAliveTimerTick",
".",
"bind",
"(",
"this",
")",
",",
"1000",
"*",
"60",
"*",
"10",
")",
";",
"// send keepalive every 10 minutes",
"}"
] | The actual HAP server that iOS devices talk to.
Notes
-----
It turns out that the IP-based version of HomeKit's HAP protocol operates over a sort of pseudo-HTTP.
Accessories are meant to host a TCP socket server that initially behaves exactly as an HTTP/1.1 server.
So iOS devices will open up a long-lived connection to this server and begin issuing HTTP requests.
So far, this conforms with HTTP/1.1 Keepalive. However, after the "pairing" process is complete, the
connection is expected to be "upgraded" to support full-packet encryption of both HTTP headers and data.
This encryption is NOT SSL. It is a customized ChaCha20+Poly1305 encryption layer.
Additionally, this "HTTP Server" supports sending "event" responses at any time without warning. The iOS
device simply keeps the connection open after it's finished with HTTP request/response traffic, and while
the connection is open, the server can elect to issue "EVENT/1.0 200 OK" HTTP-style responses. These are
typically sent to inform the iOS device of a characteristic change for the accessory (like "Door was Unlocked").
See eventedhttp.js for more detail on the implementation of this protocol.
@event 'listening' => function() { }
Emitted when the server is fully set up and ready to receive connections.
@event 'identify' => function(callback(err)) { }
Emitted when a client wishes for this server to identify itself before pairing. You must call the
callback to respond to the client with success.
@event 'pair' => function(username, publicKey, callback(err)) { }
This event is emitted when a client completes the "pairing" process and exchanges encryption keys.
Note that this does not mean the "Add Accessory" process in iOS has completed. You must call the
callback to complete the process.
@event 'verify' => function() { }
This event is emitted after a client successfully completes the "verify" process, thereby authenticating
itself to an Accessory as a known-paired client.
@event 'unpair' => function(username, callback(err)) { }
This event is emitted when a client has requested us to "remove their pairing info", or basically to unpair.
You must call the callback to complete the process.
@event 'accessories' => function(callback(err, accessories)) { }
This event is emitted when a client requests the complete representation of Accessory data for
this Accessory (for instance, what services, characteristics, etc. are supported) and any bridged
Accessories in the case of a Bridge Accessory. The listener must call the provided callback function
when the accessory data is ready. We will automatically JSON.stringify the data.
@event 'get-characteristics' => function(data, events, callback(err, characteristics), remote, connectionID) { }
This event is emitted when a client wishes to retrieve the current value of one or more characteristics.
The listener must call the provided callback function when the values are ready. iOS clients can typically
wait up to 10 seconds for this call to return. We will automatically JSON.stringify the data (which must
be an array) and wrap it in an object with a top-level "characteristics" property.
@event 'set-characteristics' => function(data, events, callback(err), remote, connectionID) { }
This event is emitted when a client wishes to set the current value of one or more characteristics and/or
subscribe to one or more events. The 'events' param is an initially-empty object, associated with the current
connection, on which you may store event registration keys for later processing. The listener must call
the provided callback when the request has been processed. | [
"The",
"actual",
"HAP",
"server",
"that",
"iOS",
"devices",
"talk",
"to",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/HAPServer.js#L81-L109 |
7,652 | KhaosT/HAP-NodeJS | lib/HAPServer.js | HAPEncryption | function HAPEncryption() {
// initialize member vars with null-object values
this.clientPublicKey = bufferShim.alloc(0);
this.secretKey = bufferShim.alloc(0);
this.publicKey = bufferShim.alloc(0);
this.sharedSec = bufferShim.alloc(0);
this.hkdfPairEncKey = bufferShim.alloc(0);
this.accessoryToControllerCount = { value: 0 };
this.controllerToAccessoryCount = { value: 0 };
this.accessoryToControllerKey = bufferShim.alloc(0);
this.controllerToAccessoryKey = bufferShim.alloc(0);
this.extraInfo = {};
} | javascript | function HAPEncryption() {
// initialize member vars with null-object values
this.clientPublicKey = bufferShim.alloc(0);
this.secretKey = bufferShim.alloc(0);
this.publicKey = bufferShim.alloc(0);
this.sharedSec = bufferShim.alloc(0);
this.hkdfPairEncKey = bufferShim.alloc(0);
this.accessoryToControllerCount = { value: 0 };
this.controllerToAccessoryCount = { value: 0 };
this.accessoryToControllerKey = bufferShim.alloc(0);
this.controllerToAccessoryKey = bufferShim.alloc(0);
this.extraInfo = {};
} | [
"function",
"HAPEncryption",
"(",
")",
"{",
"// initialize member vars with null-object values",
"this",
".",
"clientPublicKey",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"secretKey",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"publicKey",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"sharedSec",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"hkdfPairEncKey",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"accessoryToControllerCount",
"=",
"{",
"value",
":",
"0",
"}",
";",
"this",
".",
"controllerToAccessoryCount",
"=",
"{",
"value",
":",
"0",
"}",
";",
"this",
".",
"accessoryToControllerKey",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"controllerToAccessoryKey",
"=",
"bufferShim",
".",
"alloc",
"(",
"0",
")",
";",
"this",
".",
"extraInfo",
"=",
"{",
"}",
";",
"}"
] | Simple struct to hold vars needed to support HAP encryption. | [
"Simple",
"struct",
"to",
"hold",
"vars",
"needed",
"to",
"support",
"HAP",
"encryption",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/HAPServer.js#L1107-L1119 |
7,653 | KhaosT/HAP-NodeJS | lib/Advertiser.js | Advertiser | function Advertiser(accessoryInfo, mdnsConfig) {
this.accessoryInfo = accessoryInfo;
this._bonjourService = bonjour(mdnsConfig);
this._advertisement = null;
this._setupHash = this._computeSetupHash();
} | javascript | function Advertiser(accessoryInfo, mdnsConfig) {
this.accessoryInfo = accessoryInfo;
this._bonjourService = bonjour(mdnsConfig);
this._advertisement = null;
this._setupHash = this._computeSetupHash();
} | [
"function",
"Advertiser",
"(",
"accessoryInfo",
",",
"mdnsConfig",
")",
"{",
"this",
".",
"accessoryInfo",
"=",
"accessoryInfo",
";",
"this",
".",
"_bonjourService",
"=",
"bonjour",
"(",
"mdnsConfig",
")",
";",
"this",
".",
"_advertisement",
"=",
"null",
";",
"this",
".",
"_setupHash",
"=",
"this",
".",
"_computeSetupHash",
"(",
")",
";",
"}"
] | Advertiser uses mdns to broadcast the presence of an Accessory to the local network.
Note that as of iOS 9, an accessory can only pair with a single client. Instead of pairing your
accessories with multiple iOS devices in your home, Apple intends for you to use Home Sharing.
To support this requirement, we provide the ability to be "discoverable" or not (via a "service flag" on the
mdns payload). | [
"Advertiser",
"uses",
"mdns",
"to",
"broadcast",
"the",
"presence",
"of",
"an",
"Accessory",
"to",
"the",
"local",
"network",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/Advertiser.js#L21-L27 |
7,654 | KhaosT/HAP-NodeJS | lib/AccessoryLoader.js | loadDirectory | function loadDirectory(dir) {
// exported accessory objects loaded from this dir
var accessories = [];
fs.readdirSync(dir).forEach(function(file) {
// "Accessories" are modules that export a single accessory.
if (file.split('_').pop() === 'accessory.js') {
debug('Parsing accessory: %s', file);
var loadedAccessory = require(path.join(dir, file)).accessory;
accessories.push(loadedAccessory);
}
// "Accessory Factories" are modules that export an array of accessories.
else if (file.split('_').pop() === 'accfactory.js') {
debug('Parsing accessory factory: %s', file);
// should return an array of objects { accessory: accessory-json }
var loadedAccessories = require(path.join(dir, file));
accessories = accessories.concat(loadedAccessories);
}
});
// now we need to coerce all accessory objects into instances of Accessory (some or all of them may
// be object-literal JSON-style accessories)
return accessories.map(function(accessory) {
if(accessory === null || accessory === undefined) { //check if accessory is not empty
console.log("Invalid accessory!");
return false;
} else {
return (accessory instanceof Accessory) ? accessory : parseAccessoryJSON(accessory);
}
}).filter(function(accessory) { return accessory ? true : false; });
} | javascript | function loadDirectory(dir) {
// exported accessory objects loaded from this dir
var accessories = [];
fs.readdirSync(dir).forEach(function(file) {
// "Accessories" are modules that export a single accessory.
if (file.split('_').pop() === 'accessory.js') {
debug('Parsing accessory: %s', file);
var loadedAccessory = require(path.join(dir, file)).accessory;
accessories.push(loadedAccessory);
}
// "Accessory Factories" are modules that export an array of accessories.
else if (file.split('_').pop() === 'accfactory.js') {
debug('Parsing accessory factory: %s', file);
// should return an array of objects { accessory: accessory-json }
var loadedAccessories = require(path.join(dir, file));
accessories = accessories.concat(loadedAccessories);
}
});
// now we need to coerce all accessory objects into instances of Accessory (some or all of them may
// be object-literal JSON-style accessories)
return accessories.map(function(accessory) {
if(accessory === null || accessory === undefined) { //check if accessory is not empty
console.log("Invalid accessory!");
return false;
} else {
return (accessory instanceof Accessory) ? accessory : parseAccessoryJSON(accessory);
}
}).filter(function(accessory) { return accessory ? true : false; });
} | [
"function",
"loadDirectory",
"(",
"dir",
")",
"{",
"// exported accessory objects loaded from this dir",
"var",
"accessories",
"=",
"[",
"]",
";",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"// \"Accessories\" are modules that export a single accessory.",
"if",
"(",
"file",
".",
"split",
"(",
"'_'",
")",
".",
"pop",
"(",
")",
"===",
"'accessory.js'",
")",
"{",
"debug",
"(",
"'Parsing accessory: %s'",
",",
"file",
")",
";",
"var",
"loadedAccessory",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
")",
".",
"accessory",
";",
"accessories",
".",
"push",
"(",
"loadedAccessory",
")",
";",
"}",
"// \"Accessory Factories\" are modules that export an array of accessories.",
"else",
"if",
"(",
"file",
".",
"split",
"(",
"'_'",
")",
".",
"pop",
"(",
")",
"===",
"'accfactory.js'",
")",
"{",
"debug",
"(",
"'Parsing accessory factory: %s'",
",",
"file",
")",
";",
"// should return an array of objects { accessory: accessory-json }",
"var",
"loadedAccessories",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
")",
";",
"accessories",
"=",
"accessories",
".",
"concat",
"(",
"loadedAccessories",
")",
";",
"}",
"}",
")",
";",
"// now we need to coerce all accessory objects into instances of Accessory (some or all of them may",
"// be object-literal JSON-style accessories)",
"return",
"accessories",
".",
"map",
"(",
"function",
"(",
"accessory",
")",
"{",
"if",
"(",
"accessory",
"===",
"null",
"||",
"accessory",
"===",
"undefined",
")",
"{",
"//check if accessory is not empty",
"console",
".",
"log",
"(",
"\"Invalid accessory!\"",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"(",
"accessory",
"instanceof",
"Accessory",
")",
"?",
"accessory",
":",
"parseAccessoryJSON",
"(",
"accessory",
")",
";",
"}",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"accessory",
")",
"{",
"return",
"accessory",
"?",
"true",
":",
"false",
";",
"}",
")",
";",
"}"
] | Loads all accessories from the given folder. Handles object-literal-style accessories, "accessory factories",
and new-API style modules. | [
"Loads",
"all",
"accessories",
"from",
"the",
"given",
"folder",
".",
"Handles",
"object",
"-",
"literal",
"-",
"style",
"accessories",
"accessory",
"factories",
"and",
"new",
"-",
"API",
"style",
"modules",
"."
] | 1862f73d495c7f25d3ed812abac4be4c1d2dee34 | https://github.com/KhaosT/HAP-NodeJS/blob/1862f73d495c7f25d3ed812abac4be4c1d2dee34/lib/AccessoryLoader.js#L23-L56 |
7,655 | matrix-org/matrix-js-sdk | src/timeline-window.js | TimelineWindow | function TimelineWindow(client, timelineSet, opts) {
opts = opts || {};
this._client = client;
this._timelineSet = timelineSet;
// these will be TimelineIndex objects; they delineate the 'start' and
// 'end' of the window.
//
// _start.index is inclusive; _end.index is exclusive.
this._start = null;
this._end = null;
this._eventCount = 0;
this._windowLimit = opts.windowLimit || 1000;
} | javascript | function TimelineWindow(client, timelineSet, opts) {
opts = opts || {};
this._client = client;
this._timelineSet = timelineSet;
// these will be TimelineIndex objects; they delineate the 'start' and
// 'end' of the window.
//
// _start.index is inclusive; _end.index is exclusive.
this._start = null;
this._end = null;
this._eventCount = 0;
this._windowLimit = opts.windowLimit || 1000;
} | [
"function",
"TimelineWindow",
"(",
"client",
",",
"timelineSet",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"_client",
"=",
"client",
";",
"this",
".",
"_timelineSet",
"=",
"timelineSet",
";",
"// these will be TimelineIndex objects; they delineate the 'start' and",
"// 'end' of the window.",
"//",
"// _start.index is inclusive; _end.index is exclusive.",
"this",
".",
"_start",
"=",
"null",
";",
"this",
".",
"_end",
"=",
"null",
";",
"this",
".",
"_eventCount",
"=",
"0",
";",
"this",
".",
"_windowLimit",
"=",
"opts",
".",
"windowLimit",
"||",
"1000",
";",
"}"
] | Construct a TimelineWindow.
<p>This abstracts the separate timelines in a Matrix {@link
module:models/room|Room} into a single iterable thing. It keeps track of
the start and endpoints of the window, which can be advanced with the help
of pagination requests.
<p>Before the window is useful, it must be initialised by calling {@link
module:timeline-window~TimelineWindow#load|load}.
<p>Note that the window will not automatically extend itself when new events
are received from /sync; you should arrange to call {@link
module:timeline-window~TimelineWindow#paginate|paginate} on {@link
module:client~MatrixClient.event:"Room.timeline"|Room.timeline} events.
@param {MatrixClient} client MatrixClient to be used for context/pagination
requests.
@param {EventTimelineSet} timelineSet The timelineSet to track
@param {Object} [opts] Configuration options for this window
@param {number} [opts.windowLimit = 1000] maximum number of events to keep
in the window. If more events are retrieved via pagination requests,
excess events will be dropped from the other end of the window.
@constructor | [
"Construct",
"a",
"TimelineWindow",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/timeline-window.js#L69-L83 |
7,656 | matrix-org/matrix-js-sdk | src/timeline-window.js | function(timeline) {
let eventIndex;
const events = timeline.getEvents();
if (!initialEventId) {
// we were looking for the live timeline: initialise to the end
eventIndex = events.length;
} else {
for (let i = 0; i < events.length; i++) {
if (events[i].getId() == initialEventId) {
eventIndex = i;
break;
}
}
if (eventIndex === undefined) {
throw new Error("getEventTimeline result didn't include requested event");
}
}
const endIndex = Math.min(events.length,
eventIndex + Math.ceil(initialWindowSize / 2));
const startIndex = Math.max(0, endIndex - initialWindowSize);
self._start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());
self._end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());
self._eventCount = endIndex - startIndex;
} | javascript | function(timeline) {
let eventIndex;
const events = timeline.getEvents();
if (!initialEventId) {
// we were looking for the live timeline: initialise to the end
eventIndex = events.length;
} else {
for (let i = 0; i < events.length; i++) {
if (events[i].getId() == initialEventId) {
eventIndex = i;
break;
}
}
if (eventIndex === undefined) {
throw new Error("getEventTimeline result didn't include requested event");
}
}
const endIndex = Math.min(events.length,
eventIndex + Math.ceil(initialWindowSize / 2));
const startIndex = Math.max(0, endIndex - initialWindowSize);
self._start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());
self._end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());
self._eventCount = endIndex - startIndex;
} | [
"function",
"(",
"timeline",
")",
"{",
"let",
"eventIndex",
";",
"const",
"events",
"=",
"timeline",
".",
"getEvents",
"(",
")",
";",
"if",
"(",
"!",
"initialEventId",
")",
"{",
"// we were looking for the live timeline: initialise to the end",
"eventIndex",
"=",
"events",
".",
"length",
";",
"}",
"else",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"events",
"[",
"i",
"]",
".",
"getId",
"(",
")",
"==",
"initialEventId",
")",
"{",
"eventIndex",
"=",
"i",
";",
"break",
";",
"}",
"}",
"if",
"(",
"eventIndex",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"getEventTimeline result didn't include requested event\"",
")",
";",
"}",
"}",
"const",
"endIndex",
"=",
"Math",
".",
"min",
"(",
"events",
".",
"length",
",",
"eventIndex",
"+",
"Math",
".",
"ceil",
"(",
"initialWindowSize",
"/",
"2",
")",
")",
";",
"const",
"startIndex",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"endIndex",
"-",
"initialWindowSize",
")",
";",
"self",
".",
"_start",
"=",
"new",
"TimelineIndex",
"(",
"timeline",
",",
"startIndex",
"-",
"timeline",
".",
"getBaseIndex",
"(",
")",
")",
";",
"self",
".",
"_end",
"=",
"new",
"TimelineIndex",
"(",
"timeline",
",",
"endIndex",
"-",
"timeline",
".",
"getBaseIndex",
"(",
")",
")",
";",
"self",
".",
"_eventCount",
"=",
"endIndex",
"-",
"startIndex",
";",
"}"
] | given an EventTimeline, find the event we were looking for, and initialise our fields so that the event in question is in the middle of the window. | [
"given",
"an",
"EventTimeline",
"find",
"the",
"event",
"we",
"were",
"looking",
"for",
"and",
"initialise",
"our",
"fields",
"so",
"that",
"the",
"event",
"in",
"question",
"is",
"in",
"the",
"middle",
"of",
"the",
"window",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/timeline-window.js#L100-L127 |
|
7,657 | matrix-org/matrix-js-sdk | spec/integ/megolm-integ.spec.js | createOlmSession | function createOlmSession(olmAccount, recipientTestClient) {
return recipientTestClient.awaitOneTimeKeyUpload().then((keys) => {
const otkId = utils.keys(keys)[0];
const otk = keys[otkId];
const session = new global.Olm.Session();
session.create_outbound(
olmAccount, recipientTestClient.getDeviceKey(), otk.key,
);
return session;
});
} | javascript | function createOlmSession(olmAccount, recipientTestClient) {
return recipientTestClient.awaitOneTimeKeyUpload().then((keys) => {
const otkId = utils.keys(keys)[0];
const otk = keys[otkId];
const session = new global.Olm.Session();
session.create_outbound(
olmAccount, recipientTestClient.getDeviceKey(), otk.key,
);
return session;
});
} | [
"function",
"createOlmSession",
"(",
"olmAccount",
",",
"recipientTestClient",
")",
"{",
"return",
"recipientTestClient",
".",
"awaitOneTimeKeyUpload",
"(",
")",
".",
"then",
"(",
"(",
"keys",
")",
"=>",
"{",
"const",
"otkId",
"=",
"utils",
".",
"keys",
"(",
"keys",
")",
"[",
"0",
"]",
";",
"const",
"otk",
"=",
"keys",
"[",
"otkId",
"]",
";",
"const",
"session",
"=",
"new",
"global",
".",
"Olm",
".",
"Session",
"(",
")",
";",
"session",
".",
"create_outbound",
"(",
"olmAccount",
",",
"recipientTestClient",
".",
"getDeviceKey",
"(",
")",
",",
"otk",
".",
"key",
",",
")",
";",
"return",
"session",
";",
"}",
")",
";",
"}"
] | start an Olm session with a given recipient
@param {Olm.Account} olmAccount
@param {TestClient} recipientTestClient
@return {Promise} promise for Olm.Session | [
"start",
"an",
"Olm",
"session",
"with",
"a",
"given",
"recipient"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/megolm-integ.spec.js#L36-L47 |
7,658 | matrix-org/matrix-js-sdk | spec/integ/megolm-integ.spec.js | encryptOlmEvent | function encryptOlmEvent(opts) {
expect(opts.senderKey).toBeTruthy();
expect(opts.p2pSession).toBeTruthy();
expect(opts.recipient).toBeTruthy();
const plaintext = {
content: opts.plaincontent || {},
recipient: opts.recipient.userId,
recipient_keys: {
ed25519: opts.recipient.getSigningKey(),
},
sender: opts.sender || '@bob:xyz',
type: opts.plaintype || 'm.test',
};
const event = {
content: {
algorithm: 'm.olm.v1.curve25519-aes-sha2',
ciphertext: {},
sender_key: opts.senderKey,
},
sender: opts.sender || '@bob:xyz',
type: 'm.room.encrypted',
};
event.content.ciphertext[opts.recipient.getDeviceKey()] =
opts.p2pSession.encrypt(JSON.stringify(plaintext));
return event;
} | javascript | function encryptOlmEvent(opts) {
expect(opts.senderKey).toBeTruthy();
expect(opts.p2pSession).toBeTruthy();
expect(opts.recipient).toBeTruthy();
const plaintext = {
content: opts.plaincontent || {},
recipient: opts.recipient.userId,
recipient_keys: {
ed25519: opts.recipient.getSigningKey(),
},
sender: opts.sender || '@bob:xyz',
type: opts.plaintype || 'm.test',
};
const event = {
content: {
algorithm: 'm.olm.v1.curve25519-aes-sha2',
ciphertext: {},
sender_key: opts.senderKey,
},
sender: opts.sender || '@bob:xyz',
type: 'm.room.encrypted',
};
event.content.ciphertext[opts.recipient.getDeviceKey()] =
opts.p2pSession.encrypt(JSON.stringify(plaintext));
return event;
} | [
"function",
"encryptOlmEvent",
"(",
"opts",
")",
"{",
"expect",
"(",
"opts",
".",
"senderKey",
")",
".",
"toBeTruthy",
"(",
")",
";",
"expect",
"(",
"opts",
".",
"p2pSession",
")",
".",
"toBeTruthy",
"(",
")",
";",
"expect",
"(",
"opts",
".",
"recipient",
")",
".",
"toBeTruthy",
"(",
")",
";",
"const",
"plaintext",
"=",
"{",
"content",
":",
"opts",
".",
"plaincontent",
"||",
"{",
"}",
",",
"recipient",
":",
"opts",
".",
"recipient",
".",
"userId",
",",
"recipient_keys",
":",
"{",
"ed25519",
":",
"opts",
".",
"recipient",
".",
"getSigningKey",
"(",
")",
",",
"}",
",",
"sender",
":",
"opts",
".",
"sender",
"||",
"'@bob:xyz'",
",",
"type",
":",
"opts",
".",
"plaintype",
"||",
"'m.test'",
",",
"}",
";",
"const",
"event",
"=",
"{",
"content",
":",
"{",
"algorithm",
":",
"'m.olm.v1.curve25519-aes-sha2'",
",",
"ciphertext",
":",
"{",
"}",
",",
"sender_key",
":",
"opts",
".",
"senderKey",
",",
"}",
",",
"sender",
":",
"opts",
".",
"sender",
"||",
"'@bob:xyz'",
",",
"type",
":",
"'m.room.encrypted'",
",",
"}",
";",
"event",
".",
"content",
".",
"ciphertext",
"[",
"opts",
".",
"recipient",
".",
"getDeviceKey",
"(",
")",
"]",
"=",
"opts",
".",
"p2pSession",
".",
"encrypt",
"(",
"JSON",
".",
"stringify",
"(",
"plaintext",
")",
")",
";",
"return",
"event",
";",
"}"
] | encrypt an event with olm
@param {object} opts
@param {string=} opts.sender
@param {string} opts.senderKey
@param {Olm.Session} opts.p2pSession
@param {TestClient} opts.recipient
@param {object=} opts.plaincontent
@param {string=} opts.plaintype
@return {object} event | [
"encrypt",
"an",
"event",
"with",
"olm"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/megolm-integ.spec.js#L62-L89 |
7,659 | matrix-org/matrix-js-sdk | spec/integ/megolm-integ.spec.js | encryptMegolmEvent | function encryptMegolmEvent(opts) {
expect(opts.senderKey).toBeTruthy();
expect(opts.groupSession).toBeTruthy();
const plaintext = opts.plaintext || {};
if (!plaintext.content) {
plaintext.content = {
body: '42',
msgtype: "m.text",
};
}
if (!plaintext.type) {
plaintext.type = "m.room.message";
}
if (!plaintext.room_id) {
expect(opts.room_id).toBeTruthy();
plaintext.room_id = opts.room_id;
}
return {
event_id: 'test_megolm_event',
content: {
algorithm: "m.megolm.v1.aes-sha2",
ciphertext: opts.groupSession.encrypt(JSON.stringify(plaintext)),
device_id: "testDevice",
sender_key: opts.senderKey,
session_id: opts.groupSession.session_id(),
},
type: "m.room.encrypted",
};
} | javascript | function encryptMegolmEvent(opts) {
expect(opts.senderKey).toBeTruthy();
expect(opts.groupSession).toBeTruthy();
const plaintext = opts.plaintext || {};
if (!plaintext.content) {
plaintext.content = {
body: '42',
msgtype: "m.text",
};
}
if (!plaintext.type) {
plaintext.type = "m.room.message";
}
if (!plaintext.room_id) {
expect(opts.room_id).toBeTruthy();
plaintext.room_id = opts.room_id;
}
return {
event_id: 'test_megolm_event',
content: {
algorithm: "m.megolm.v1.aes-sha2",
ciphertext: opts.groupSession.encrypt(JSON.stringify(plaintext)),
device_id: "testDevice",
sender_key: opts.senderKey,
session_id: opts.groupSession.session_id(),
},
type: "m.room.encrypted",
};
} | [
"function",
"encryptMegolmEvent",
"(",
"opts",
")",
"{",
"expect",
"(",
"opts",
".",
"senderKey",
")",
".",
"toBeTruthy",
"(",
")",
";",
"expect",
"(",
"opts",
".",
"groupSession",
")",
".",
"toBeTruthy",
"(",
")",
";",
"const",
"plaintext",
"=",
"opts",
".",
"plaintext",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"plaintext",
".",
"content",
")",
"{",
"plaintext",
".",
"content",
"=",
"{",
"body",
":",
"'42'",
",",
"msgtype",
":",
"\"m.text\"",
",",
"}",
";",
"}",
"if",
"(",
"!",
"plaintext",
".",
"type",
")",
"{",
"plaintext",
".",
"type",
"=",
"\"m.room.message\"",
";",
"}",
"if",
"(",
"!",
"plaintext",
".",
"room_id",
")",
"{",
"expect",
"(",
"opts",
".",
"room_id",
")",
".",
"toBeTruthy",
"(",
")",
";",
"plaintext",
".",
"room_id",
"=",
"opts",
".",
"room_id",
";",
"}",
"return",
"{",
"event_id",
":",
"'test_megolm_event'",
",",
"content",
":",
"{",
"algorithm",
":",
"\"m.megolm.v1.aes-sha2\"",
",",
"ciphertext",
":",
"opts",
".",
"groupSession",
".",
"encrypt",
"(",
"JSON",
".",
"stringify",
"(",
"plaintext",
")",
")",
",",
"device_id",
":",
"\"testDevice\"",
",",
"sender_key",
":",
"opts",
".",
"senderKey",
",",
"session_id",
":",
"opts",
".",
"groupSession",
".",
"session_id",
"(",
")",
",",
"}",
",",
"type",
":",
"\"m.room.encrypted\"",
",",
"}",
";",
"}"
] | encrypt an event with megolm
@param {object} opts
@param {string} opts.senderKey
@param {Olm.OutboundGroupSession} opts.groupSession
@param {object=} opts.plaintext
@param {string=} opts.room_id
@return {object} event | [
"encrypt",
"an",
"event",
"with",
"megolm"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/megolm-integ.spec.js#L102-L132 |
7,660 | matrix-org/matrix-js-sdk | spec/integ/megolm-integ.spec.js | encryptGroupSessionKey | function encryptGroupSessionKey(opts) {
return encryptOlmEvent({
senderKey: opts.senderKey,
recipient: opts.recipient,
p2pSession: opts.p2pSession,
plaincontent: {
algorithm: 'm.megolm.v1.aes-sha2',
room_id: opts.room_id,
session_id: opts.groupSession.session_id(),
session_key: opts.groupSession.session_key(),
},
plaintype: 'm.room_key',
});
} | javascript | function encryptGroupSessionKey(opts) {
return encryptOlmEvent({
senderKey: opts.senderKey,
recipient: opts.recipient,
p2pSession: opts.p2pSession,
plaincontent: {
algorithm: 'm.megolm.v1.aes-sha2',
room_id: opts.room_id,
session_id: opts.groupSession.session_id(),
session_key: opts.groupSession.session_key(),
},
plaintype: 'm.room_key',
});
} | [
"function",
"encryptGroupSessionKey",
"(",
"opts",
")",
"{",
"return",
"encryptOlmEvent",
"(",
"{",
"senderKey",
":",
"opts",
".",
"senderKey",
",",
"recipient",
":",
"opts",
".",
"recipient",
",",
"p2pSession",
":",
"opts",
".",
"p2pSession",
",",
"plaincontent",
":",
"{",
"algorithm",
":",
"'m.megolm.v1.aes-sha2'",
",",
"room_id",
":",
"opts",
".",
"room_id",
",",
"session_id",
":",
"opts",
".",
"groupSession",
".",
"session_id",
"(",
")",
",",
"session_key",
":",
"opts",
".",
"groupSession",
".",
"session_key",
"(",
")",
",",
"}",
",",
"plaintype",
":",
"'m.room_key'",
",",
"}",
")",
";",
"}"
] | build an encrypted room_key event to share a group session
@param {object} opts
@param {string} opts.senderKey
@param {TestClient} opts.recipient
@param {Olm.Session} opts.p2pSession
@param {Olm.OutboundGroupSession} opts.groupSession
@param {string=} opts.room_id
@return {object} event | [
"build",
"an",
"encrypted",
"room_key",
"event",
"to",
"share",
"a",
"group",
"session"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/megolm-integ.spec.js#L146-L159 |
7,661 | matrix-org/matrix-js-sdk | src/store/session/webstorage.js | WebStorageSessionStore | function WebStorageSessionStore(webStore) {
this.store = webStore;
if (!utils.isFunction(webStore.getItem) ||
!utils.isFunction(webStore.setItem) ||
!utils.isFunction(webStore.removeItem) ||
!utils.isFunction(webStore.key) ||
typeof(webStore.length) !== 'number'
) {
throw new Error(
"Supplied webStore does not meet the WebStorage API interface",
);
}
} | javascript | function WebStorageSessionStore(webStore) {
this.store = webStore;
if (!utils.isFunction(webStore.getItem) ||
!utils.isFunction(webStore.setItem) ||
!utils.isFunction(webStore.removeItem) ||
!utils.isFunction(webStore.key) ||
typeof(webStore.length) !== 'number'
) {
throw new Error(
"Supplied webStore does not meet the WebStorage API interface",
);
}
} | [
"function",
"WebStorageSessionStore",
"(",
"webStore",
")",
"{",
"this",
".",
"store",
"=",
"webStore",
";",
"if",
"(",
"!",
"utils",
".",
"isFunction",
"(",
"webStore",
".",
"getItem",
")",
"||",
"!",
"utils",
".",
"isFunction",
"(",
"webStore",
".",
"setItem",
")",
"||",
"!",
"utils",
".",
"isFunction",
"(",
"webStore",
".",
"removeItem",
")",
"||",
"!",
"utils",
".",
"isFunction",
"(",
"webStore",
".",
"key",
")",
"||",
"typeof",
"(",
"webStore",
".",
"length",
")",
"!==",
"'number'",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Supplied webStore does not meet the WebStorage API interface\"",
",",
")",
";",
"}",
"}"
] | Construct a web storage session store, capable of storing account keys,
session keys and access tokens.
@constructor
@param {WebStorage} webStore A web storage implementation, e.g.
'window.localStorage' or 'window.sessionStorage' or a custom implementation.
@throws if the supplied 'store' does not meet the Storage interface of the
WebStorage API. | [
"Construct",
"a",
"web",
"storage",
"session",
"store",
"capable",
"of",
"storing",
"account",
"keys",
"session",
"keys",
"and",
"access",
"tokens",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/session/webstorage.js#L38-L50 |
7,662 | matrix-org/matrix-js-sdk | src/store/session/webstorage.js | function() {
const prefix = keyEndToEndDevicesForUser('');
const devices = {};
for (let i = 0; i < this.store.length; ++i) {
const key = this.store.key(i);
const userId = key.substr(prefix.length);
if (key.startsWith(prefix)) devices[userId] = getJsonItem(this.store, key);
}
return devices;
} | javascript | function() {
const prefix = keyEndToEndDevicesForUser('');
const devices = {};
for (let i = 0; i < this.store.length; ++i) {
const key = this.store.key(i);
const userId = key.substr(prefix.length);
if (key.startsWith(prefix)) devices[userId] = getJsonItem(this.store, key);
}
return devices;
} | [
"function",
"(",
")",
"{",
"const",
"prefix",
"=",
"keyEndToEndDevicesForUser",
"(",
"''",
")",
";",
"const",
"devices",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"store",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"key",
"=",
"this",
".",
"store",
".",
"key",
"(",
"i",
")",
";",
"const",
"userId",
"=",
"key",
".",
"substr",
"(",
"prefix",
".",
"length",
")",
";",
"if",
"(",
"key",
".",
"startsWith",
"(",
"prefix",
")",
")",
"devices",
"[",
"userId",
"]",
"=",
"getJsonItem",
"(",
"this",
".",
"store",
",",
"key",
")",
";",
"}",
"return",
"devices",
";",
"}"
] | Retrieves the known devices for all users.
@return {object} A map from user ID to map of device ID to keys for the device. | [
"Retrieves",
"the",
"known",
"devices",
"for",
"all",
"users",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/session/webstorage.js#L75-L84 |
|
7,663 | matrix-org/matrix-js-sdk | src/store/session/webstorage.js | function() {
const deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions(''));
const results = {};
for (const k of deviceKeys) {
const unprefixedKey = k.substr(keyEndToEndSessions('').length);
results[unprefixedKey] = getJsonItem(this.store, k);
}
return results;
} | javascript | function() {
const deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions(''));
const results = {};
for (const k of deviceKeys) {
const unprefixedKey = k.substr(keyEndToEndSessions('').length);
results[unprefixedKey] = getJsonItem(this.store, k);
}
return results;
} | [
"function",
"(",
")",
"{",
"const",
"deviceKeys",
"=",
"getKeysWithPrefix",
"(",
"this",
".",
"store",
",",
"keyEndToEndSessions",
"(",
"''",
")",
")",
";",
"const",
"results",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"k",
"of",
"deviceKeys",
")",
"{",
"const",
"unprefixedKey",
"=",
"k",
".",
"substr",
"(",
"keyEndToEndSessions",
"(",
"''",
")",
".",
"length",
")",
";",
"results",
"[",
"unprefixedKey",
"]",
"=",
"getJsonItem",
"(",
"this",
".",
"store",
",",
"k",
")",
";",
"}",
"return",
"results",
";",
"}"
] | Retrieve all end-to-end sessions between the logged-in user and other
devices.
@return {object} A map of {deviceKey -> {sessionId -> session pickle}} | [
"Retrieve",
"all",
"end",
"-",
"to",
"-",
"end",
"sessions",
"between",
"the",
"logged",
"-",
"in",
"user",
"and",
"other",
"devices",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/session/webstorage.js#L123-L131 |
|
7,664 | matrix-org/matrix-js-sdk | src/store/session/webstorage.js | function() {
const prefix = E2E_PREFIX + 'inboundgroupsessions/';
const result = [];
for (let i = 0; i < this.store.length; i++) {
const key = this.store.key(i);
if (!key.startsWith(prefix)) {
continue;
}
// we can't use split, as the components we are trying to split out
// might themselves contain '/' characters. We rely on the
// senderKey being a (32-byte) curve25519 key, base64-encoded
// (hence 43 characters long).
result.push({
senderKey: key.substr(prefix.length, 43),
sessionId: key.substr(prefix.length + 44),
});
}
return result;
} | javascript | function() {
const prefix = E2E_PREFIX + 'inboundgroupsessions/';
const result = [];
for (let i = 0; i < this.store.length; i++) {
const key = this.store.key(i);
if (!key.startsWith(prefix)) {
continue;
}
// we can't use split, as the components we are trying to split out
// might themselves contain '/' characters. We rely on the
// senderKey being a (32-byte) curve25519 key, base64-encoded
// (hence 43 characters long).
result.push({
senderKey: key.substr(prefix.length, 43),
sessionId: key.substr(prefix.length + 44),
});
}
return result;
} | [
"function",
"(",
")",
"{",
"const",
"prefix",
"=",
"E2E_PREFIX",
"+",
"'inboundgroupsessions/'",
";",
"const",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"store",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"key",
"=",
"this",
".",
"store",
".",
"key",
"(",
"i",
")",
";",
"if",
"(",
"!",
"key",
".",
"startsWith",
"(",
"prefix",
")",
")",
"{",
"continue",
";",
"}",
"// we can't use split, as the components we are trying to split out",
"// might themselves contain '/' characters. We rely on the",
"// senderKey being a (32-byte) curve25519 key, base64-encoded",
"// (hence 43 characters long).",
"result",
".",
"push",
"(",
"{",
"senderKey",
":",
"key",
".",
"substr",
"(",
"prefix",
".",
"length",
",",
"43",
")",
",",
"sessionId",
":",
"key",
".",
"substr",
"(",
"prefix",
".",
"length",
"+",
"44",
")",
",",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Retrieve a list of all known inbound group sessions
@return {{senderKey: string, sessionId: string}} | [
"Retrieve",
"a",
"list",
"of",
"all",
"known",
"inbound",
"group",
"sessions"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/session/webstorage.js#L146-L165 |
|
7,665 | matrix-org/matrix-js-sdk | src/store/session/webstorage.js | function() {
const roomKeys = getKeysWithPrefix(this.store, keyEndToEndRoom(''));
const results = {};
for (const k of roomKeys) {
const unprefixedKey = k.substr(keyEndToEndRoom('').length);
results[unprefixedKey] = getJsonItem(this.store, k);
}
return results;
} | javascript | function() {
const roomKeys = getKeysWithPrefix(this.store, keyEndToEndRoom(''));
const results = {};
for (const k of roomKeys) {
const unprefixedKey = k.substr(keyEndToEndRoom('').length);
results[unprefixedKey] = getJsonItem(this.store, k);
}
return results;
} | [
"function",
"(",
")",
"{",
"const",
"roomKeys",
"=",
"getKeysWithPrefix",
"(",
"this",
".",
"store",
",",
"keyEndToEndRoom",
"(",
"''",
")",
")",
";",
"const",
"results",
"=",
"{",
"}",
";",
"for",
"(",
"const",
"k",
"of",
"roomKeys",
")",
"{",
"const",
"unprefixedKey",
"=",
"k",
".",
"substr",
"(",
"keyEndToEndRoom",
"(",
"''",
")",
".",
"length",
")",
";",
"results",
"[",
"unprefixedKey",
"]",
"=",
"getJsonItem",
"(",
"this",
".",
"store",
",",
"k",
")",
";",
"}",
"return",
"results",
";",
"}"
] | Get the end-to-end state for all rooms
@return {object} roomId -> object with the end-to-end info for the room. | [
"Get",
"the",
"end",
"-",
"to",
"-",
"end",
"state",
"for",
"all",
"rooms"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/session/webstorage.js#L180-L188 |
|
7,666 | matrix-org/matrix-js-sdk | src/store/indexeddb.js | IndexedDBStore | function IndexedDBStore(opts) {
MemoryStore.call(this, opts);
if (!opts.indexedDB) {
throw new Error('Missing required option: indexedDB');
}
if (opts.workerScript) {
// try & find a webworker-compatible API
let workerApi = opts.workerApi;
if (!workerApi) {
// default to the global Worker object (which is where it in a browser)
workerApi = global.Worker;
}
this.backend = new RemoteIndexedDBStoreBackend(
opts.workerScript, opts.dbName, workerApi,
);
} else {
this.backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);
}
this.startedUp = false;
this._syncTs = 0;
// Records the last-modified-time of each user at the last point we saved
// the database, such that we can derive the set if users that have been
// modified since we last saved.
this._userModifiedMap = {
// user_id : timestamp
};
} | javascript | function IndexedDBStore(opts) {
MemoryStore.call(this, opts);
if (!opts.indexedDB) {
throw new Error('Missing required option: indexedDB');
}
if (opts.workerScript) {
// try & find a webworker-compatible API
let workerApi = opts.workerApi;
if (!workerApi) {
// default to the global Worker object (which is where it in a browser)
workerApi = global.Worker;
}
this.backend = new RemoteIndexedDBStoreBackend(
opts.workerScript, opts.dbName, workerApi,
);
} else {
this.backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);
}
this.startedUp = false;
this._syncTs = 0;
// Records the last-modified-time of each user at the last point we saved
// the database, such that we can derive the set if users that have been
// modified since we last saved.
this._userModifiedMap = {
// user_id : timestamp
};
} | [
"function",
"IndexedDBStore",
"(",
"opts",
")",
"{",
"MemoryStore",
".",
"call",
"(",
"this",
",",
"opts",
")",
";",
"if",
"(",
"!",
"opts",
".",
"indexedDB",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing required option: indexedDB'",
")",
";",
"}",
"if",
"(",
"opts",
".",
"workerScript",
")",
"{",
"// try & find a webworker-compatible API",
"let",
"workerApi",
"=",
"opts",
".",
"workerApi",
";",
"if",
"(",
"!",
"workerApi",
")",
"{",
"// default to the global Worker object (which is where it in a browser)",
"workerApi",
"=",
"global",
".",
"Worker",
";",
"}",
"this",
".",
"backend",
"=",
"new",
"RemoteIndexedDBStoreBackend",
"(",
"opts",
".",
"workerScript",
",",
"opts",
".",
"dbName",
",",
"workerApi",
",",
")",
";",
"}",
"else",
"{",
"this",
".",
"backend",
"=",
"new",
"LocalIndexedDBStoreBackend",
"(",
"opts",
".",
"indexedDB",
",",
"opts",
".",
"dbName",
")",
";",
"}",
"this",
".",
"startedUp",
"=",
"false",
";",
"this",
".",
"_syncTs",
"=",
"0",
";",
"// Records the last-modified-time of each user at the last point we saved",
"// the database, such that we can derive the set if users that have been",
"// modified since we last saved.",
"this",
".",
"_userModifiedMap",
"=",
"{",
"// user_id : timestamp",
"}",
";",
"}"
] | once every 5 minutes
Construct a new Indexed Database store, which extends MemoryStore.
This store functions like a MemoryStore except it periodically persists
the contents of the store to an IndexedDB backend.
All data is still kept in-memory but can be loaded from disk by calling
<code>startup()</code>. This can make startup times quicker as a complete
sync from the server is not required. This does not reduce memory usage as all
the data is eagerly fetched when <code>startup()</code> is called.
<pre>
let opts = { localStorage: window.localStorage };
let store = new IndexedDBStore();
await store.startup(); // load from indexed db
let client = sdk.createClient({
store: store,
});
client.startClient();
client.on("sync", function(state, prevState, data) {
if (state === "PREPARED") {
console.log("Started up, now with go faster stripes!");
}
});
</pre>
@constructor
@extends MemoryStore
@param {Object} opts Options object.
@param {Object} opts.indexedDB The Indexed DB interface e.g.
<code>window.indexedDB</code>
@param {string=} opts.dbName Optional database name. The same name must be used
to open the same database.
@param {string=} opts.workerScript Optional URL to a script to invoke a web
worker with to run IndexedDB queries on the web worker. The IndexedDbStoreWorker
class is provided for this purpose and requires the application to provide a
trivial wrapper script around it.
@param {Object=} opts.workerApi The webWorker API object. If omitted, the global Worker
object will be used if it exists.
@prop {IndexedDBStoreBackend} backend The backend instance. Call through to
this API if you need to perform specific indexeddb actions like deleting the
database. | [
"once",
"every",
"5",
"minutes",
"Construct",
"a",
"new",
"Indexed",
"Database",
"store",
"which",
"extends",
"MemoryStore",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb.js#L84-L114 |
7,667 | matrix-org/matrix-js-sdk | src/store/indexeddb.js | degradable | function degradable(func, fallback) {
return async function(...args) {
try {
return await func.call(this, ...args);
} catch (e) {
console.error("IndexedDBStore failure, degrading to MemoryStore", e);
this.emit("degraded", e);
try {
// We try to delete IndexedDB after degrading since this store is only a
// cache (the app will still function correctly without the data).
// It's possible that deleting repair IndexedDB for the next app load,
// potenially by making a little more space available.
console.log("IndexedDBStore trying to delete degraded data");
await this.backend.clearDatabase();
console.log("IndexedDBStore delete after degrading succeeeded");
} catch (e) {
console.warn("IndexedDBStore delete after degrading failed", e);
}
// Degrade the store from being an instance of `IndexedDBStore` to instead be
// an instance of `MemoryStore` so that future API calls use the memory path
// directly and skip IndexedDB entirely. This should be safe as
// `IndexedDBStore` already extends from `MemoryStore`, so we are making the
// store become its parent type in a way. The mutator methods of
// `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are
// not overridden at all).
Object.setPrototypeOf(this, MemoryStore.prototype);
if (fallback) {
return await MemoryStore.prototype[fallback].call(this, ...args);
}
}
};
} | javascript | function degradable(func, fallback) {
return async function(...args) {
try {
return await func.call(this, ...args);
} catch (e) {
console.error("IndexedDBStore failure, degrading to MemoryStore", e);
this.emit("degraded", e);
try {
// We try to delete IndexedDB after degrading since this store is only a
// cache (the app will still function correctly without the data).
// It's possible that deleting repair IndexedDB for the next app load,
// potenially by making a little more space available.
console.log("IndexedDBStore trying to delete degraded data");
await this.backend.clearDatabase();
console.log("IndexedDBStore delete after degrading succeeeded");
} catch (e) {
console.warn("IndexedDBStore delete after degrading failed", e);
}
// Degrade the store from being an instance of `IndexedDBStore` to instead be
// an instance of `MemoryStore` so that future API calls use the memory path
// directly and skip IndexedDB entirely. This should be safe as
// `IndexedDBStore` already extends from `MemoryStore`, so we are making the
// store become its parent type in a way. The mutator methods of
// `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are
// not overridden at all).
Object.setPrototypeOf(this, MemoryStore.prototype);
if (fallback) {
return await MemoryStore.prototype[fallback].call(this, ...args);
}
}
};
} | [
"function",
"degradable",
"(",
"func",
",",
"fallback",
")",
"{",
"return",
"async",
"function",
"(",
"...",
"args",
")",
"{",
"try",
"{",
"return",
"await",
"func",
".",
"call",
"(",
"this",
",",
"...",
"args",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"\"IndexedDBStore failure, degrading to MemoryStore\"",
",",
"e",
")",
";",
"this",
".",
"emit",
"(",
"\"degraded\"",
",",
"e",
")",
";",
"try",
"{",
"// We try to delete IndexedDB after degrading since this store is only a",
"// cache (the app will still function correctly without the data).",
"// It's possible that deleting repair IndexedDB for the next app load,",
"// potenially by making a little more space available.",
"console",
".",
"log",
"(",
"\"IndexedDBStore trying to delete degraded data\"",
")",
";",
"await",
"this",
".",
"backend",
".",
"clearDatabase",
"(",
")",
";",
"console",
".",
"log",
"(",
"\"IndexedDBStore delete after degrading succeeeded\"",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"warn",
"(",
"\"IndexedDBStore delete after degrading failed\"",
",",
"e",
")",
";",
"}",
"// Degrade the store from being an instance of `IndexedDBStore` to instead be",
"// an instance of `MemoryStore` so that future API calls use the memory path",
"// directly and skip IndexedDB entirely. This should be safe as",
"// `IndexedDBStore` already extends from `MemoryStore`, so we are making the",
"// store become its parent type in a way. The mutator methods of",
"// `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are",
"// not overridden at all).",
"Object",
".",
"setPrototypeOf",
"(",
"this",
",",
"MemoryStore",
".",
"prototype",
")",
";",
"if",
"(",
"fallback",
")",
"{",
"return",
"await",
"MemoryStore",
".",
"prototype",
"[",
"fallback",
"]",
".",
"call",
"(",
"this",
",",
"...",
"args",
")",
";",
"}",
"}",
"}",
";",
"}"
] | All member functions of `IndexedDBStore` that access the backend use this wrapper to
watch for failures after initial store startup, including `QuotaExceededError` as
free disk space changes, etc.
When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore`
in place so that the current operation and all future ones are in-memory only.
@param {Function} func The degradable work to do.
@param {String} fallback The method name for fallback.
@returns {Function} A wrapped member function. | [
"All",
"member",
"functions",
"of",
"IndexedDBStore",
"that",
"access",
"the",
"backend",
"use",
"this",
"wrapper",
"to",
"watch",
"for",
"failures",
"after",
"initial",
"store",
"startup",
"including",
"QuotaExceededError",
"as",
"free",
"disk",
"space",
"changes",
"etc",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/store/indexeddb.js#L288-L319 |
7,668 | matrix-org/matrix-js-sdk | src/base-apis.js | MatrixBaseApis | function MatrixBaseApis(opts) {
utils.checkObjectHasKeys(opts, ["baseUrl", "request"]);
this.baseUrl = opts.baseUrl;
this.idBaseUrl = opts.idBaseUrl;
const httpOpts = {
baseUrl: opts.baseUrl,
idBaseUrl: opts.idBaseUrl,
accessToken: opts.accessToken,
request: opts.request,
prefix: httpApi.PREFIX_R0,
onlyData: true,
extraParams: opts.queryParams,
localTimeoutMs: opts.localTimeoutMs,
useAuthorizationHeader: opts.useAuthorizationHeader,
};
this._http = new httpApi.MatrixHttpApi(this, httpOpts);
this._txnCtr = 0;
} | javascript | function MatrixBaseApis(opts) {
utils.checkObjectHasKeys(opts, ["baseUrl", "request"]);
this.baseUrl = opts.baseUrl;
this.idBaseUrl = opts.idBaseUrl;
const httpOpts = {
baseUrl: opts.baseUrl,
idBaseUrl: opts.idBaseUrl,
accessToken: opts.accessToken,
request: opts.request,
prefix: httpApi.PREFIX_R0,
onlyData: true,
extraParams: opts.queryParams,
localTimeoutMs: opts.localTimeoutMs,
useAuthorizationHeader: opts.useAuthorizationHeader,
};
this._http = new httpApi.MatrixHttpApi(this, httpOpts);
this._txnCtr = 0;
} | [
"function",
"MatrixBaseApis",
"(",
"opts",
")",
"{",
"utils",
".",
"checkObjectHasKeys",
"(",
"opts",
",",
"[",
"\"baseUrl\"",
",",
"\"request\"",
"]",
")",
";",
"this",
".",
"baseUrl",
"=",
"opts",
".",
"baseUrl",
";",
"this",
".",
"idBaseUrl",
"=",
"opts",
".",
"idBaseUrl",
";",
"const",
"httpOpts",
"=",
"{",
"baseUrl",
":",
"opts",
".",
"baseUrl",
",",
"idBaseUrl",
":",
"opts",
".",
"idBaseUrl",
",",
"accessToken",
":",
"opts",
".",
"accessToken",
",",
"request",
":",
"opts",
".",
"request",
",",
"prefix",
":",
"httpApi",
".",
"PREFIX_R0",
",",
"onlyData",
":",
"true",
",",
"extraParams",
":",
"opts",
".",
"queryParams",
",",
"localTimeoutMs",
":",
"opts",
".",
"localTimeoutMs",
",",
"useAuthorizationHeader",
":",
"opts",
".",
"useAuthorizationHeader",
",",
"}",
";",
"this",
".",
"_http",
"=",
"new",
"httpApi",
".",
"MatrixHttpApi",
"(",
"this",
",",
"httpOpts",
")",
";",
"this",
".",
"_txnCtr",
"=",
"0",
";",
"}"
] | Low-level wrappers for the Matrix APIs
@constructor
@param {Object} opts Configuration options
@param {string} opts.baseUrl Required. The base URL to the client-server
HTTP API.
@param {string} opts.idBaseUrl Optional. The base identity server URL for
identity server requests.
@param {Function} opts.request Required. The function to invoke for HTTP
requests. The value of this property is typically <code>require("request")
</code> as it returns a function which meets the required interface. See
{@link requestFunction} for more information.
@param {string} opts.accessToken The access_token for this user.
@param {Number=} opts.localTimeoutMs Optional. The default maximum amount of
time to wait before timing out HTTP requests. If not specified, there is no
timeout.
@param {Object} opts.queryParams Optional. Extra query parameters to append
to all requests with this client. Useful for application services which require
<code>?user_id=</code>.
@param {boolean} [opts.useAuthorizationHeader = false] Set to true to use
Authorization header instead of query param to send the access token to the server. | [
"Low",
"-",
"level",
"wrappers",
"for",
"the",
"Matrix",
"APIs"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/base-apis.js#L60-L80 |
7,669 | matrix-org/matrix-js-sdk | src/realtime-callbacks.js | _scheduleRealCallback | function _scheduleRealCallback() {
if (_realCallbackKey) {
global.clearTimeout(_realCallbackKey);
}
const first = _callbackList[0];
if (!first) {
debuglog("_scheduleRealCallback: no more callbacks, not rescheduling");
return;
}
const now = _now();
const delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS);
debuglog("_scheduleRealCallback: now:", now, "delay:", delayMs);
_realCallbackKey = global.setTimeout(_runCallbacks, delayMs);
} | javascript | function _scheduleRealCallback() {
if (_realCallbackKey) {
global.clearTimeout(_realCallbackKey);
}
const first = _callbackList[0];
if (!first) {
debuglog("_scheduleRealCallback: no more callbacks, not rescheduling");
return;
}
const now = _now();
const delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS);
debuglog("_scheduleRealCallback: now:", now, "delay:", delayMs);
_realCallbackKey = global.setTimeout(_runCallbacks, delayMs);
} | [
"function",
"_scheduleRealCallback",
"(",
")",
"{",
"if",
"(",
"_realCallbackKey",
")",
"{",
"global",
".",
"clearTimeout",
"(",
"_realCallbackKey",
")",
";",
"}",
"const",
"first",
"=",
"_callbackList",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"first",
")",
"{",
"debuglog",
"(",
"\"_scheduleRealCallback: no more callbacks, not rescheduling\"",
")",
";",
"return",
";",
"}",
"const",
"now",
"=",
"_now",
"(",
")",
";",
"const",
"delayMs",
"=",
"Math",
".",
"min",
"(",
"first",
".",
"runAt",
"-",
"now",
",",
"TIMER_CHECK_PERIOD_MS",
")",
";",
"debuglog",
"(",
"\"_scheduleRealCallback: now:\"",
",",
"now",
",",
"\"delay:\"",
",",
"delayMs",
")",
";",
"_realCallbackKey",
"=",
"global",
".",
"setTimeout",
"(",
"_runCallbacks",
",",
"delayMs",
")",
";",
"}"
] | use the real global.setTimeout to schedule a callback to _runCallbacks. | [
"use",
"the",
"real",
"global",
".",
"setTimeout",
"to",
"schedule",
"a",
"callback",
"to",
"_runCallbacks",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/realtime-callbacks.js#L127-L144 |
7,670 | matrix-org/matrix-js-sdk | src/models/room.js | Room | function Room(roomId, client, myUserId, opts) {
opts = opts || {};
opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological";
this.reEmitter = new ReEmitter(this);
if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) {
throw new Error(
"opts.pendingEventOrdering MUST be either 'chronological' or " +
"'detached'. Got: '" + opts.pendingEventOrdering + "'",
);
}
this.myUserId = myUserId;
this.roomId = roomId;
this.name = roomId;
this.tags = {
// $tagName: { $metadata: $value },
// $tagName: { $metadata: $value },
};
this.accountData = {
// $eventType: $event
};
this.summary = null;
this.storageToken = opts.storageToken;
this._opts = opts;
this._txnToEvent = {}; // Pending in-flight requests { string: MatrixEvent }
// receipts should clobber based on receipt_type and user_id pairs hence
// the form of this structure. This is sub-optimal for the exposed APIs
// which pass in an event ID and get back some receipts, so we also store
// a pre-cached list for this purpose.
this._receipts = {
// receipt_type: {
// user_id: {
// eventId: <event_id>,
// data: <receipt_data>
// }
// }
};
this._receiptCacheByEventId = {
// $event_id: [{
// type: $type,
// userId: $user_id,
// data: <receipt data>
// }]
};
// only receipts that came from the server, not synthesized ones
this._realReceipts = {};
this._notificationCounts = {};
// all our per-room timeline sets. the first one is the unfiltered ones;
// the subsequent ones are the filtered ones in no particular order.
this._timelineSets = [new EventTimelineSet(this, opts)];
this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),
["Room.timeline", "Room.timelineReset"]);
this._fixUpLegacyTimelineFields();
// any filtered timeline sets we're maintaining for this room
this._filteredTimelineSets = {
// filter_id: timelineSet
};
if (this._opts.pendingEventOrdering == "detached") {
this._pendingEventList = [];
}
// read by megolm; boolean value - null indicates "use global value"
this._blacklistUnverifiedDevices = null;
this._selfMembership = null;
this._summaryHeroes = null;
// awaited by getEncryptionTargetMembers while room members are loading
this._client = client;
if (!this._opts.lazyLoadMembers) {
this._membersPromise = Promise.resolve();
} else {
this._membersPromise = null;
}
} | javascript | function Room(roomId, client, myUserId, opts) {
opts = opts || {};
opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological";
this.reEmitter = new ReEmitter(this);
if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) {
throw new Error(
"opts.pendingEventOrdering MUST be either 'chronological' or " +
"'detached'. Got: '" + opts.pendingEventOrdering + "'",
);
}
this.myUserId = myUserId;
this.roomId = roomId;
this.name = roomId;
this.tags = {
// $tagName: { $metadata: $value },
// $tagName: { $metadata: $value },
};
this.accountData = {
// $eventType: $event
};
this.summary = null;
this.storageToken = opts.storageToken;
this._opts = opts;
this._txnToEvent = {}; // Pending in-flight requests { string: MatrixEvent }
// receipts should clobber based on receipt_type and user_id pairs hence
// the form of this structure. This is sub-optimal for the exposed APIs
// which pass in an event ID and get back some receipts, so we also store
// a pre-cached list for this purpose.
this._receipts = {
// receipt_type: {
// user_id: {
// eventId: <event_id>,
// data: <receipt_data>
// }
// }
};
this._receiptCacheByEventId = {
// $event_id: [{
// type: $type,
// userId: $user_id,
// data: <receipt data>
// }]
};
// only receipts that came from the server, not synthesized ones
this._realReceipts = {};
this._notificationCounts = {};
// all our per-room timeline sets. the first one is the unfiltered ones;
// the subsequent ones are the filtered ones in no particular order.
this._timelineSets = [new EventTimelineSet(this, opts)];
this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),
["Room.timeline", "Room.timelineReset"]);
this._fixUpLegacyTimelineFields();
// any filtered timeline sets we're maintaining for this room
this._filteredTimelineSets = {
// filter_id: timelineSet
};
if (this._opts.pendingEventOrdering == "detached") {
this._pendingEventList = [];
}
// read by megolm; boolean value - null indicates "use global value"
this._blacklistUnverifiedDevices = null;
this._selfMembership = null;
this._summaryHeroes = null;
// awaited by getEncryptionTargetMembers while room members are loading
this._client = client;
if (!this._opts.lazyLoadMembers) {
this._membersPromise = Promise.resolve();
} else {
this._membersPromise = null;
}
} | [
"function",
"Room",
"(",
"roomId",
",",
"client",
",",
"myUserId",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"opts",
".",
"pendingEventOrdering",
"=",
"opts",
".",
"pendingEventOrdering",
"||",
"\"chronological\"",
";",
"this",
".",
"reEmitter",
"=",
"new",
"ReEmitter",
"(",
"this",
")",
";",
"if",
"(",
"[",
"\"chronological\"",
",",
"\"detached\"",
"]",
".",
"indexOf",
"(",
"opts",
".",
"pendingEventOrdering",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"opts.pendingEventOrdering MUST be either 'chronological' or \"",
"+",
"\"'detached'. Got: '\"",
"+",
"opts",
".",
"pendingEventOrdering",
"+",
"\"'\"",
",",
")",
";",
"}",
"this",
".",
"myUserId",
"=",
"myUserId",
";",
"this",
".",
"roomId",
"=",
"roomId",
";",
"this",
".",
"name",
"=",
"roomId",
";",
"this",
".",
"tags",
"=",
"{",
"// $tagName: { $metadata: $value },",
"// $tagName: { $metadata: $value },",
"}",
";",
"this",
".",
"accountData",
"=",
"{",
"// $eventType: $event",
"}",
";",
"this",
".",
"summary",
"=",
"null",
";",
"this",
".",
"storageToken",
"=",
"opts",
".",
"storageToken",
";",
"this",
".",
"_opts",
"=",
"opts",
";",
"this",
".",
"_txnToEvent",
"=",
"{",
"}",
";",
"// Pending in-flight requests { string: MatrixEvent }",
"// receipts should clobber based on receipt_type and user_id pairs hence",
"// the form of this structure. This is sub-optimal for the exposed APIs",
"// which pass in an event ID and get back some receipts, so we also store",
"// a pre-cached list for this purpose.",
"this",
".",
"_receipts",
"=",
"{",
"// receipt_type: {",
"// user_id: {",
"// eventId: <event_id>,",
"// data: <receipt_data>",
"// }",
"// }",
"}",
";",
"this",
".",
"_receiptCacheByEventId",
"=",
"{",
"// $event_id: [{",
"// type: $type,",
"// userId: $user_id,",
"// data: <receipt data>",
"// }]",
"}",
";",
"// only receipts that came from the server, not synthesized ones",
"this",
".",
"_realReceipts",
"=",
"{",
"}",
";",
"this",
".",
"_notificationCounts",
"=",
"{",
"}",
";",
"// all our per-room timeline sets. the first one is the unfiltered ones;",
"// the subsequent ones are the filtered ones in no particular order.",
"this",
".",
"_timelineSets",
"=",
"[",
"new",
"EventTimelineSet",
"(",
"this",
",",
"opts",
")",
"]",
";",
"this",
".",
"reEmitter",
".",
"reEmit",
"(",
"this",
".",
"getUnfilteredTimelineSet",
"(",
")",
",",
"[",
"\"Room.timeline\"",
",",
"\"Room.timelineReset\"",
"]",
")",
";",
"this",
".",
"_fixUpLegacyTimelineFields",
"(",
")",
";",
"// any filtered timeline sets we're maintaining for this room",
"this",
".",
"_filteredTimelineSets",
"=",
"{",
"// filter_id: timelineSet",
"}",
";",
"if",
"(",
"this",
".",
"_opts",
".",
"pendingEventOrdering",
"==",
"\"detached\"",
")",
"{",
"this",
".",
"_pendingEventList",
"=",
"[",
"]",
";",
"}",
"// read by megolm; boolean value - null indicates \"use global value\"",
"this",
".",
"_blacklistUnverifiedDevices",
"=",
"null",
";",
"this",
".",
"_selfMembership",
"=",
"null",
";",
"this",
".",
"_summaryHeroes",
"=",
"null",
";",
"// awaited by getEncryptionTargetMembers while room members are loading",
"this",
".",
"_client",
"=",
"client",
";",
"if",
"(",
"!",
"this",
".",
"_opts",
".",
"lazyLoadMembers",
")",
"{",
"this",
".",
"_membersPromise",
"=",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"this",
".",
"_membersPromise",
"=",
"null",
";",
"}",
"}"
] | Construct a new Room.
<p>For a room, we store an ordered sequence of timelines, which may or may not
be continuous. Each timeline lists a series of events, as well as tracking
the room state at the start and the end of the timeline. It also tracks
forward and backward pagination tokens, as well as containing links to the
next timeline in the sequence.
<p>There is one special timeline - the 'live' timeline, which represents the
timeline to which events are being added in real-time as they are received
from the /sync API. Note that you should not retain references to this
timeline - even if it is the current timeline right now, it may not remain
so if the server gives us a timeline gap in /sync.
<p>In order that we can find events from their ids later, we also maintain a
map from event_id to timeline and index.
@constructor
@alias module:models/room
@param {string} roomId Required. The ID of this room.
@param {MatrixClient} client Required. The client, used to lazy load members.
@param {string} myUserId Required. The ID of the syncing user.
@param {Object=} opts Configuration options
@param {*} opts.storageToken Optional. The token which a data store can use
to remember the state of the room. What this means is dependent on the store
implementation.
@param {String=} opts.pendingEventOrdering Controls where pending messages
appear in a room's timeline. If "<b>chronological</b>", messages will appear
in the timeline when the call to <code>sendEvent</code> was made. If
"<b>detached</b>", pending messages will appear in a separate list,
accessbile via {@link module:models/room#getPendingEvents}. Default:
"chronological".
@param {boolean} [opts.timelineSupport = false] Set to true to enable improved
timeline support.
@prop {string} roomId The ID of this room.
@prop {string} name The human-readable display name for this room.
@prop {Array<MatrixEvent>} timeline The live event timeline for this room,
with the oldest event at index 0. Present for backwards compatibility -
prefer getLiveTimeline().getEvents().
@prop {object} tags Dict of room tags; the keys are the tag name and the values
are any metadata associated with the tag - e.g. { "fav" : { order: 1 } }
@prop {object} accountData Dict of per-room account_data events; the keys are the
event type and the values are the events.
@prop {RoomState} oldState The state of the room at the time of the oldest
event in the live timeline. Present for backwards compatibility -
prefer getLiveTimeline().getState(EventTimeline.BACKWARDS).
@prop {RoomState} currentState The state of the room at the time of the
newest event in the timeline. Present for backwards compatibility -
prefer getLiveTimeline().getState(EventTimeline.FORWARDS).
@prop {RoomSummary} summary The room summary.
@prop {*} storageToken A token which a data store can use to remember
the state of the room. | [
"Construct",
"a",
"new",
"Room",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/room.js#L118-L198 |
7,671 | matrix-org/matrix-js-sdk | src/models/room.js | calculateRoomName | function calculateRoomName(room, userId, ignoreRoomNameEvent) {
if (!ignoreRoomNameEvent) {
// check for an alias, if any. for now, assume first alias is the
// official one.
const mRoomName = room.currentState.getStateEvents("m.room.name", "");
if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) {
return mRoomName.getContent().name;
}
}
let alias = room.getCanonicalAlias();
if (!alias) {
const aliases = room.getAliases();
if (aliases.length) {
alias = aliases[0];
}
}
if (alias) {
return alias;
}
const joinedMemberCount = room.currentState.getJoinedMemberCount();
const invitedMemberCount = room.currentState.getInvitedMemberCount();
// -1 because these numbers include the syncing user
const inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;
// get members that are NOT ourselves and are actually in the room.
let otherNames = null;
if (room._summaryHeroes) {
// if we have a summary, the member state events
// should be in the room state
otherNames = room._summaryHeroes.map((userId) => {
const member = room.getMember(userId);
return member ? member.name : userId;
});
} else {
let otherMembers = room.currentState.getMembers().filter((m) => {
return m.userId !== userId &&
(m.membership === "invite" || m.membership === "join");
});
// make sure members have stable order
otherMembers.sort((a, b) => a.userId.localeCompare(b.userId));
// only 5 first members, immitate _summaryHeroes
otherMembers = otherMembers.slice(0, 5);
otherNames = otherMembers.map((m) => m.name);
}
if (inviteJoinCount) {
return memberNamesToRoomName(otherNames, inviteJoinCount);
}
const myMembership = room.getMyMembership();
// if I have created a room and invited people throuh
// 3rd party invites
if (myMembership == 'join') {
const thirdPartyInvites =
room.currentState.getStateEvents("m.room.third_party_invite");
if (thirdPartyInvites && thirdPartyInvites.length) {
const thirdPartyNames = thirdPartyInvites.map((i) => {
return i.getContent().display_name;
});
return `Inviting ${memberNamesToRoomName(thirdPartyNames)}`;
}
}
// let's try to figure out who was here before
let leftNames = otherNames;
// if we didn't have heroes, try finding them in the room state
if(!leftNames.length) {
leftNames = room.currentState.getMembers().filter((m) => {
return m.userId !== userId &&
m.membership !== "invite" &&
m.membership !== "join";
}).map((m) => m.name);
}
if(leftNames.length) {
return `Empty room (was ${memberNamesToRoomName(leftNames)})`;
} else {
return "Empty room";
}
} | javascript | function calculateRoomName(room, userId, ignoreRoomNameEvent) {
if (!ignoreRoomNameEvent) {
// check for an alias, if any. for now, assume first alias is the
// official one.
const mRoomName = room.currentState.getStateEvents("m.room.name", "");
if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) {
return mRoomName.getContent().name;
}
}
let alias = room.getCanonicalAlias();
if (!alias) {
const aliases = room.getAliases();
if (aliases.length) {
alias = aliases[0];
}
}
if (alias) {
return alias;
}
const joinedMemberCount = room.currentState.getJoinedMemberCount();
const invitedMemberCount = room.currentState.getInvitedMemberCount();
// -1 because these numbers include the syncing user
const inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;
// get members that are NOT ourselves and are actually in the room.
let otherNames = null;
if (room._summaryHeroes) {
// if we have a summary, the member state events
// should be in the room state
otherNames = room._summaryHeroes.map((userId) => {
const member = room.getMember(userId);
return member ? member.name : userId;
});
} else {
let otherMembers = room.currentState.getMembers().filter((m) => {
return m.userId !== userId &&
(m.membership === "invite" || m.membership === "join");
});
// make sure members have stable order
otherMembers.sort((a, b) => a.userId.localeCompare(b.userId));
// only 5 first members, immitate _summaryHeroes
otherMembers = otherMembers.slice(0, 5);
otherNames = otherMembers.map((m) => m.name);
}
if (inviteJoinCount) {
return memberNamesToRoomName(otherNames, inviteJoinCount);
}
const myMembership = room.getMyMembership();
// if I have created a room and invited people throuh
// 3rd party invites
if (myMembership == 'join') {
const thirdPartyInvites =
room.currentState.getStateEvents("m.room.third_party_invite");
if (thirdPartyInvites && thirdPartyInvites.length) {
const thirdPartyNames = thirdPartyInvites.map((i) => {
return i.getContent().display_name;
});
return `Inviting ${memberNamesToRoomName(thirdPartyNames)}`;
}
}
// let's try to figure out who was here before
let leftNames = otherNames;
// if we didn't have heroes, try finding them in the room state
if(!leftNames.length) {
leftNames = room.currentState.getMembers().filter((m) => {
return m.userId !== userId &&
m.membership !== "invite" &&
m.membership !== "join";
}).map((m) => m.name);
}
if(leftNames.length) {
return `Empty room (was ${memberNamesToRoomName(leftNames)})`;
} else {
return "Empty room";
}
} | [
"function",
"calculateRoomName",
"(",
"room",
",",
"userId",
",",
"ignoreRoomNameEvent",
")",
"{",
"if",
"(",
"!",
"ignoreRoomNameEvent",
")",
"{",
"// check for an alias, if any. for now, assume first alias is the",
"// official one.",
"const",
"mRoomName",
"=",
"room",
".",
"currentState",
".",
"getStateEvents",
"(",
"\"m.room.name\"",
",",
"\"\"",
")",
";",
"if",
"(",
"mRoomName",
"&&",
"mRoomName",
".",
"getContent",
"(",
")",
"&&",
"mRoomName",
".",
"getContent",
"(",
")",
".",
"name",
")",
"{",
"return",
"mRoomName",
".",
"getContent",
"(",
")",
".",
"name",
";",
"}",
"}",
"let",
"alias",
"=",
"room",
".",
"getCanonicalAlias",
"(",
")",
";",
"if",
"(",
"!",
"alias",
")",
"{",
"const",
"aliases",
"=",
"room",
".",
"getAliases",
"(",
")",
";",
"if",
"(",
"aliases",
".",
"length",
")",
"{",
"alias",
"=",
"aliases",
"[",
"0",
"]",
";",
"}",
"}",
"if",
"(",
"alias",
")",
"{",
"return",
"alias",
";",
"}",
"const",
"joinedMemberCount",
"=",
"room",
".",
"currentState",
".",
"getJoinedMemberCount",
"(",
")",
";",
"const",
"invitedMemberCount",
"=",
"room",
".",
"currentState",
".",
"getInvitedMemberCount",
"(",
")",
";",
"// -1 because these numbers include the syncing user",
"const",
"inviteJoinCount",
"=",
"joinedMemberCount",
"+",
"invitedMemberCount",
"-",
"1",
";",
"// get members that are NOT ourselves and are actually in the room.",
"let",
"otherNames",
"=",
"null",
";",
"if",
"(",
"room",
".",
"_summaryHeroes",
")",
"{",
"// if we have a summary, the member state events",
"// should be in the room state",
"otherNames",
"=",
"room",
".",
"_summaryHeroes",
".",
"map",
"(",
"(",
"userId",
")",
"=>",
"{",
"const",
"member",
"=",
"room",
".",
"getMember",
"(",
"userId",
")",
";",
"return",
"member",
"?",
"member",
".",
"name",
":",
"userId",
";",
"}",
")",
";",
"}",
"else",
"{",
"let",
"otherMembers",
"=",
"room",
".",
"currentState",
".",
"getMembers",
"(",
")",
".",
"filter",
"(",
"(",
"m",
")",
"=>",
"{",
"return",
"m",
".",
"userId",
"!==",
"userId",
"&&",
"(",
"m",
".",
"membership",
"===",
"\"invite\"",
"||",
"m",
".",
"membership",
"===",
"\"join\"",
")",
";",
"}",
")",
";",
"// make sure members have stable order",
"otherMembers",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"userId",
".",
"localeCompare",
"(",
"b",
".",
"userId",
")",
")",
";",
"// only 5 first members, immitate _summaryHeroes",
"otherMembers",
"=",
"otherMembers",
".",
"slice",
"(",
"0",
",",
"5",
")",
";",
"otherNames",
"=",
"otherMembers",
".",
"map",
"(",
"(",
"m",
")",
"=>",
"m",
".",
"name",
")",
";",
"}",
"if",
"(",
"inviteJoinCount",
")",
"{",
"return",
"memberNamesToRoomName",
"(",
"otherNames",
",",
"inviteJoinCount",
")",
";",
"}",
"const",
"myMembership",
"=",
"room",
".",
"getMyMembership",
"(",
")",
";",
"// if I have created a room and invited people throuh",
"// 3rd party invites",
"if",
"(",
"myMembership",
"==",
"'join'",
")",
"{",
"const",
"thirdPartyInvites",
"=",
"room",
".",
"currentState",
".",
"getStateEvents",
"(",
"\"m.room.third_party_invite\"",
")",
";",
"if",
"(",
"thirdPartyInvites",
"&&",
"thirdPartyInvites",
".",
"length",
")",
"{",
"const",
"thirdPartyNames",
"=",
"thirdPartyInvites",
".",
"map",
"(",
"(",
"i",
")",
"=>",
"{",
"return",
"i",
".",
"getContent",
"(",
")",
".",
"display_name",
";",
"}",
")",
";",
"return",
"`",
"${",
"memberNamesToRoomName",
"(",
"thirdPartyNames",
")",
"}",
"`",
";",
"}",
"}",
"// let's try to figure out who was here before",
"let",
"leftNames",
"=",
"otherNames",
";",
"// if we didn't have heroes, try finding them in the room state",
"if",
"(",
"!",
"leftNames",
".",
"length",
")",
"{",
"leftNames",
"=",
"room",
".",
"currentState",
".",
"getMembers",
"(",
")",
".",
"filter",
"(",
"(",
"m",
")",
"=>",
"{",
"return",
"m",
".",
"userId",
"!==",
"userId",
"&&",
"m",
".",
"membership",
"!==",
"\"invite\"",
"&&",
"m",
".",
"membership",
"!==",
"\"join\"",
";",
"}",
")",
".",
"map",
"(",
"(",
"m",
")",
"=>",
"m",
".",
"name",
")",
";",
"}",
"if",
"(",
"leftNames",
".",
"length",
")",
"{",
"return",
"`",
"${",
"memberNamesToRoomName",
"(",
"leftNames",
")",
"}",
"`",
";",
"}",
"else",
"{",
"return",
"\"Empty room\"",
";",
"}",
"}"
] | This is an internal method. Calculates the name of the room from the current
room state.
@param {Room} room The matrix room.
@param {string} userId The client's user ID. Used to filter room members
correctly.
@param {bool} ignoreRoomNameEvent Return the implicit room name that we'd see if there
was no m.room.name event.
@return {string} The calculated room name. | [
"This",
"is",
"an",
"internal",
"method",
".",
"Calculates",
"the",
"name",
"of",
"the",
"room",
"from",
"the",
"current",
"room",
"state",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/room.js#L1658-L1741 |
7,672 | matrix-org/matrix-js-sdk | src/interactive-auth.js | InteractiveAuth | function InteractiveAuth(opts) {
this._matrixClient = opts.matrixClient;
this._data = opts.authData || {};
this._requestCallback = opts.doRequest;
// startAuthStage included for backwards compat
this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
this._completionDeferred = null;
this._inputs = opts.inputs || {};
if (opts.sessionId) this._data.session = opts.sessionId;
this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
this._emailSid = opts.emailSid;
if (this._emailSid === undefined) this._emailSid = null;
this._currentStage = null;
} | javascript | function InteractiveAuth(opts) {
this._matrixClient = opts.matrixClient;
this._data = opts.authData || {};
this._requestCallback = opts.doRequest;
// startAuthStage included for backwards compat
this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
this._completionDeferred = null;
this._inputs = opts.inputs || {};
if (opts.sessionId) this._data.session = opts.sessionId;
this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
this._emailSid = opts.emailSid;
if (this._emailSid === undefined) this._emailSid = null;
this._currentStage = null;
} | [
"function",
"InteractiveAuth",
"(",
"opts",
")",
"{",
"this",
".",
"_matrixClient",
"=",
"opts",
".",
"matrixClient",
";",
"this",
".",
"_data",
"=",
"opts",
".",
"authData",
"||",
"{",
"}",
";",
"this",
".",
"_requestCallback",
"=",
"opts",
".",
"doRequest",
";",
"// startAuthStage included for backwards compat",
"this",
".",
"_stateUpdatedCallback",
"=",
"opts",
".",
"stateUpdated",
"||",
"opts",
".",
"startAuthStage",
";",
"this",
".",
"_completionDeferred",
"=",
"null",
";",
"this",
".",
"_inputs",
"=",
"opts",
".",
"inputs",
"||",
"{",
"}",
";",
"if",
"(",
"opts",
".",
"sessionId",
")",
"this",
".",
"_data",
".",
"session",
"=",
"opts",
".",
"sessionId",
";",
"this",
".",
"_clientSecret",
"=",
"opts",
".",
"clientSecret",
"||",
"this",
".",
"_matrixClient",
".",
"generateClientSecret",
"(",
")",
";",
"this",
".",
"_emailSid",
"=",
"opts",
".",
"emailSid",
";",
"if",
"(",
"this",
".",
"_emailSid",
"===",
"undefined",
")",
"this",
".",
"_emailSid",
"=",
"null",
";",
"this",
".",
"_currentStage",
"=",
"null",
";",
"}"
] | Abstracts the logic used to drive the interactive auth process.
<p>Components implementing an interactive auth flow should instantiate one of
these, passing in the necessary callbacks to the constructor. They should
then call attemptAuth, which will return a promise which will resolve or
reject when the interactive-auth process completes.
<p>Meanwhile, calls will be made to the startAuthStage and doRequest
callbacks, and information gathered from the user can be submitted with
submitAuthDict.
@constructor
@alias module:interactive-auth
@param {object} opts options object
@param {object} opts.matrixClient A matrix client to use for the auth process
@param {object?} opts.authData error response from the last request. If
null, a request will be made with no auth before starting.
@param {function(object?, bool?): module:client.Promise} opts.doRequest
called with the new auth dict to submit the request and a flag set
to true if this request is a background request. Should return a
promise which resolves to the successful response or rejects with a
MatrixError.
@param {function(string, object?)} opts.stateUpdated
called when the status of the UI auth changes, ie. when the state of
an auth stage changes of when the auth flow moves to a new stage.
The arguments are: the login type (eg m.login.password); and an object
which is either an error or an informational object specific to the
login type. If the 'errcode' key is defined, the object is an error,
and has keys:
errcode: string, the textual error code, eg. M_UNKNOWN
error: string, human readable string describing the error
The login type specific objects are as follows:
m.login.email.identity:
* emailSid: string, the sid of the active email auth session
@param {object?} opts.inputs Inputs provided by the user and used by different
stages of the auto process. The inputs provided will affect what flow is chosen.
@param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
using email verification will be chosen.
@param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
the country that opts.phoneNumber should be resolved relative to.
@param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
using phone number validation will be chosen.
@param {string?} opts.sessionId If resuming an existing interactive auth session,
the sessionId of that session.
@param {string?} opts.clientSecret If resuming an existing interactive auth session,
the client secret for that session
@param {string?} opts.emailSid If returning from having completed m.login.email.identity
auth, the sid for the email verification session. | [
"Abstracts",
"the",
"logic",
"used",
"to",
"drive",
"the",
"interactive",
"auth",
"process",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L92-L107 |
7,673 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function() {
this._completionDeferred = Promise.defer();
// wrap in a promise so that if _startNextAuthStage
// throws, it rejects the promise in a consistent way
return Promise.resolve().then(() => {
// if we have no flows, try a request (we'll have
// just a session ID in _data if resuming)
if (!this._data.flows) {
this._doRequest(this._data);
} else {
this._startNextAuthStage();
}
return this._completionDeferred.promise;
});
} | javascript | function() {
this._completionDeferred = Promise.defer();
// wrap in a promise so that if _startNextAuthStage
// throws, it rejects the promise in a consistent way
return Promise.resolve().then(() => {
// if we have no flows, try a request (we'll have
// just a session ID in _data if resuming)
if (!this._data.flows) {
this._doRequest(this._data);
} else {
this._startNextAuthStage();
}
return this._completionDeferred.promise;
});
} | [
"function",
"(",
")",
"{",
"this",
".",
"_completionDeferred",
"=",
"Promise",
".",
"defer",
"(",
")",
";",
"// wrap in a promise so that if _startNextAuthStage",
"// throws, it rejects the promise in a consistent way",
"return",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"// if we have no flows, try a request (we'll have",
"// just a session ID in _data if resuming)",
"if",
"(",
"!",
"this",
".",
"_data",
".",
"flows",
")",
"{",
"this",
".",
"_doRequest",
"(",
"this",
".",
"_data",
")",
";",
"}",
"else",
"{",
"this",
".",
"_startNextAuthStage",
"(",
")",
";",
"}",
"return",
"this",
".",
"_completionDeferred",
".",
"promise",
";",
"}",
")",
";",
"}"
] | begin the authentication process.
@return {module:client.Promise} which resolves to the response on success,
or rejects with the error on failure. Rejects with NoAuthFlowFoundError if
no suitable authentication flow can be found | [
"begin",
"the",
"authentication",
"process",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L117-L132 |
|
7,674 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function() {
if (!this._data.session) return;
let authDict = {};
if (this._currentStage == EMAIL_STAGE_TYPE) {
// The email can be validated out-of-band, but we need to provide the
// creds so the HS can go & check it.
if (this._emailSid) {
const idServerParsedUrl = url.parse(
this._matrixClient.getIdentityServerUrl(),
);
authDict = {
type: EMAIL_STAGE_TYPE,
threepid_creds: {
sid: this._emailSid,
client_secret: this._clientSecret,
id_server: idServerParsedUrl.host,
},
};
}
}
this.submitAuthDict(authDict, true);
} | javascript | function() {
if (!this._data.session) return;
let authDict = {};
if (this._currentStage == EMAIL_STAGE_TYPE) {
// The email can be validated out-of-band, but we need to provide the
// creds so the HS can go & check it.
if (this._emailSid) {
const idServerParsedUrl = url.parse(
this._matrixClient.getIdentityServerUrl(),
);
authDict = {
type: EMAIL_STAGE_TYPE,
threepid_creds: {
sid: this._emailSid,
client_secret: this._clientSecret,
id_server: idServerParsedUrl.host,
},
};
}
}
this.submitAuthDict(authDict, true);
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_data",
".",
"session",
")",
"return",
";",
"let",
"authDict",
"=",
"{",
"}",
";",
"if",
"(",
"this",
".",
"_currentStage",
"==",
"EMAIL_STAGE_TYPE",
")",
"{",
"// The email can be validated out-of-band, but we need to provide the",
"// creds so the HS can go & check it.",
"if",
"(",
"this",
".",
"_emailSid",
")",
"{",
"const",
"idServerParsedUrl",
"=",
"url",
".",
"parse",
"(",
"this",
".",
"_matrixClient",
".",
"getIdentityServerUrl",
"(",
")",
",",
")",
";",
"authDict",
"=",
"{",
"type",
":",
"EMAIL_STAGE_TYPE",
",",
"threepid_creds",
":",
"{",
"sid",
":",
"this",
".",
"_emailSid",
",",
"client_secret",
":",
"this",
".",
"_clientSecret",
",",
"id_server",
":",
"idServerParsedUrl",
".",
"host",
",",
"}",
",",
"}",
";",
"}",
"}",
"this",
".",
"submitAuthDict",
"(",
"authDict",
",",
"true",
")",
";",
"}"
] | Poll to check if the auth session or current stage has been
completed out-of-band. If so, the attemptAuth promise will
be resolved. | [
"Poll",
"to",
"check",
"if",
"the",
"auth",
"session",
"or",
"current",
"stage",
"has",
"been",
"completed",
"out",
"-",
"of",
"-",
"band",
".",
"If",
"so",
"the",
"attemptAuth",
"promise",
"will",
"be",
"resolved",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L139-L162 |
|
7,675 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function(loginType) {
let params = {};
if (this._data && this._data.params) {
params = this._data.params;
}
return params[loginType];
} | javascript | function(loginType) {
let params = {};
if (this._data && this._data.params) {
params = this._data.params;
}
return params[loginType];
} | [
"function",
"(",
"loginType",
")",
"{",
"let",
"params",
"=",
"{",
"}",
";",
"if",
"(",
"this",
".",
"_data",
"&&",
"this",
".",
"_data",
".",
"params",
")",
"{",
"params",
"=",
"this",
".",
"_data",
".",
"params",
";",
"}",
"return",
"params",
"[",
"loginType",
"]",
";",
"}"
] | get the server params for a given stage
@param {string} loginType login type for the stage
@return {object?} any parameters from the server for this stage | [
"get",
"the",
"server",
"params",
"for",
"a",
"given",
"stage"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L189-L195 |
|
7,676 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function(auth, background) {
const self = this;
// hackery to make sure that synchronous exceptions end up in the catch
// handler (without the additional event loop entailed by q.fcall or an
// extra Promise.resolve().then)
let prom;
try {
prom = this._requestCallback(auth, background);
} catch (e) {
prom = Promise.reject(e);
}
prom = prom.then(
function(result) {
console.log("result from request: ", result);
self._completionDeferred.resolve(result);
}, function(error) {
// sometimes UI auth errors don't come with flows
const errorFlows = error.data ? error.data.flows : null;
const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows);
if (error.httpStatus !== 401 || !error.data || !haveFlows) {
// doesn't look like an interactive-auth failure. fail the whole lot.
throw error;
}
// if the error didn't come with flows, completed flows or session ID,
// copy over the ones we have. Synapse sometimes sends responses without
// any UI auth data (eg. when polling for email validation, if the email
// has not yet been validated). This appears to be a Synapse bug, which
// we workaround here.
if (!error.data.flows && !error.data.completed && !error.data.session) {
error.data.flows = self._data.flows;
error.data.completed = self._data.completed;
error.data.session = self._data.session;
}
self._data = error.data;
self._startNextAuthStage();
},
);
if (!background) {
prom = prom.catch((e) => {
this._completionDeferred.reject(e);
});
} else {
// We ignore all failures here (even non-UI auth related ones)
// since we don't want to suddenly fail if the internet connection
// had a blip whilst we were polling
prom = prom.catch((error) => {
console.log("Ignoring error from UI auth: " + error);
});
}
prom.done();
} | javascript | function(auth, background) {
const self = this;
// hackery to make sure that synchronous exceptions end up in the catch
// handler (without the additional event loop entailed by q.fcall or an
// extra Promise.resolve().then)
let prom;
try {
prom = this._requestCallback(auth, background);
} catch (e) {
prom = Promise.reject(e);
}
prom = prom.then(
function(result) {
console.log("result from request: ", result);
self._completionDeferred.resolve(result);
}, function(error) {
// sometimes UI auth errors don't come with flows
const errorFlows = error.data ? error.data.flows : null;
const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows);
if (error.httpStatus !== 401 || !error.data || !haveFlows) {
// doesn't look like an interactive-auth failure. fail the whole lot.
throw error;
}
// if the error didn't come with flows, completed flows or session ID,
// copy over the ones we have. Synapse sometimes sends responses without
// any UI auth data (eg. when polling for email validation, if the email
// has not yet been validated). This appears to be a Synapse bug, which
// we workaround here.
if (!error.data.flows && !error.data.completed && !error.data.session) {
error.data.flows = self._data.flows;
error.data.completed = self._data.completed;
error.data.session = self._data.session;
}
self._data = error.data;
self._startNextAuthStage();
},
);
if (!background) {
prom = prom.catch((e) => {
this._completionDeferred.reject(e);
});
} else {
// We ignore all failures here (even non-UI auth related ones)
// since we don't want to suddenly fail if the internet connection
// had a blip whilst we were polling
prom = prom.catch((error) => {
console.log("Ignoring error from UI auth: " + error);
});
}
prom.done();
} | [
"function",
"(",
"auth",
",",
"background",
")",
"{",
"const",
"self",
"=",
"this",
";",
"// hackery to make sure that synchronous exceptions end up in the catch",
"// handler (without the additional event loop entailed by q.fcall or an",
"// extra Promise.resolve().then)",
"let",
"prom",
";",
"try",
"{",
"prom",
"=",
"this",
".",
"_requestCallback",
"(",
"auth",
",",
"background",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"prom",
"=",
"Promise",
".",
"reject",
"(",
"e",
")",
";",
"}",
"prom",
"=",
"prom",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"console",
".",
"log",
"(",
"\"result from request: \"",
",",
"result",
")",
";",
"self",
".",
"_completionDeferred",
".",
"resolve",
"(",
"result",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"// sometimes UI auth errors don't come with flows",
"const",
"errorFlows",
"=",
"error",
".",
"data",
"?",
"error",
".",
"data",
".",
"flows",
":",
"null",
";",
"const",
"haveFlows",
"=",
"Boolean",
"(",
"self",
".",
"_data",
".",
"flows",
")",
"||",
"Boolean",
"(",
"errorFlows",
")",
";",
"if",
"(",
"error",
".",
"httpStatus",
"!==",
"401",
"||",
"!",
"error",
".",
"data",
"||",
"!",
"haveFlows",
")",
"{",
"// doesn't look like an interactive-auth failure. fail the whole lot.",
"throw",
"error",
";",
"}",
"// if the error didn't come with flows, completed flows or session ID,",
"// copy over the ones we have. Synapse sometimes sends responses without",
"// any UI auth data (eg. when polling for email validation, if the email",
"// has not yet been validated). This appears to be a Synapse bug, which",
"// we workaround here.",
"if",
"(",
"!",
"error",
".",
"data",
".",
"flows",
"&&",
"!",
"error",
".",
"data",
".",
"completed",
"&&",
"!",
"error",
".",
"data",
".",
"session",
")",
"{",
"error",
".",
"data",
".",
"flows",
"=",
"self",
".",
"_data",
".",
"flows",
";",
"error",
".",
"data",
".",
"completed",
"=",
"self",
".",
"_data",
".",
"completed",
";",
"error",
".",
"data",
".",
"session",
"=",
"self",
".",
"_data",
".",
"session",
";",
"}",
"self",
".",
"_data",
"=",
"error",
".",
"data",
";",
"self",
".",
"_startNextAuthStage",
"(",
")",
";",
"}",
",",
")",
";",
"if",
"(",
"!",
"background",
")",
"{",
"prom",
"=",
"prom",
".",
"catch",
"(",
"(",
"e",
")",
"=>",
"{",
"this",
".",
"_completionDeferred",
".",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// We ignore all failures here (even non-UI auth related ones)",
"// since we don't want to suddenly fail if the internet connection",
"// had a blip whilst we were polling",
"prom",
"=",
"prom",
".",
"catch",
"(",
"(",
"error",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"\"Ignoring error from UI auth: \"",
"+",
"error",
")",
";",
"}",
")",
";",
"}",
"prom",
".",
"done",
"(",
")",
";",
"}"
] | Fire off a request, and either resolve the promise, or call
startAuthStage.
@private
@param {object?} auth new auth dict, including session id
@param {bool?} background If true, this request is a background poll, so it
failing will not result in the attemptAuth promise being rejected.
This can be set to true for requests that just poll to see if auth has
been completed elsewhere. | [
"Fire",
"off",
"a",
"request",
"and",
"either",
"resolve",
"the",
"promise",
"or",
"call",
"startAuthStage",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L256-L308 |
|
7,677 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function() {
const nextStage = this._chooseStage();
if (!nextStage) {
throw new Error("No incomplete flows from the server");
}
this._currentStage = nextStage;
if (nextStage == 'm.login.dummy') {
this.submitAuthDict({
type: 'm.login.dummy',
});
return;
}
if (this._data.errcode || this._data.error) {
this._stateUpdatedCallback(nextStage, {
errcode: this._data.errcode || "",
error: this._data.error || "",
});
return;
}
const stageStatus = {};
if (nextStage == EMAIL_STAGE_TYPE) {
stageStatus.emailSid = this._emailSid;
}
this._stateUpdatedCallback(nextStage, stageStatus);
} | javascript | function() {
const nextStage = this._chooseStage();
if (!nextStage) {
throw new Error("No incomplete flows from the server");
}
this._currentStage = nextStage;
if (nextStage == 'm.login.dummy') {
this.submitAuthDict({
type: 'm.login.dummy',
});
return;
}
if (this._data.errcode || this._data.error) {
this._stateUpdatedCallback(nextStage, {
errcode: this._data.errcode || "",
error: this._data.error || "",
});
return;
}
const stageStatus = {};
if (nextStage == EMAIL_STAGE_TYPE) {
stageStatus.emailSid = this._emailSid;
}
this._stateUpdatedCallback(nextStage, stageStatus);
} | [
"function",
"(",
")",
"{",
"const",
"nextStage",
"=",
"this",
".",
"_chooseStage",
"(",
")",
";",
"if",
"(",
"!",
"nextStage",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"No incomplete flows from the server\"",
")",
";",
"}",
"this",
".",
"_currentStage",
"=",
"nextStage",
";",
"if",
"(",
"nextStage",
"==",
"'m.login.dummy'",
")",
"{",
"this",
".",
"submitAuthDict",
"(",
"{",
"type",
":",
"'m.login.dummy'",
",",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"this",
".",
"_data",
".",
"errcode",
"||",
"this",
".",
"_data",
".",
"error",
")",
"{",
"this",
".",
"_stateUpdatedCallback",
"(",
"nextStage",
",",
"{",
"errcode",
":",
"this",
".",
"_data",
".",
"errcode",
"||",
"\"\"",
",",
"error",
":",
"this",
".",
"_data",
".",
"error",
"||",
"\"\"",
",",
"}",
")",
";",
"return",
";",
"}",
"const",
"stageStatus",
"=",
"{",
"}",
";",
"if",
"(",
"nextStage",
"==",
"EMAIL_STAGE_TYPE",
")",
"{",
"stageStatus",
".",
"emailSid",
"=",
"this",
".",
"_emailSid",
";",
"}",
"this",
".",
"_stateUpdatedCallback",
"(",
"nextStage",
",",
"stageStatus",
")",
";",
"}"
] | Pick the next stage and call the callback
@private
@throws {NoAuthFlowFoundError} If no suitable authentication flow can be found | [
"Pick",
"the",
"next",
"stage",
"and",
"call",
"the",
"callback"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L316-L343 |
|
7,678 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function() {
const flow = this._chooseFlow();
console.log("Active flow => %s", JSON.stringify(flow));
const nextStage = this._firstUncompletedStage(flow);
console.log("Next stage: %s", nextStage);
return nextStage;
} | javascript | function() {
const flow = this._chooseFlow();
console.log("Active flow => %s", JSON.stringify(flow));
const nextStage = this._firstUncompletedStage(flow);
console.log("Next stage: %s", nextStage);
return nextStage;
} | [
"function",
"(",
")",
"{",
"const",
"flow",
"=",
"this",
".",
"_chooseFlow",
"(",
")",
";",
"console",
".",
"log",
"(",
"\"Active flow => %s\"",
",",
"JSON",
".",
"stringify",
"(",
"flow",
")",
")",
";",
"const",
"nextStage",
"=",
"this",
".",
"_firstUncompletedStage",
"(",
"flow",
")",
";",
"console",
".",
"log",
"(",
"\"Next stage: %s\"",
",",
"nextStage",
")",
";",
"return",
"nextStage",
";",
"}"
] | Pick the next auth stage
@private
@return {string?} login type
@throws {NoAuthFlowFoundError} If no suitable authentication flow can be found | [
"Pick",
"the",
"next",
"auth",
"stage"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L352-L358 |
|
7,679 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function() {
const flows = this._data.flows || [];
// we've been given an email or we've already done an email part
const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
const haveMsisdn = (
Boolean(this._inputs.phoneCountry) &&
Boolean(this._inputs.phoneNumber)
);
for (const flow of flows) {
let flowHasEmail = false;
let flowHasMsisdn = false;
for (const stage of flow.stages) {
if (stage === EMAIL_STAGE_TYPE) {
flowHasEmail = true;
} else if (stage == MSISDN_STAGE_TYPE) {
flowHasMsisdn = true;
}
}
if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
return flow;
}
}
// Throw an error with a fairly generic description, but with more
// information such that the app can give a better one if so desired.
const err = new Error("No appropriate authentication flow found");
err.name = 'NoAuthFlowFoundError';
err.required_stages = [];
if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);
if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);
err.available_flows = flows;
throw err;
} | javascript | function() {
const flows = this._data.flows || [];
// we've been given an email or we've already done an email part
const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
const haveMsisdn = (
Boolean(this._inputs.phoneCountry) &&
Boolean(this._inputs.phoneNumber)
);
for (const flow of flows) {
let flowHasEmail = false;
let flowHasMsisdn = false;
for (const stage of flow.stages) {
if (stage === EMAIL_STAGE_TYPE) {
flowHasEmail = true;
} else if (stage == MSISDN_STAGE_TYPE) {
flowHasMsisdn = true;
}
}
if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
return flow;
}
}
// Throw an error with a fairly generic description, but with more
// information such that the app can give a better one if so desired.
const err = new Error("No appropriate authentication flow found");
err.name = 'NoAuthFlowFoundError';
err.required_stages = [];
if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);
if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);
err.available_flows = flows;
throw err;
} | [
"function",
"(",
")",
"{",
"const",
"flows",
"=",
"this",
".",
"_data",
".",
"flows",
"||",
"[",
"]",
";",
"// we've been given an email or we've already done an email part",
"const",
"haveEmail",
"=",
"Boolean",
"(",
"this",
".",
"_inputs",
".",
"emailAddress",
")",
"||",
"Boolean",
"(",
"this",
".",
"_emailSid",
")",
";",
"const",
"haveMsisdn",
"=",
"(",
"Boolean",
"(",
"this",
".",
"_inputs",
".",
"phoneCountry",
")",
"&&",
"Boolean",
"(",
"this",
".",
"_inputs",
".",
"phoneNumber",
")",
")",
";",
"for",
"(",
"const",
"flow",
"of",
"flows",
")",
"{",
"let",
"flowHasEmail",
"=",
"false",
";",
"let",
"flowHasMsisdn",
"=",
"false",
";",
"for",
"(",
"const",
"stage",
"of",
"flow",
".",
"stages",
")",
"{",
"if",
"(",
"stage",
"===",
"EMAIL_STAGE_TYPE",
")",
"{",
"flowHasEmail",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"stage",
"==",
"MSISDN_STAGE_TYPE",
")",
"{",
"flowHasMsisdn",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"flowHasEmail",
"==",
"haveEmail",
"&&",
"flowHasMsisdn",
"==",
"haveMsisdn",
")",
"{",
"return",
"flow",
";",
"}",
"}",
"// Throw an error with a fairly generic description, but with more",
"// information such that the app can give a better one if so desired.",
"const",
"err",
"=",
"new",
"Error",
"(",
"\"No appropriate authentication flow found\"",
")",
";",
"err",
".",
"name",
"=",
"'NoAuthFlowFoundError'",
";",
"err",
".",
"required_stages",
"=",
"[",
"]",
";",
"if",
"(",
"haveEmail",
")",
"err",
".",
"required_stages",
".",
"push",
"(",
"EMAIL_STAGE_TYPE",
")",
";",
"if",
"(",
"haveMsisdn",
")",
"err",
".",
"required_stages",
".",
"push",
"(",
"MSISDN_STAGE_TYPE",
")",
";",
"err",
".",
"available_flows",
"=",
"flows",
";",
"throw",
"err",
";",
"}"
] | Pick one of the flows from the returned list
If a flow using all of the inputs is found, it will
be returned, otherwise, null will be returned.
Only flows using all given inputs are chosen because it
is likley to be surprising if the user provides a
credential and it is not used. For example, for registration,
this could result in the email not being used which would leave
the account with no means to reset a password.
@private
@return {object} flow
@throws {NoAuthFlowFoundError} If no suitable authentication flow can be found | [
"Pick",
"one",
"of",
"the",
"flows",
"from",
"the",
"returned",
"list",
"If",
"a",
"flow",
"using",
"all",
"of",
"the",
"inputs",
"is",
"found",
"it",
"will",
"be",
"returned",
"otherwise",
"null",
"will",
"be",
"returned",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L375-L409 |
|
7,680 | matrix-org/matrix-js-sdk | src/interactive-auth.js | function(flow) {
const completed = (this._data || {}).completed || [];
for (let i = 0; i < flow.stages.length; ++i) {
const stageType = flow.stages[i];
if (completed.indexOf(stageType) === -1) {
return stageType;
}
}
} | javascript | function(flow) {
const completed = (this._data || {}).completed || [];
for (let i = 0; i < flow.stages.length; ++i) {
const stageType = flow.stages[i];
if (completed.indexOf(stageType) === -1) {
return stageType;
}
}
} | [
"function",
"(",
"flow",
")",
"{",
"const",
"completed",
"=",
"(",
"this",
".",
"_data",
"||",
"{",
"}",
")",
".",
"completed",
"||",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"flow",
".",
"stages",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"stageType",
"=",
"flow",
".",
"stages",
"[",
"i",
"]",
";",
"if",
"(",
"completed",
".",
"indexOf",
"(",
"stageType",
")",
"===",
"-",
"1",
")",
"{",
"return",
"stageType",
";",
"}",
"}",
"}"
] | Get the first uncompleted stage in the given flow
@private
@param {object} flow
@return {string} login type | [
"Get",
"the",
"first",
"uncompleted",
"stage",
"in",
"the",
"given",
"flow"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/interactive-auth.js#L418-L426 |
|
7,681 | matrix-org/matrix-js-sdk | src/models/room-member.js | RoomMember | function RoomMember(roomId, userId) {
this.roomId = roomId;
this.userId = userId;
this.typing = false;
this.name = userId;
this.rawDisplayName = userId;
this.powerLevel = 0;
this.powerLevelNorm = 0;
this.user = null;
this.membership = null;
this.events = {
member: null,
};
this._isOutOfBand = false;
this._updateModifiedTime();
} | javascript | function RoomMember(roomId, userId) {
this.roomId = roomId;
this.userId = userId;
this.typing = false;
this.name = userId;
this.rawDisplayName = userId;
this.powerLevel = 0;
this.powerLevelNorm = 0;
this.user = null;
this.membership = null;
this.events = {
member: null,
};
this._isOutOfBand = false;
this._updateModifiedTime();
} | [
"function",
"RoomMember",
"(",
"roomId",
",",
"userId",
")",
"{",
"this",
".",
"roomId",
"=",
"roomId",
";",
"this",
".",
"userId",
"=",
"userId",
";",
"this",
".",
"typing",
"=",
"false",
";",
"this",
".",
"name",
"=",
"userId",
";",
"this",
".",
"rawDisplayName",
"=",
"userId",
";",
"this",
".",
"powerLevel",
"=",
"0",
";",
"this",
".",
"powerLevelNorm",
"=",
"0",
";",
"this",
".",
"user",
"=",
"null",
";",
"this",
".",
"membership",
"=",
"null",
";",
"this",
".",
"events",
"=",
"{",
"member",
":",
"null",
",",
"}",
";",
"this",
".",
"_isOutOfBand",
"=",
"false",
";",
"this",
".",
"_updateModifiedTime",
"(",
")",
";",
"}"
] | Construct a new room member.
@constructor
@alias module:models/room-member
@param {string} roomId The room ID of the member.
@param {string} userId The user ID of the member.
@prop {string} roomId The room ID for this member.
@prop {string} userId The user ID of this member.
@prop {boolean} typing True if the room member is currently typing.
@prop {string} name The human-readable name for this room member. This will be
disambiguated with a suffix of " (@user_id:matrix.org)" if another member shares the
same displayname.
@prop {string} rawDisplayName The ambiguous displayname of this room member.
@prop {Number} powerLevel The power level for this room member.
@prop {Number} powerLevelNorm The normalised power level (0-100) for this
room member.
@prop {User} user The User object for this room member, if one exists.
@prop {string} membership The membership state for this room member e.g. 'join'.
@prop {Object} events The events describing this RoomMember.
@prop {MatrixEvent} events.member The m.room.member event for this RoomMember. | [
"Construct",
"a",
"new",
"room",
"member",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/room-member.js#L48-L63 |
7,682 | matrix-org/matrix-js-sdk | src/models/room-state.js | RoomState | function RoomState(roomId, oobMemberFlags = undefined) {
this.roomId = roomId;
this.members = {
// userId: RoomMember
};
this.events = {
// eventType: { stateKey: MatrixEvent }
};
this.paginationToken = null;
this._sentinels = {
// userId: RoomMember
};
this._updateModifiedTime();
// stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)
this._displayNameToUserIds = {};
this._userIdsToDisplayNames = {};
this._tokenToInvite = {}; // 3pid invite state_key to m.room.member invite
this._joinedMemberCount = null; // cache of the number of joined members
// joined members count from summary api
// once set, we know the server supports the summary api
// and we should only trust that
// we could also only trust that before OOB members
// are loaded but doesn't seem worth the hassle atm
this._summaryJoinedMemberCount = null;
// same for invited member count
this._invitedMemberCount = null;
this._summaryInvitedMemberCount = null;
if (!oobMemberFlags) {
oobMemberFlags = {
status: OOB_STATUS_NOTSTARTED,
};
}
this._oobMemberFlags = oobMemberFlags;
} | javascript | function RoomState(roomId, oobMemberFlags = undefined) {
this.roomId = roomId;
this.members = {
// userId: RoomMember
};
this.events = {
// eventType: { stateKey: MatrixEvent }
};
this.paginationToken = null;
this._sentinels = {
// userId: RoomMember
};
this._updateModifiedTime();
// stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)
this._displayNameToUserIds = {};
this._userIdsToDisplayNames = {};
this._tokenToInvite = {}; // 3pid invite state_key to m.room.member invite
this._joinedMemberCount = null; // cache of the number of joined members
// joined members count from summary api
// once set, we know the server supports the summary api
// and we should only trust that
// we could also only trust that before OOB members
// are loaded but doesn't seem worth the hassle atm
this._summaryJoinedMemberCount = null;
// same for invited member count
this._invitedMemberCount = null;
this._summaryInvitedMemberCount = null;
if (!oobMemberFlags) {
oobMemberFlags = {
status: OOB_STATUS_NOTSTARTED,
};
}
this._oobMemberFlags = oobMemberFlags;
} | [
"function",
"RoomState",
"(",
"roomId",
",",
"oobMemberFlags",
"=",
"undefined",
")",
"{",
"this",
".",
"roomId",
"=",
"roomId",
";",
"this",
".",
"members",
"=",
"{",
"// userId: RoomMember",
"}",
";",
"this",
".",
"events",
"=",
"{",
"// eventType: { stateKey: MatrixEvent }",
"}",
";",
"this",
".",
"paginationToken",
"=",
"null",
";",
"this",
".",
"_sentinels",
"=",
"{",
"// userId: RoomMember",
"}",
";",
"this",
".",
"_updateModifiedTime",
"(",
")",
";",
"// stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)",
"this",
".",
"_displayNameToUserIds",
"=",
"{",
"}",
";",
"this",
".",
"_userIdsToDisplayNames",
"=",
"{",
"}",
";",
"this",
".",
"_tokenToInvite",
"=",
"{",
"}",
";",
"// 3pid invite state_key to m.room.member invite",
"this",
".",
"_joinedMemberCount",
"=",
"null",
";",
"// cache of the number of joined members",
"// joined members count from summary api",
"// once set, we know the server supports the summary api",
"// and we should only trust that",
"// we could also only trust that before OOB members",
"// are loaded but doesn't seem worth the hassle atm",
"this",
".",
"_summaryJoinedMemberCount",
"=",
"null",
";",
"// same for invited member count",
"this",
".",
"_invitedMemberCount",
"=",
"null",
";",
"this",
".",
"_summaryInvitedMemberCount",
"=",
"null",
";",
"if",
"(",
"!",
"oobMemberFlags",
")",
"{",
"oobMemberFlags",
"=",
"{",
"status",
":",
"OOB_STATUS_NOTSTARTED",
",",
"}",
";",
"}",
"this",
".",
"_oobMemberFlags",
"=",
"oobMemberFlags",
";",
"}"
] | Construct room state.
Room State represents the state of the room at a given point.
It can be mutated by adding state events to it.
There are two types of room member associated with a state event:
normal member objects (accessed via getMember/getMembers) which mutate
with the state to represent the current state of that room/user, eg.
the object returned by getMember('@bob:example.com') will mutate to
get a different display name if Bob later changes his display name
in the room.
There are also 'sentinel' members (accessed via getSentinelMember).
These also represent the state of room members at the point in time
represented by the RoomState object, but unlike objects from getMember,
sentinel objects will always represent the room state as at the time
getSentinelMember was called, so if Bob subsequently changes his display
name, a room member object previously acquired with getSentinelMember
will still have his old display name. Calling getSentinelMember again
after the display name change will return a new RoomMember object
with Bob's new display name.
@constructor
@param {?string} roomId Optional. The ID of the room which has this state.
If none is specified it just tracks paginationTokens, useful for notifTimelineSet
@param {?object} oobMemberFlags Optional. The state of loading out of bound members.
As the timeline might get reset while they are loading, this state needs to be inherited
and shared when the room state is cloned for the new timeline.
This should only be passed from clone.
@prop {Object.<string, RoomMember>} members The room member dictionary, keyed
on the user's ID.
@prop {Object.<string, Object.<string, MatrixEvent>>} events The state
events dictionary, keyed on the event type and then the state_key value.
@prop {string} paginationToken The pagination token for this state. | [
"Construct",
"room",
"state",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/room-state.js#L64-L100 |
7,683 | matrix-org/matrix-js-sdk | src/crypto/algorithms/olm.js | OlmEncryption | function OlmEncryption(params) {
base.EncryptionAlgorithm.call(this, params);
this._sessionPrepared = false;
this._prepPromise = null;
} | javascript | function OlmEncryption(params) {
base.EncryptionAlgorithm.call(this, params);
this._sessionPrepared = false;
this._prepPromise = null;
} | [
"function",
"OlmEncryption",
"(",
"params",
")",
"{",
"base",
".",
"EncryptionAlgorithm",
".",
"call",
"(",
"this",
",",
"params",
")",
";",
"this",
".",
"_sessionPrepared",
"=",
"false",
";",
"this",
".",
"_prepPromise",
"=",
"null",
";",
"}"
] | Olm encryption implementation
@constructor
@extends {module:crypto/algorithms/base.EncryptionAlgorithm}
@param {object} params parameters, as per
{@link module:crypto/algorithms/base.EncryptionAlgorithm} | [
"Olm",
"encryption",
"implementation"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/crypto/algorithms/olm.js#L43-L47 |
7,684 | matrix-org/matrix-js-sdk | spec/integ/matrix-client-crypto.spec.js | expectAliQueryKeys | function expectAliQueryKeys() {
// can't query keys before bob has uploaded them
expect(bobTestClient.deviceKeys).toBeTruthy();
const bobKeys = {};
bobKeys[bobDeviceId] = bobTestClient.deviceKeys;
aliTestClient.httpBackend.when("POST", "/keys/query")
.respond(200, function(path, content) {
expect(content.device_keys[bobUserId]).toEqual(
{},
"Expected Alice to key query for " + bobUserId + ", got " +
Object.keys(content.device_keys),
);
const result = {};
result[bobUserId] = bobKeys;
return {device_keys: result};
});
return aliTestClient.httpBackend.flush("/keys/query", 1);
} | javascript | function expectAliQueryKeys() {
// can't query keys before bob has uploaded them
expect(bobTestClient.deviceKeys).toBeTruthy();
const bobKeys = {};
bobKeys[bobDeviceId] = bobTestClient.deviceKeys;
aliTestClient.httpBackend.when("POST", "/keys/query")
.respond(200, function(path, content) {
expect(content.device_keys[bobUserId]).toEqual(
{},
"Expected Alice to key query for " + bobUserId + ", got " +
Object.keys(content.device_keys),
);
const result = {};
result[bobUserId] = bobKeys;
return {device_keys: result};
});
return aliTestClient.httpBackend.flush("/keys/query", 1);
} | [
"function",
"expectAliQueryKeys",
"(",
")",
"{",
"// can't query keys before bob has uploaded them",
"expect",
"(",
"bobTestClient",
".",
"deviceKeys",
")",
".",
"toBeTruthy",
"(",
")",
";",
"const",
"bobKeys",
"=",
"{",
"}",
";",
"bobKeys",
"[",
"bobDeviceId",
"]",
"=",
"bobTestClient",
".",
"deviceKeys",
";",
"aliTestClient",
".",
"httpBackend",
".",
"when",
"(",
"\"POST\"",
",",
"\"/keys/query\"",
")",
".",
"respond",
"(",
"200",
",",
"function",
"(",
"path",
",",
"content",
")",
"{",
"expect",
"(",
"content",
".",
"device_keys",
"[",
"bobUserId",
"]",
")",
".",
"toEqual",
"(",
"{",
"}",
",",
"\"Expected Alice to key query for \"",
"+",
"bobUserId",
"+",
"\", got \"",
"+",
"Object",
".",
"keys",
"(",
"content",
".",
"device_keys",
")",
",",
")",
";",
"const",
"result",
"=",
"{",
"}",
";",
"result",
"[",
"bobUserId",
"]",
"=",
"bobKeys",
";",
"return",
"{",
"device_keys",
":",
"result",
"}",
";",
"}",
")",
";",
"return",
"aliTestClient",
".",
"httpBackend",
".",
"flush",
"(",
"\"/keys/query\"",
",",
"1",
")",
";",
"}"
] | Set an expectation that ali will query bobs keys; then flush the http request.
@return {promise} resolves once the http request has completed. | [
"Set",
"an",
"expectation",
"that",
"ali",
"will",
"query",
"bobs",
"keys",
";",
"then",
"flush",
"the",
"http",
"request",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-crypto.spec.js#L67-L85 |
7,685 | matrix-org/matrix-js-sdk | spec/integ/matrix-client-crypto.spec.js | expectBobQueryKeys | function expectBobQueryKeys() {
// can't query keys before ali has uploaded them
expect(aliTestClient.deviceKeys).toBeTruthy();
const aliKeys = {};
aliKeys[aliDeviceId] = aliTestClient.deviceKeys;
console.log("query result will be", aliKeys);
bobTestClient.httpBackend.when(
"POST", "/keys/query",
).respond(200, function(path, content) {
expect(content.device_keys[aliUserId]).toEqual(
{},
"Expected Bob to key query for " + aliUserId + ", got " +
Object.keys(content.device_keys),
);
const result = {};
result[aliUserId] = aliKeys;
return {device_keys: result};
});
return bobTestClient.httpBackend.flush("/keys/query", 1);
} | javascript | function expectBobQueryKeys() {
// can't query keys before ali has uploaded them
expect(aliTestClient.deviceKeys).toBeTruthy();
const aliKeys = {};
aliKeys[aliDeviceId] = aliTestClient.deviceKeys;
console.log("query result will be", aliKeys);
bobTestClient.httpBackend.when(
"POST", "/keys/query",
).respond(200, function(path, content) {
expect(content.device_keys[aliUserId]).toEqual(
{},
"Expected Bob to key query for " + aliUserId + ", got " +
Object.keys(content.device_keys),
);
const result = {};
result[aliUserId] = aliKeys;
return {device_keys: result};
});
return bobTestClient.httpBackend.flush("/keys/query", 1);
} | [
"function",
"expectBobQueryKeys",
"(",
")",
"{",
"// can't query keys before ali has uploaded them",
"expect",
"(",
"aliTestClient",
".",
"deviceKeys",
")",
".",
"toBeTruthy",
"(",
")",
";",
"const",
"aliKeys",
"=",
"{",
"}",
";",
"aliKeys",
"[",
"aliDeviceId",
"]",
"=",
"aliTestClient",
".",
"deviceKeys",
";",
"console",
".",
"log",
"(",
"\"query result will be\"",
",",
"aliKeys",
")",
";",
"bobTestClient",
".",
"httpBackend",
".",
"when",
"(",
"\"POST\"",
",",
"\"/keys/query\"",
",",
")",
".",
"respond",
"(",
"200",
",",
"function",
"(",
"path",
",",
"content",
")",
"{",
"expect",
"(",
"content",
".",
"device_keys",
"[",
"aliUserId",
"]",
")",
".",
"toEqual",
"(",
"{",
"}",
",",
"\"Expected Bob to key query for \"",
"+",
"aliUserId",
"+",
"\", got \"",
"+",
"Object",
".",
"keys",
"(",
"content",
".",
"device_keys",
")",
",",
")",
";",
"const",
"result",
"=",
"{",
"}",
";",
"result",
"[",
"aliUserId",
"]",
"=",
"aliKeys",
";",
"return",
"{",
"device_keys",
":",
"result",
"}",
";",
"}",
")",
";",
"return",
"bobTestClient",
".",
"httpBackend",
".",
"flush",
"(",
"\"/keys/query\"",
",",
"1",
")",
";",
"}"
] | Set an expectation that bob will query alis keys; then flush the http request.
@return {promise} which resolves once the http request has completed. | [
"Set",
"an",
"expectation",
"that",
"bob",
"will",
"query",
"alis",
"keys",
";",
"then",
"flush",
"the",
"http",
"request",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-crypto.spec.js#L92-L113 |
7,686 | matrix-org/matrix-js-sdk | spec/integ/matrix-client-crypto.spec.js | expectAliClaimKeys | function expectAliClaimKeys() {
return bobTestClient.awaitOneTimeKeyUpload().then((keys) => {
aliTestClient.httpBackend.when(
"POST", "/keys/claim",
).respond(200, function(path, content) {
const claimType = content.one_time_keys[bobUserId][bobDeviceId];
expect(claimType).toEqual("signed_curve25519");
let keyId = null;
for (keyId in keys) {
if (bobTestClient.oneTimeKeys.hasOwnProperty(keyId)) {
if (keyId.indexOf(claimType + ":") === 0) {
break;
}
}
}
const result = {};
result[bobUserId] = {};
result[bobUserId][bobDeviceId] = {};
result[bobUserId][bobDeviceId][keyId] = keys[keyId];
return {one_time_keys: result};
});
}).then(() => {
// it can take a while to process the key query, so give it some extra
// time, and make sure the claim actually happens rather than ploughing on
// confusingly.
return aliTestClient.httpBackend.flush("/keys/claim", 1, 500).then((r) => {
expect(r).toEqual(1, "Ali did not claim Bob's keys");
});
});
} | javascript | function expectAliClaimKeys() {
return bobTestClient.awaitOneTimeKeyUpload().then((keys) => {
aliTestClient.httpBackend.when(
"POST", "/keys/claim",
).respond(200, function(path, content) {
const claimType = content.one_time_keys[bobUserId][bobDeviceId];
expect(claimType).toEqual("signed_curve25519");
let keyId = null;
for (keyId in keys) {
if (bobTestClient.oneTimeKeys.hasOwnProperty(keyId)) {
if (keyId.indexOf(claimType + ":") === 0) {
break;
}
}
}
const result = {};
result[bobUserId] = {};
result[bobUserId][bobDeviceId] = {};
result[bobUserId][bobDeviceId][keyId] = keys[keyId];
return {one_time_keys: result};
});
}).then(() => {
// it can take a while to process the key query, so give it some extra
// time, and make sure the claim actually happens rather than ploughing on
// confusingly.
return aliTestClient.httpBackend.flush("/keys/claim", 1, 500).then((r) => {
expect(r).toEqual(1, "Ali did not claim Bob's keys");
});
});
} | [
"function",
"expectAliClaimKeys",
"(",
")",
"{",
"return",
"bobTestClient",
".",
"awaitOneTimeKeyUpload",
"(",
")",
".",
"then",
"(",
"(",
"keys",
")",
"=>",
"{",
"aliTestClient",
".",
"httpBackend",
".",
"when",
"(",
"\"POST\"",
",",
"\"/keys/claim\"",
",",
")",
".",
"respond",
"(",
"200",
",",
"function",
"(",
"path",
",",
"content",
")",
"{",
"const",
"claimType",
"=",
"content",
".",
"one_time_keys",
"[",
"bobUserId",
"]",
"[",
"bobDeviceId",
"]",
";",
"expect",
"(",
"claimType",
")",
".",
"toEqual",
"(",
"\"signed_curve25519\"",
")",
";",
"let",
"keyId",
"=",
"null",
";",
"for",
"(",
"keyId",
"in",
"keys",
")",
"{",
"if",
"(",
"bobTestClient",
".",
"oneTimeKeys",
".",
"hasOwnProperty",
"(",
"keyId",
")",
")",
"{",
"if",
"(",
"keyId",
".",
"indexOf",
"(",
"claimType",
"+",
"\":\"",
")",
"===",
"0",
")",
"{",
"break",
";",
"}",
"}",
"}",
"const",
"result",
"=",
"{",
"}",
";",
"result",
"[",
"bobUserId",
"]",
"=",
"{",
"}",
";",
"result",
"[",
"bobUserId",
"]",
"[",
"bobDeviceId",
"]",
"=",
"{",
"}",
";",
"result",
"[",
"bobUserId",
"]",
"[",
"bobDeviceId",
"]",
"[",
"keyId",
"]",
"=",
"keys",
"[",
"keyId",
"]",
";",
"return",
"{",
"one_time_keys",
":",
"result",
"}",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"// it can take a while to process the key query, so give it some extra",
"// time, and make sure the claim actually happens rather than ploughing on",
"// confusingly.",
"return",
"aliTestClient",
".",
"httpBackend",
".",
"flush",
"(",
"\"/keys/claim\"",
",",
"1",
",",
"500",
")",
".",
"then",
"(",
"(",
"r",
")",
"=>",
"{",
"expect",
"(",
"r",
")",
".",
"toEqual",
"(",
"1",
",",
"\"Ali did not claim Bob's keys\"",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Set an expectation that ali will claim one of bob's keys; then flush the http request.
@return {promise} resolves once the http request has completed. | [
"Set",
"an",
"expectation",
"that",
"ali",
"will",
"claim",
"one",
"of",
"bob",
"s",
"keys",
";",
"then",
"flush",
"the",
"http",
"request",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-crypto.spec.js#L120-L149 |
7,687 | matrix-org/matrix-js-sdk | spec/integ/matrix-client-crypto.spec.js | aliSendsFirstMessage | function aliSendsFirstMessage() {
return Promise.all([
sendMessage(aliTestClient.client),
expectAliQueryKeys()
.then(expectAliClaimKeys)
.then(expectAliSendMessageRequest),
]).spread(function(_, ciphertext) {
return ciphertext;
});
} | javascript | function aliSendsFirstMessage() {
return Promise.all([
sendMessage(aliTestClient.client),
expectAliQueryKeys()
.then(expectAliClaimKeys)
.then(expectAliSendMessageRequest),
]).spread(function(_, ciphertext) {
return ciphertext;
});
} | [
"function",
"aliSendsFirstMessage",
"(",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"[",
"sendMessage",
"(",
"aliTestClient",
".",
"client",
")",
",",
"expectAliQueryKeys",
"(",
")",
".",
"then",
"(",
"expectAliClaimKeys",
")",
".",
"then",
"(",
"expectAliSendMessageRequest",
")",
",",
"]",
")",
".",
"spread",
"(",
"function",
"(",
"_",
",",
"ciphertext",
")",
"{",
"return",
"ciphertext",
";",
"}",
")",
";",
"}"
] | Ali sends a message, first claiming e2e keys. Set the expectations and
check the results.
@return {promise} which resolves to the ciphertext for Bob's device. | [
"Ali",
"sends",
"a",
"message",
"first",
"claiming",
"e2e",
"keys",
".",
"Set",
"the",
"expectations",
"and",
"check",
"the",
"results",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-crypto.spec.js#L200-L209 |
7,688 | matrix-org/matrix-js-sdk | spec/integ/matrix-client-crypto.spec.js | aliSendsMessage | function aliSendsMessage() {
return Promise.all([
sendMessage(aliTestClient.client),
expectAliSendMessageRequest(),
]).spread(function(_, ciphertext) {
return ciphertext;
});
} | javascript | function aliSendsMessage() {
return Promise.all([
sendMessage(aliTestClient.client),
expectAliSendMessageRequest(),
]).spread(function(_, ciphertext) {
return ciphertext;
});
} | [
"function",
"aliSendsMessage",
"(",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"[",
"sendMessage",
"(",
"aliTestClient",
".",
"client",
")",
",",
"expectAliSendMessageRequest",
"(",
")",
",",
"]",
")",
".",
"spread",
"(",
"function",
"(",
"_",
",",
"ciphertext",
")",
"{",
"return",
"ciphertext",
";",
"}",
")",
";",
"}"
] | Ali sends a message without first claiming e2e keys. Set the expectations
and check the results.
@return {promise} which resolves to the ciphertext for Bob's device. | [
"Ali",
"sends",
"a",
"message",
"without",
"first",
"claiming",
"e2e",
"keys",
".",
"Set",
"the",
"expectations",
"and",
"check",
"the",
"results",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-crypto.spec.js#L217-L224 |
7,689 | matrix-org/matrix-js-sdk | spec/integ/matrix-client-crypto.spec.js | expectAliSendMessageRequest | function expectAliSendMessageRequest() {
return expectSendMessageRequest(aliTestClient.httpBackend).then(function(content) {
aliMessages.push(content);
expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]);
const ciphertext = content.ciphertext[bobTestClient.getDeviceKey()];
expect(ciphertext).toBeTruthy();
return ciphertext;
});
} | javascript | function expectAliSendMessageRequest() {
return expectSendMessageRequest(aliTestClient.httpBackend).then(function(content) {
aliMessages.push(content);
expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]);
const ciphertext = content.ciphertext[bobTestClient.getDeviceKey()];
expect(ciphertext).toBeTruthy();
return ciphertext;
});
} | [
"function",
"expectAliSendMessageRequest",
"(",
")",
"{",
"return",
"expectSendMessageRequest",
"(",
"aliTestClient",
".",
"httpBackend",
")",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"aliMessages",
".",
"push",
"(",
"content",
")",
";",
"expect",
"(",
"utils",
".",
"keys",
"(",
"content",
".",
"ciphertext",
")",
")",
".",
"toEqual",
"(",
"[",
"bobTestClient",
".",
"getDeviceKey",
"(",
")",
"]",
")",
";",
"const",
"ciphertext",
"=",
"content",
".",
"ciphertext",
"[",
"bobTestClient",
".",
"getDeviceKey",
"(",
")",
"]",
";",
"expect",
"(",
"ciphertext",
")",
".",
"toBeTruthy",
"(",
")",
";",
"return",
"ciphertext",
";",
"}",
")",
";",
"}"
] | Set an expectation that Ali will send a message, and flush the request
@return {promise} which resolves to the ciphertext for Bob's device. | [
"Set",
"an",
"expectation",
"that",
"Ali",
"will",
"send",
"a",
"message",
"and",
"flush",
"the",
"request"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-crypto.spec.js#L247-L255 |
7,690 | matrix-org/matrix-js-sdk | spec/integ/matrix-client-crypto.spec.js | expectBobSendMessageRequest | function expectBobSendMessageRequest() {
return expectSendMessageRequest(bobTestClient.httpBackend).then(function(content) {
bobMessages.push(content);
const aliKeyId = "curve25519:" + aliDeviceId;
const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId];
expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]);
const ciphertext = content.ciphertext[aliDeviceCurve25519Key];
expect(ciphertext).toBeTruthy();
return ciphertext;
});
} | javascript | function expectBobSendMessageRequest() {
return expectSendMessageRequest(bobTestClient.httpBackend).then(function(content) {
bobMessages.push(content);
const aliKeyId = "curve25519:" + aliDeviceId;
const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId];
expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]);
const ciphertext = content.ciphertext[aliDeviceCurve25519Key];
expect(ciphertext).toBeTruthy();
return ciphertext;
});
} | [
"function",
"expectBobSendMessageRequest",
"(",
")",
"{",
"return",
"expectSendMessageRequest",
"(",
"bobTestClient",
".",
"httpBackend",
")",
".",
"then",
"(",
"function",
"(",
"content",
")",
"{",
"bobMessages",
".",
"push",
"(",
"content",
")",
";",
"const",
"aliKeyId",
"=",
"\"curve25519:\"",
"+",
"aliDeviceId",
";",
"const",
"aliDeviceCurve25519Key",
"=",
"aliTestClient",
".",
"deviceKeys",
".",
"keys",
"[",
"aliKeyId",
"]",
";",
"expect",
"(",
"utils",
".",
"keys",
"(",
"content",
".",
"ciphertext",
")",
")",
".",
"toEqual",
"(",
"[",
"aliDeviceCurve25519Key",
"]",
")",
";",
"const",
"ciphertext",
"=",
"content",
".",
"ciphertext",
"[",
"aliDeviceCurve25519Key",
"]",
";",
"expect",
"(",
"ciphertext",
")",
".",
"toBeTruthy",
"(",
")",
";",
"return",
"ciphertext",
";",
"}",
")",
";",
"}"
] | Set an expectation that Bob will send a message, and flush the request
@return {promise} which resolves to the ciphertext for Bob's device. | [
"Set",
"an",
"expectation",
"that",
"Bob",
"will",
"send",
"a",
"message",
"and",
"flush",
"the",
"request"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/spec/integ/matrix-client-crypto.spec.js#L262-L272 |
7,691 | matrix-org/matrix-js-sdk | src/crypto/OlmDevice.js | OlmDevice | function OlmDevice(cryptoStore) {
this._cryptoStore = cryptoStore;
this._pickleKey = "DEFAULT_KEY";
// don't know these until we load the account from storage in init()
this.deviceCurve25519Key = null;
this.deviceEd25519Key = null;
this._maxOneTimeKeys = null;
// we don't bother stashing outboundgroupsessions in the cryptoStore -
// instead we keep them here.
this._outboundGroupSessionStore = {};
// Store a set of decrypted message indexes for each group session.
// This partially mitigates a replay attack where a MITM resends a group
// message into the room.
//
// When we decrypt a message and the message index matches a previously
// decrypted message, one possible cause of that is that we are decrypting
// the same event, and may not indicate an actual replay attack. For
// example, this could happen if we receive events, forget about them, and
// then re-fetch them when we backfill. So we store the event ID and
// timestamp corresponding to each message index when we first decrypt it,
// and compare these against the event ID and timestamp every time we use
// that same index. If they match, then we're probably decrypting the same
// event and we don't consider it a replay attack.
//
// Keys are strings of form "<senderKey>|<session_id>|<message_index>"
// Values are objects of the form "{id: <event id>, timestamp: <ts>}"
this._inboundGroupSessionMessageIndexes = {};
// Keep track of sessions that we're starting, so that we don't start
// multiple sessions for the same device at the same time.
this._sessionsInProgress = {};
} | javascript | function OlmDevice(cryptoStore) {
this._cryptoStore = cryptoStore;
this._pickleKey = "DEFAULT_KEY";
// don't know these until we load the account from storage in init()
this.deviceCurve25519Key = null;
this.deviceEd25519Key = null;
this._maxOneTimeKeys = null;
// we don't bother stashing outboundgroupsessions in the cryptoStore -
// instead we keep them here.
this._outboundGroupSessionStore = {};
// Store a set of decrypted message indexes for each group session.
// This partially mitigates a replay attack where a MITM resends a group
// message into the room.
//
// When we decrypt a message and the message index matches a previously
// decrypted message, one possible cause of that is that we are decrypting
// the same event, and may not indicate an actual replay attack. For
// example, this could happen if we receive events, forget about them, and
// then re-fetch them when we backfill. So we store the event ID and
// timestamp corresponding to each message index when we first decrypt it,
// and compare these against the event ID and timestamp every time we use
// that same index. If they match, then we're probably decrypting the same
// event and we don't consider it a replay attack.
//
// Keys are strings of form "<senderKey>|<session_id>|<message_index>"
// Values are objects of the form "{id: <event id>, timestamp: <ts>}"
this._inboundGroupSessionMessageIndexes = {};
// Keep track of sessions that we're starting, so that we don't start
// multiple sessions for the same device at the same time.
this._sessionsInProgress = {};
} | [
"function",
"OlmDevice",
"(",
"cryptoStore",
")",
"{",
"this",
".",
"_cryptoStore",
"=",
"cryptoStore",
";",
"this",
".",
"_pickleKey",
"=",
"\"DEFAULT_KEY\"",
";",
"// don't know these until we load the account from storage in init()",
"this",
".",
"deviceCurve25519Key",
"=",
"null",
";",
"this",
".",
"deviceEd25519Key",
"=",
"null",
";",
"this",
".",
"_maxOneTimeKeys",
"=",
"null",
";",
"// we don't bother stashing outboundgroupsessions in the cryptoStore -",
"// instead we keep them here.",
"this",
".",
"_outboundGroupSessionStore",
"=",
"{",
"}",
";",
"// Store a set of decrypted message indexes for each group session.",
"// This partially mitigates a replay attack where a MITM resends a group",
"// message into the room.",
"//",
"// When we decrypt a message and the message index matches a previously",
"// decrypted message, one possible cause of that is that we are decrypting",
"// the same event, and may not indicate an actual replay attack. For",
"// example, this could happen if we receive events, forget about them, and",
"// then re-fetch them when we backfill. So we store the event ID and",
"// timestamp corresponding to each message index when we first decrypt it,",
"// and compare these against the event ID and timestamp every time we use",
"// that same index. If they match, then we're probably decrypting the same",
"// event and we don't consider it a replay attack.",
"//",
"// Keys are strings of form \"<senderKey>|<session_id>|<message_index>\"",
"// Values are objects of the form \"{id: <event id>, timestamp: <ts>}\"",
"this",
".",
"_inboundGroupSessionMessageIndexes",
"=",
"{",
"}",
";",
"// Keep track of sessions that we're starting, so that we don't start",
"// multiple sessions for the same device at the same time.",
"this",
".",
"_sessionsInProgress",
"=",
"{",
"}",
";",
"}"
] | The type of object we use for importing and exporting megolm session data.
@typedef {Object} module:crypto/OlmDevice.MegolmSessionData
@property {String} sender_key Sender's Curve25519 device key
@property {String[]} forwarding_curve25519_key_chain Devices which forwarded
this session to us (normally empty).
@property {Object<string, string>} sender_claimed_keys Other keys the sender claims.
@property {String} room_id Room this session is used in
@property {String} session_id Unique id for the session
@property {String} session_key Base64'ed key data
Manages the olm cryptography functions. Each OlmDevice has a single
OlmAccount and a number of OlmSessions.
Accounts and sessions are kept pickled in the cryptoStore.
@constructor
@alias module:crypto/OlmDevice
@param {Object} cryptoStore A store for crypto data
@property {string} deviceCurve25519Key Curve25519 key for the account
@property {string} deviceEd25519Key Ed25519 key for the account | [
"The",
"type",
"of",
"object",
"we",
"use",
"for",
"importing",
"and",
"exporting",
"megolm",
"session",
"data",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/crypto/OlmDevice.js#L72-L106 |
7,692 | matrix-org/matrix-js-sdk | src/crypto/algorithms/megolm.js | MegolmEncryption | function MegolmEncryption(params) {
base.EncryptionAlgorithm.call(this, params);
// the most recent attempt to set up a session. This is used to serialise
// the session setups, so that we have a race-free view of which session we
// are using, and which devices we have shared the keys with. It resolves
// with an OutboundSessionInfo (or undefined, for the first message in the
// room).
this._setupPromise = Promise.resolve();
// Map of outbound sessions by sessions ID. Used if we need a particular
// session (the session we're currently using to send is always obtained
// using _setupPromise).
this._outboundSessions = {};
// default rotation periods
this._sessionRotationPeriodMsgs = 100;
this._sessionRotationPeriodMs = 7 * 24 * 3600 * 1000;
if (params.config.rotation_period_ms !== undefined) {
this._sessionRotationPeriodMs = params.config.rotation_period_ms;
}
if (params.config.rotation_period_msgs !== undefined) {
this._sessionRotationPeriodMsgs = params.config.rotation_period_msgs;
}
} | javascript | function MegolmEncryption(params) {
base.EncryptionAlgorithm.call(this, params);
// the most recent attempt to set up a session. This is used to serialise
// the session setups, so that we have a race-free view of which session we
// are using, and which devices we have shared the keys with. It resolves
// with an OutboundSessionInfo (or undefined, for the first message in the
// room).
this._setupPromise = Promise.resolve();
// Map of outbound sessions by sessions ID. Used if we need a particular
// session (the session we're currently using to send is always obtained
// using _setupPromise).
this._outboundSessions = {};
// default rotation periods
this._sessionRotationPeriodMsgs = 100;
this._sessionRotationPeriodMs = 7 * 24 * 3600 * 1000;
if (params.config.rotation_period_ms !== undefined) {
this._sessionRotationPeriodMs = params.config.rotation_period_ms;
}
if (params.config.rotation_period_msgs !== undefined) {
this._sessionRotationPeriodMsgs = params.config.rotation_period_msgs;
}
} | [
"function",
"MegolmEncryption",
"(",
"params",
")",
"{",
"base",
".",
"EncryptionAlgorithm",
".",
"call",
"(",
"this",
",",
"params",
")",
";",
"// the most recent attempt to set up a session. This is used to serialise",
"// the session setups, so that we have a race-free view of which session we",
"// are using, and which devices we have shared the keys with. It resolves",
"// with an OutboundSessionInfo (or undefined, for the first message in the",
"// room).",
"this",
".",
"_setupPromise",
"=",
"Promise",
".",
"resolve",
"(",
")",
";",
"// Map of outbound sessions by sessions ID. Used if we need a particular",
"// session (the session we're currently using to send is always obtained",
"// using _setupPromise).",
"this",
".",
"_outboundSessions",
"=",
"{",
"}",
";",
"// default rotation periods",
"this",
".",
"_sessionRotationPeriodMsgs",
"=",
"100",
";",
"this",
".",
"_sessionRotationPeriodMs",
"=",
"7",
"*",
"24",
"*",
"3600",
"*",
"1000",
";",
"if",
"(",
"params",
".",
"config",
".",
"rotation_period_ms",
"!==",
"undefined",
")",
"{",
"this",
".",
"_sessionRotationPeriodMs",
"=",
"params",
".",
"config",
".",
"rotation_period_ms",
";",
"}",
"if",
"(",
"params",
".",
"config",
".",
"rotation_period_msgs",
"!==",
"undefined",
")",
"{",
"this",
".",
"_sessionRotationPeriodMsgs",
"=",
"params",
".",
"config",
".",
"rotation_period_msgs",
";",
"}",
"}"
] | Megolm encryption implementation
@constructor
@extends {module:crypto/algorithms/base.EncryptionAlgorithm}
@param {object} params parameters, as per
{@link module:crypto/algorithms/base.EncryptionAlgorithm} | [
"Megolm",
"encryption",
"implementation"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/crypto/algorithms/megolm.js#L137-L163 |
7,693 | matrix-org/matrix-js-sdk | src/models/group.js | Group | function Group(groupId) {
this.groupId = groupId;
this.name = null;
this.avatarUrl = null;
this.myMembership = null;
this.inviter = null;
} | javascript | function Group(groupId) {
this.groupId = groupId;
this.name = null;
this.avatarUrl = null;
this.myMembership = null;
this.inviter = null;
} | [
"function",
"Group",
"(",
"groupId",
")",
"{",
"this",
".",
"groupId",
"=",
"groupId",
";",
"this",
".",
"name",
"=",
"null",
";",
"this",
".",
"avatarUrl",
"=",
"null",
";",
"this",
".",
"myMembership",
"=",
"null",
";",
"this",
".",
"inviter",
"=",
"null",
";",
"}"
] | Construct a new Group.
@param {string} groupId The ID of this group.
@prop {string} groupId The ID of this group.
@prop {string} name The human-readable display name for this group.
@prop {string} avatarUrl The mxc URL for this group's avatar.
@prop {string} myMembership The logged in user's membership of this group
@prop {Object} inviter Infomation about the user who invited the logged in user
to the group, if myMembership is 'invite'.
@prop {string} inviter.userId The user ID of the inviter | [
"Construct",
"a",
"new",
"Group",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/group.js#L37-L43 |
7,694 | matrix-org/matrix-js-sdk | src/models/user.js | User | function User(userId) {
this.userId = userId;
this.presence = "offline";
this.presenceStatusMsg = null;
this._unstable_statusMessage = "";
this.displayName = userId;
this.rawDisplayName = userId;
this.avatarUrl = null;
this.lastActiveAgo = 0;
this.lastPresenceTs = 0;
this.currentlyActive = false;
this.events = {
presence: null,
profile: null,
};
this._updateModifiedTime();
} | javascript | function User(userId) {
this.userId = userId;
this.presence = "offline";
this.presenceStatusMsg = null;
this._unstable_statusMessage = "";
this.displayName = userId;
this.rawDisplayName = userId;
this.avatarUrl = null;
this.lastActiveAgo = 0;
this.lastPresenceTs = 0;
this.currentlyActive = false;
this.events = {
presence: null,
profile: null,
};
this._updateModifiedTime();
} | [
"function",
"User",
"(",
"userId",
")",
"{",
"this",
".",
"userId",
"=",
"userId",
";",
"this",
".",
"presence",
"=",
"\"offline\"",
";",
"this",
".",
"presenceStatusMsg",
"=",
"null",
";",
"this",
".",
"_unstable_statusMessage",
"=",
"\"\"",
";",
"this",
".",
"displayName",
"=",
"userId",
";",
"this",
".",
"rawDisplayName",
"=",
"userId",
";",
"this",
".",
"avatarUrl",
"=",
"null",
";",
"this",
".",
"lastActiveAgo",
"=",
"0",
";",
"this",
".",
"lastPresenceTs",
"=",
"0",
";",
"this",
".",
"currentlyActive",
"=",
"false",
";",
"this",
".",
"events",
"=",
"{",
"presence",
":",
"null",
",",
"profile",
":",
"null",
",",
"}",
";",
"this",
".",
"_updateModifiedTime",
"(",
")",
";",
"}"
] | Construct a new User. A User must have an ID and can optionally have extra
information associated with it.
@constructor
@param {string} userId Required. The ID of this user.
@prop {string} userId The ID of the user.
@prop {Object} info The info object supplied in the constructor.
@prop {string} displayName The 'displayname' of the user if known.
@prop {string} avatarUrl The 'avatar_url' of the user if known.
@prop {string} presence The presence enum if known.
@prop {string} presenceStatusMsg The presence status message if known.
@prop {Number} lastActiveAgo The time elapsed in ms since the user interacted
proactively with the server, or we saw a message from the user
@prop {Number} lastPresenceTs Timestamp (ms since the epoch) for when we last
received presence data for this user. We can subtract
lastActiveAgo from this to approximate an absolute value for
when a user was last active.
@prop {Boolean} currentlyActive Whether we should consider lastActiveAgo to be
an approximation and that the user should be seen as active 'now'
@prop {string} _unstable_statusMessage The status message for the user, if known. This is
different from the presenceStatusMsg in that this is not tied to
the user's presence, and should be represented differently.
@prop {Object} events The events describing this user.
@prop {MatrixEvent} events.presence The m.presence event for this user. | [
"Construct",
"a",
"new",
"User",
".",
"A",
"User",
"must",
"have",
"an",
"ID",
"and",
"can",
"optionally",
"have",
"extra",
"information",
"associated",
"with",
"it",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/models/user.js#L48-L64 |
7,695 | matrix-org/matrix-js-sdk | src/filter-component.js | FilterComponent | function FilterComponent(filter_json) {
this.filter_json = filter_json;
this.types = filter_json.types || null;
this.not_types = filter_json.not_types || [];
this.rooms = filter_json.rooms || null;
this.not_rooms = filter_json.not_rooms || [];
this.senders = filter_json.senders || null;
this.not_senders = filter_json.not_senders || [];
this.contains_url = filter_json.contains_url || null;
} | javascript | function FilterComponent(filter_json) {
this.filter_json = filter_json;
this.types = filter_json.types || null;
this.not_types = filter_json.not_types || [];
this.rooms = filter_json.rooms || null;
this.not_rooms = filter_json.not_rooms || [];
this.senders = filter_json.senders || null;
this.not_senders = filter_json.not_senders || [];
this.contains_url = filter_json.contains_url || null;
} | [
"function",
"FilterComponent",
"(",
"filter_json",
")",
"{",
"this",
".",
"filter_json",
"=",
"filter_json",
";",
"this",
".",
"types",
"=",
"filter_json",
".",
"types",
"||",
"null",
";",
"this",
".",
"not_types",
"=",
"filter_json",
".",
"not_types",
"||",
"[",
"]",
";",
"this",
".",
"rooms",
"=",
"filter_json",
".",
"rooms",
"||",
"null",
";",
"this",
".",
"not_rooms",
"=",
"filter_json",
".",
"not_rooms",
"||",
"[",
"]",
";",
"this",
".",
"senders",
"=",
"filter_json",
".",
"senders",
"||",
"null",
";",
"this",
".",
"not_senders",
"=",
"filter_json",
".",
"not_senders",
"||",
"[",
"]",
";",
"this",
".",
"contains_url",
"=",
"filter_json",
".",
"contains_url",
"||",
"null",
";",
"}"
] | FilterComponent is a section of a Filter definition which defines the
types, rooms, senders filters etc to be applied to a particular type of resource.
This is all ported over from synapse's Filter object.
N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as
'Filters' are referred to as 'FilterCollections'.
@constructor
@param {Object} filter_json the definition of this filter JSON, e.g. { 'contains_url': true } | [
"FilterComponent",
"is",
"a",
"section",
"of",
"a",
"Filter",
"definition",
"which",
"defines",
"the",
"types",
"rooms",
"senders",
"filters",
"etc",
"to",
"be",
"applied",
"to",
"a",
"particular",
"type",
"of",
"resource",
".",
"This",
"is",
"all",
"ported",
"over",
"from",
"synapse",
"s",
"Filter",
"object",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/filter-component.js#L48-L61 |
7,696 | matrix-org/matrix-js-sdk | src/http-api.js | function() {
const params = {
access_token: this.opts.accessToken,
};
return {
base: this.opts.baseUrl,
path: "/_matrix/media/v1/upload",
params: params,
};
} | javascript | function() {
const params = {
access_token: this.opts.accessToken,
};
return {
base: this.opts.baseUrl,
path: "/_matrix/media/v1/upload",
params: params,
};
} | [
"function",
"(",
")",
"{",
"const",
"params",
"=",
"{",
"access_token",
":",
"this",
".",
"opts",
".",
"accessToken",
",",
"}",
";",
"return",
"{",
"base",
":",
"this",
".",
"opts",
".",
"baseUrl",
",",
"path",
":",
"\"/_matrix/media/v1/upload\"",
",",
"params",
":",
"params",
",",
"}",
";",
"}"
] | Get the content repository url with query parameters.
@return {Object} An object with a 'base', 'path' and 'params' for base URL,
path and query parameters respectively. | [
"Get",
"the",
"content",
"repository",
"url",
"with",
"query",
"parameters",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/http-api.js#L98-L107 |
|
7,697 | matrix-org/matrix-js-sdk | src/http-api.js | function(path, queryParams, prefix) {
let queryString = "";
if (queryParams) {
queryString = "?" + utils.encodeParams(queryParams);
}
return this.opts.baseUrl + prefix + path + queryString;
} | javascript | function(path, queryParams, prefix) {
let queryString = "";
if (queryParams) {
queryString = "?" + utils.encodeParams(queryParams);
}
return this.opts.baseUrl + prefix + path + queryString;
} | [
"function",
"(",
"path",
",",
"queryParams",
",",
"prefix",
")",
"{",
"let",
"queryString",
"=",
"\"\"",
";",
"if",
"(",
"queryParams",
")",
"{",
"queryString",
"=",
"\"?\"",
"+",
"utils",
".",
"encodeParams",
"(",
"queryParams",
")",
";",
"}",
"return",
"this",
".",
"opts",
".",
"baseUrl",
"+",
"prefix",
"+",
"path",
"+",
"queryString",
";",
"}"
] | Form and return a homeserver request URL based on the given path
params and prefix.
@param {string} path The HTTP path <b>after</b> the supplied prefix e.g.
"/createRoom".
@param {Object} queryParams A dict of query params (these will NOT be
urlencoded).
@param {string} prefix The full prefix to use e.g.
"/_matrix/client/v2_alpha".
@return {string} URL | [
"Form",
"and",
"return",
"a",
"homeserver",
"request",
"URL",
"based",
"on",
"the",
"given",
"path",
"params",
"and",
"prefix",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/http-api.js#L641-L647 |
|
7,698 | matrix-org/matrix-js-sdk | src/http-api.js | parseErrorResponse | function parseErrorResponse(response, body) {
const httpStatus = response.statusCode;
const contentType = getResponseContentType(response);
let err;
if (contentType) {
if (contentType.type === 'application/json') {
err = new module.exports.MatrixError(JSON.parse(body));
} else if (contentType.type === 'text/plain') {
err = new Error(`Server returned ${httpStatus} error: ${body}`);
}
}
if (!err) {
err = new Error(`Server returned ${httpStatus} error`);
}
err.httpStatus = httpStatus;
return err;
} | javascript | function parseErrorResponse(response, body) {
const httpStatus = response.statusCode;
const contentType = getResponseContentType(response);
let err;
if (contentType) {
if (contentType.type === 'application/json') {
err = new module.exports.MatrixError(JSON.parse(body));
} else if (contentType.type === 'text/plain') {
err = new Error(`Server returned ${httpStatus} error: ${body}`);
}
}
if (!err) {
err = new Error(`Server returned ${httpStatus} error`);
}
err.httpStatus = httpStatus;
return err;
} | [
"function",
"parseErrorResponse",
"(",
"response",
",",
"body",
")",
"{",
"const",
"httpStatus",
"=",
"response",
".",
"statusCode",
";",
"const",
"contentType",
"=",
"getResponseContentType",
"(",
"response",
")",
";",
"let",
"err",
";",
"if",
"(",
"contentType",
")",
"{",
"if",
"(",
"contentType",
".",
"type",
"===",
"'application/json'",
")",
"{",
"err",
"=",
"new",
"module",
".",
"exports",
".",
"MatrixError",
"(",
"JSON",
".",
"parse",
"(",
"body",
")",
")",
";",
"}",
"else",
"if",
"(",
"contentType",
".",
"type",
"===",
"'text/plain'",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"`",
"${",
"httpStatus",
"}",
"${",
"body",
"}",
"`",
")",
";",
"}",
"}",
"if",
"(",
"!",
"err",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"`",
"${",
"httpStatus",
"}",
"`",
")",
";",
"}",
"err",
".",
"httpStatus",
"=",
"httpStatus",
";",
"return",
"err",
";",
"}"
] | Attempt to turn an HTTP error response into a Javascript Error.
If it is a JSON response, we will parse it into a MatrixError. Otherwise
we return a generic Error.
@param {XMLHttpRequest|http.IncomingMessage} response response object
@param {String} body raw body of the response
@returns {Error} | [
"Attempt",
"to",
"turn",
"an",
"HTTP",
"error",
"response",
"into",
"a",
"Javascript",
"Error",
"."
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/http-api.js#L866-L884 |
7,699 | matrix-org/matrix-js-sdk | src/client.js | keysFromRecoverySession | function keysFromRecoverySession(sessions, decryptionKey, roomId) {
const keys = [];
for (const [sessionId, sessionData] of Object.entries(sessions)) {
try {
const decrypted = keyFromRecoverySession(sessionData, decryptionKey);
decrypted.session_id = sessionId;
decrypted.room_id = roomId;
keys.push(decrypted);
} catch (e) {
console.log("Failed to decrypt session from backup");
}
}
return keys;
} | javascript | function keysFromRecoverySession(sessions, decryptionKey, roomId) {
const keys = [];
for (const [sessionId, sessionData] of Object.entries(sessions)) {
try {
const decrypted = keyFromRecoverySession(sessionData, decryptionKey);
decrypted.session_id = sessionId;
decrypted.room_id = roomId;
keys.push(decrypted);
} catch (e) {
console.log("Failed to decrypt session from backup");
}
}
return keys;
} | [
"function",
"keysFromRecoverySession",
"(",
"sessions",
",",
"decryptionKey",
",",
"roomId",
")",
"{",
"const",
"keys",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"[",
"sessionId",
",",
"sessionData",
"]",
"of",
"Object",
".",
"entries",
"(",
"sessions",
")",
")",
"{",
"try",
"{",
"const",
"decrypted",
"=",
"keyFromRecoverySession",
"(",
"sessionData",
",",
"decryptionKey",
")",
";",
"decrypted",
".",
"session_id",
"=",
"sessionId",
";",
"decrypted",
".",
"room_id",
"=",
"roomId",
";",
"keys",
".",
"push",
"(",
"decrypted",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"\"Failed to decrypt session from backup\"",
")",
";",
"}",
"}",
"return",
"keys",
";",
"}"
] | 6 hours - an arbitrary value | [
"6",
"hours",
"-",
"an",
"arbitrary",
"value"
] | ee8a4698a94a4a6bfaded61d6108492a04aa0d4e | https://github.com/matrix-org/matrix-js-sdk/blob/ee8a4698a94a4a6bfaded61d6108492a04aa0d4e/src/client.js#L64-L77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.