zulip/web/src/presence.ts

287 lines
8.6 KiB
TypeScript
Raw Normal View History

import * as people from "./people";
import {realm} from "./state_data";
import {user_settings} from "./user_settings";
2020-08-20 21:24:06 +02:00
export type RawPresence = {
server_timestamp: number;
active_timestamp?: number | undefined;
idle_timestamp?: number | undefined;
};
export type PresenceStatus = {
status: "active" | "idle" | "offline";
last_active?: number | undefined;
};
export type PresenceInfoFromEvent = {
website: {
client: "website";
status: "idle" | "active";
timestamp: number;
pushable: boolean;
};
};
// This module just manages data. See activity.js for
// the UI of our buddy list.
presence: Prep for upcoming changes to server data. In the next commit we're going to change what the server sends for the following: - page_params - server responses to /json/users/me/presence We will **not** yet be changing the format of the data that we get in events when users update their presence. It's also just a bit in flux what our final formats will be for various presence payloads, and different optimizations may lead us to use different data structures in different payloads. So for now we decouple these two things: raw_info: this is intended to represent a snapshot of the latest data from the server, including some data like timestamps that are only used in downstream calculations and not user-facing exports.presence_info: this is calculated info for modules like buddy_data that just need to know active vs. idle and last_active_date Another change that happens here is we rename set_info_for_user to update_info_for_event, which just makes it clear that the function expects data in the "event" format (as opposed to the format for page_params or server responses). As of now keeping the intermediate raw_info data around feels slightly awkward, because we just immediately calculate presence_info for any kind of update. This may be sorta surprising if you just skim the code and see the various timeout constants. You would think we might be automatically expiring "active" statuses in the client due to the simple passage of time, but in fact the precise places we do this are all triggered by new data from the server and we re-calculate statuses immediately. (There are indirect ways that clients have timing logic, since they ask the server for new data at various intervals, but a smarter client could simply expire users on its own, or at least with a more efficient transfer of info between it and the server. One of the thing that complicates client-side logic is that server and client clocks may be out of sync. Also, it's not inherently super expensive to get updates from the server.)
2020-02-07 17:19:03 +01:00
// The following Maps have user_id as the key. Some of the
// user_ids may not yet be registered in people.js.
// See the long comment in `set_info` below for details.
presence: Prep for upcoming changes to server data. In the next commit we're going to change what the server sends for the following: - page_params - server responses to /json/users/me/presence We will **not** yet be changing the format of the data that we get in events when users update their presence. It's also just a bit in flux what our final formats will be for various presence payloads, and different optimizations may lead us to use different data structures in different payloads. So for now we decouple these two things: raw_info: this is intended to represent a snapshot of the latest data from the server, including some data like timestamps that are only used in downstream calculations and not user-facing exports.presence_info: this is calculated info for modules like buddy_data that just need to know active vs. idle and last_active_date Another change that happens here is we rename set_info_for_user to update_info_for_event, which just makes it clear that the function expects data in the "event" format (as opposed to the format for page_params or server responses). As of now keeping the intermediate raw_info data around feels slightly awkward, because we just immediately calculate presence_info for any kind of update. This may be sorta surprising if you just skim the code and see the various timeout constants. You would think we might be automatically expiring "active" statuses in the client due to the simple passage of time, but in fact the precise places we do this are all triggered by new data from the server and we re-calculate statuses immediately. (There are indirect ways that clients have timing logic, since they ask the server for new data at various intervals, but a smarter client could simply expire users on its own, or at least with a more efficient transfer of info between it and the server. One of the thing that complicates client-side logic is that server and client clocks may be out of sync. Also, it's not inherently super expensive to get updates from the server.)
2020-02-07 17:19:03 +01:00
// In future commits we'll use raw_info to facilitate
// handling server events and/or timeout events.
const raw_info = new Map<number, RawPresence>();
export const presence_info = new Map<number, PresenceStatus>();
// We use this internally and export it for testing convenience.
export function clear_internal_data(): void {
raw_info.clear();
presence_info.clear();
}
const BIG_REALM_COUNT = 250;
export function get_status(user_id: number): PresenceStatus["status"] {
if (people.is_my_user_id(user_id)) {
if (user_settings.presence_enabled) {
// if the current user is sharing presence, they always see themselves as online.
return "active";
}
// if the current user is not sharing presence, they always see themselves as offline.
return "offline";
}
if (presence_info.has(user_id)) {
return presence_info.get(user_id)!.status;
}
return "offline";
}
export function get_user_ids(): number[] {
return [...presence_info.keys()];
}
export function status_from_raw(raw: RawPresence): PresenceStatus {
/*
Example of `raw`:
{
active_timestamp: 1585745133
idle_timestamp: 1585745091
server_timestamp: 1585745140
}
*/
/* Mark users as offline after this many seconds since their last checkin, */
const offline_threshold_secs = realm.server_presence_offline_threshold_seconds;
function age(timestamp = 0): number {
return raw.server_timestamp - timestamp;
}
const active_timestamp = raw.active_timestamp;
const idle_timestamp = raw.idle_timestamp;
let last_active: number | undefined;
if (active_timestamp !== undefined || idle_timestamp !== undefined) {
last_active = Math.max(active_timestamp ?? 0, idle_timestamp ?? 0);
}
/*
If the server sends us `active_timestamp`, this
means at least one client was active at this time
(and hasn't changed since).
As long as the timestamp is current enough, we will
show the user as active (even if there's a newer
timestamp for idle).
*/
if (age(active_timestamp) < offline_threshold_secs) {
return {
status: "active",
last_active,
};
}
if (age(idle_timestamp) < offline_threshold_secs) {
return {
status: "idle",
last_active,
};
}
return {
status: "offline",
last_active,
};
}
export function update_info_from_event(
user_id: number,
info: PresenceInfoFromEvent,
server_timestamp: number,
): void {
/*
Example of `info`:
{
website: {
client: 'website',
pushable: false,
status: 'active',
timestamp: 1585745225
}
}
Example of `raw`:
{
active_timestamp: 1585745133
idle_timestamp: 1585745091
server_timestamp: 1585745140
}
*/
const raw = raw_info.get(user_id) ?? {
server_timestamp: 0,
};
raw.server_timestamp = server_timestamp;
presence: Prep for upcoming changes to server data. In the next commit we're going to change what the server sends for the following: - page_params - server responses to /json/users/me/presence We will **not** yet be changing the format of the data that we get in events when users update their presence. It's also just a bit in flux what our final formats will be for various presence payloads, and different optimizations may lead us to use different data structures in different payloads. So for now we decouple these two things: raw_info: this is intended to represent a snapshot of the latest data from the server, including some data like timestamps that are only used in downstream calculations and not user-facing exports.presence_info: this is calculated info for modules like buddy_data that just need to know active vs. idle and last_active_date Another change that happens here is we rename set_info_for_user to update_info_for_event, which just makes it clear that the function expects data in the "event" format (as opposed to the format for page_params or server responses). As of now keeping the intermediate raw_info data around feels slightly awkward, because we just immediately calculate presence_info for any kind of update. This may be sorta surprising if you just skim the code and see the various timeout constants. You would think we might be automatically expiring "active" statuses in the client due to the simple passage of time, but in fact the precise places we do this are all triggered by new data from the server and we re-calculate statuses immediately. (There are indirect ways that clients have timing logic, since they ask the server for new data at various intervals, but a smarter client could simply expire users on its own, or at least with a more efficient transfer of info between it and the server. One of the thing that complicates client-side logic is that server and client clocks may be out of sync. Also, it's not inherently super expensive to get updates from the server.)
2020-02-07 17:19:03 +01:00
for (const rec of Object.values(info)) {
if (rec.status === "active" && rec.timestamp > (raw.active_timestamp ?? 0)) {
raw.active_timestamp = rec.timestamp;
}
if (rec.status === "idle" && rec.timestamp > (raw.idle_timestamp ?? 0)) {
raw.idle_timestamp = rec.timestamp;
}
}
raw_info.set(user_id, raw);
const status = status_from_raw(raw);
presence_info.set(user_id, status);
}
export function set_info(
presences: Record<number, Omit<RawPresence, "server_timestamp">>,
server_timestamp: number,
): void {
/*
Example `presences` data:
{
6: Object { idle_timestamp: 1585746028 },
7: Object { active_timestamp: 1585745774 },
8: Object { active_timestamp: 1585745578 }
}
*/
clear_internal_data();
for (const [user_id_str, info] of Object.entries(presences)) {
const user_id = Number.parseInt(user_id_str, 10);
presence: Prep for upcoming changes to server data. In the next commit we're going to change what the server sends for the following: - page_params - server responses to /json/users/me/presence We will **not** yet be changing the format of the data that we get in events when users update their presence. It's also just a bit in flux what our final formats will be for various presence payloads, and different optimizations may lead us to use different data structures in different payloads. So for now we decouple these two things: raw_info: this is intended to represent a snapshot of the latest data from the server, including some data like timestamps that are only used in downstream calculations and not user-facing exports.presence_info: this is calculated info for modules like buddy_data that just need to know active vs. idle and last_active_date Another change that happens here is we rename set_info_for_user to update_info_for_event, which just makes it clear that the function expects data in the "event" format (as opposed to the format for page_params or server responses). As of now keeping the intermediate raw_info data around feels slightly awkward, because we just immediately calculate presence_info for any kind of update. This may be sorta surprising if you just skim the code and see the various timeout constants. You would think we might be automatically expiring "active" statuses in the client due to the simple passage of time, but in fact the precise places we do this are all triggered by new data from the server and we re-calculate statuses immediately. (There are indirect ways that clients have timing logic, since they ask the server for new data at various intervals, but a smarter client could simply expire users on its own, or at least with a more efficient transfer of info between it and the server. One of the thing that complicates client-side logic is that server and client clocks may be out of sync. Also, it's not inherently super expensive to get updates from the server.)
2020-02-07 17:19:03 +01:00
// Note: In contrast with all other state updates received
2024-04-26 02:33:14 +02:00
// from the server, presence data is updated via a
// polling process rather than the events system
// (server_events_dispatch.js).
//
// This means that if we're coming back from being offline and
// new users were created in the meantime, we may see user IDs
// not yet present in people.js if server_events doesn't have
// current data (or we've been offline, our event queue was
// GC'ed, and we're about to reload). Such user_ids being
// present could, in turn, create spammy downstream exceptions
// when rendering the buddy list. To address this, we check
// if the user ID is not yet present in people.js, and if it
// is, we skip storing that user (we'll see them again in the
// next presence request in 1 minute anyway).
//
// It's important to check both suspect_offline and
// reload_state.is_in_progress, because races where presence
// returns data on users not yet received via the server_events
// system are common in both situations.
const person = people.maybe_get_user_by_id(user_id, true);
if (person === undefined || person.is_inaccessible_user) {
// There are a number of situations where it is expected
// that we get presence data for a user ID that we do
// not have in our user database, including when we're
// offline/reloading (watchdog.suspects_user_is_offline()
// || reload_state.is_in_progress()), when
// CAN_ACCESS_ALL_USERS_GROUP_LIMITS_PRESENCE is disabled,
// and whenever presence wins a race with the events system
// for events regarding a newly created or visible user.
//
// Either way, we deal by skipping this user and
// continuing with processing everyone else.
continue;
}
presence: Prep for upcoming changes to server data. In the next commit we're going to change what the server sends for the following: - page_params - server responses to /json/users/me/presence We will **not** yet be changing the format of the data that we get in events when users update their presence. It's also just a bit in flux what our final formats will be for various presence payloads, and different optimizations may lead us to use different data structures in different payloads. So for now we decouple these two things: raw_info: this is intended to represent a snapshot of the latest data from the server, including some data like timestamps that are only used in downstream calculations and not user-facing exports.presence_info: this is calculated info for modules like buddy_data that just need to know active vs. idle and last_active_date Another change that happens here is we rename set_info_for_user to update_info_for_event, which just makes it clear that the function expects data in the "event" format (as opposed to the format for page_params or server responses). As of now keeping the intermediate raw_info data around feels slightly awkward, because we just immediately calculate presence_info for any kind of update. This may be sorta surprising if you just skim the code and see the various timeout constants. You would think we might be automatically expiring "active" statuses in the client due to the simple passage of time, but in fact the precise places we do this are all triggered by new data from the server and we re-calculate statuses immediately. (There are indirect ways that clients have timing logic, since they ask the server for new data at various intervals, but a smarter client could simply expire users on its own, or at least with a more efficient transfer of info between it and the server. One of the thing that complicates client-side logic is that server and client clocks may be out of sync. Also, it's not inherently super expensive to get updates from the server.)
2020-02-07 17:19:03 +01:00
const raw: RawPresence = {
server_timestamp,
active_timestamp: info.active_timestamp,
idle_timestamp: info.idle_timestamp,
};
presence: Prep for upcoming changes to server data. In the next commit we're going to change what the server sends for the following: - page_params - server responses to /json/users/me/presence We will **not** yet be changing the format of the data that we get in events when users update their presence. It's also just a bit in flux what our final formats will be for various presence payloads, and different optimizations may lead us to use different data structures in different payloads. So for now we decouple these two things: raw_info: this is intended to represent a snapshot of the latest data from the server, including some data like timestamps that are only used in downstream calculations and not user-facing exports.presence_info: this is calculated info for modules like buddy_data that just need to know active vs. idle and last_active_date Another change that happens here is we rename set_info_for_user to update_info_for_event, which just makes it clear that the function expects data in the "event" format (as opposed to the format for page_params or server responses). As of now keeping the intermediate raw_info data around feels slightly awkward, because we just immediately calculate presence_info for any kind of update. This may be sorta surprising if you just skim the code and see the various timeout constants. You would think we might be automatically expiring "active" statuses in the client due to the simple passage of time, but in fact the precise places we do this are all triggered by new data from the server and we re-calculate statuses immediately. (There are indirect ways that clients have timing logic, since they ask the server for new data at various intervals, but a smarter client could simply expire users on its own, or at least with a more efficient transfer of info between it and the server. One of the thing that complicates client-side logic is that server and client clocks may be out of sync. Also, it's not inherently super expensive to get updates from the server.)
2020-02-07 17:19:03 +01:00
raw_info.set(user_id, raw);
const status = status_from_raw(raw);
presence_info.set(user_id, status);
}
update_info_for_small_realm();
}
export function update_info_for_small_realm(): void {
if (people.get_active_human_count() >= BIG_REALM_COUNT) {
// For big realms, we don't want to bloat our buddy
// lists with lots of long-time-inactive users.
return;
}
// For small realms, we create presence info for users
// that the server didn't include in its presence update.
const persons = people.get_realm_users();
js: Automatically convert _.each to for…of. This commit was automatically generated by the following script, followed by lint --fix and a few small manual lint-related cleanups. import * as babelParser from "recast/parsers/babel"; import * as recast from "recast"; import * as tsParser from "recast/parsers/typescript"; import { builders as b, namedTypes as n } from "ast-types"; import { Context } from "ast-types/lib/path-visitor"; import K from "ast-types/gen/kinds"; import { NodePath } from "ast-types/lib/node-path"; import assert from "assert"; import fs from "fs"; import path from "path"; import process from "process"; const checkExpression = (node: n.Node): node is K.ExpressionKind => n.Expression.check(node); const checkStatement = (node: n.Node): node is K.StatementKind => n.Statement.check(node); for (const file of process.argv.slice(2)) { console.log("Parsing", file); const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), { parser: path.extname(file) === ".ts" ? tsParser : babelParser, }); let changed = false; let inLoop = false; let replaceReturn = false; const visitLoop = (...args: string[]) => function(this: Context, path: NodePath) { for (const arg of args) { this.visit(path.get(arg)); } const old = { inLoop }; inLoop = true; this.visit(path.get("body")); inLoop = old.inLoop; return false; }; recast.visit(ast, { visitDoWhileStatement: visitLoop("test"), visitExpressionStatement(path) { const { expression, comments } = path.node; let valueOnly; if ( n.CallExpression.check(expression) && n.MemberExpression.check(expression.callee) && !expression.callee.computed && n.Identifier.check(expression.callee.object) && expression.callee.object.name === "_" && n.Identifier.check(expression.callee.property) && ["each", "forEach"].includes(expression.callee.property.name) && [2, 3].includes(expression.arguments.length) && checkExpression(expression.arguments[0]) && (n.FunctionExpression.check(expression.arguments[1]) || n.ArrowFunctionExpression.check(expression.arguments[1])) && [1, 2].includes(expression.arguments[1].params.length) && n.Identifier.check(expression.arguments[1].params[0]) && ((valueOnly = expression.arguments[1].params[1] === undefined) || n.Identifier.check(expression.arguments[1].params[1])) && (expression.arguments[2] === undefined || n.ThisExpression.check(expression.arguments[2])) ) { const old = { inLoop, replaceReturn }; inLoop = false; replaceReturn = true; this.visit( path .get("expression") .get("arguments") .get(1) .get("body") ); inLoop = old.inLoop; replaceReturn = old.replaceReturn; const [right, { body, params }] = expression.arguments; const loop = b.forOfStatement( b.variableDeclaration("let", [ b.variableDeclarator( valueOnly ? params[0] : b.arrayPattern([params[1], params[0]]) ), ]), valueOnly ? right : b.callExpression( b.memberExpression(right, b.identifier("entries")), [] ), checkStatement(body) ? body : b.expressionStatement(body) ); loop.comments = comments; path.replace(loop); changed = true; } this.traverse(path); }, visitForStatement: visitLoop("init", "test", "update"), visitForInStatement: visitLoop("left", "right"), visitForOfStatement: visitLoop("left", "right"), visitFunction(path) { this.visit(path.get("params")); const old = { replaceReturn }; replaceReturn = false; this.visit(path.get("body")); replaceReturn = old.replaceReturn; return false; }, visitReturnStatement(path) { if (replaceReturn) { assert(!inLoop); // could use labeled continue if this ever fires const { argument, comments } = path.node; if (argument === null) { const s = b.continueStatement(); s.comments = comments; path.replace(s); } else { const s = b.expressionStatement(argument); s.comments = comments; path.replace(s, b.continueStatement()); } return false; } this.traverse(path); }, visitWhileStatement: visitLoop("test"), }); if (changed) { console.log("Writing", file); fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" }); } } Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 06:19:47 +01:00
for (const person of persons) {
const user_id = person.user_id;
let status: PresenceStatus["status"] = "offline";
if (presence_info.has(user_id)) {
// this is normal, we have data for active
// users that we don't want to clobber.
js: Automatically convert _.each to for…of. This commit was automatically generated by the following script, followed by lint --fix and a few small manual lint-related cleanups. import * as babelParser from "recast/parsers/babel"; import * as recast from "recast"; import * as tsParser from "recast/parsers/typescript"; import { builders as b, namedTypes as n } from "ast-types"; import { Context } from "ast-types/lib/path-visitor"; import K from "ast-types/gen/kinds"; import { NodePath } from "ast-types/lib/node-path"; import assert from "assert"; import fs from "fs"; import path from "path"; import process from "process"; const checkExpression = (node: n.Node): node is K.ExpressionKind => n.Expression.check(node); const checkStatement = (node: n.Node): node is K.StatementKind => n.Statement.check(node); for (const file of process.argv.slice(2)) { console.log("Parsing", file); const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), { parser: path.extname(file) === ".ts" ? tsParser : babelParser, }); let changed = false; let inLoop = false; let replaceReturn = false; const visitLoop = (...args: string[]) => function(this: Context, path: NodePath) { for (const arg of args) { this.visit(path.get(arg)); } const old = { inLoop }; inLoop = true; this.visit(path.get("body")); inLoop = old.inLoop; return false; }; recast.visit(ast, { visitDoWhileStatement: visitLoop("test"), visitExpressionStatement(path) { const { expression, comments } = path.node; let valueOnly; if ( n.CallExpression.check(expression) && n.MemberExpression.check(expression.callee) && !expression.callee.computed && n.Identifier.check(expression.callee.object) && expression.callee.object.name === "_" && n.Identifier.check(expression.callee.property) && ["each", "forEach"].includes(expression.callee.property.name) && [2, 3].includes(expression.arguments.length) && checkExpression(expression.arguments[0]) && (n.FunctionExpression.check(expression.arguments[1]) || n.ArrowFunctionExpression.check(expression.arguments[1])) && [1, 2].includes(expression.arguments[1].params.length) && n.Identifier.check(expression.arguments[1].params[0]) && ((valueOnly = expression.arguments[1].params[1] === undefined) || n.Identifier.check(expression.arguments[1].params[1])) && (expression.arguments[2] === undefined || n.ThisExpression.check(expression.arguments[2])) ) { const old = { inLoop, replaceReturn }; inLoop = false; replaceReturn = true; this.visit( path .get("expression") .get("arguments") .get(1) .get("body") ); inLoop = old.inLoop; replaceReturn = old.replaceReturn; const [right, { body, params }] = expression.arguments; const loop = b.forOfStatement( b.variableDeclaration("let", [ b.variableDeclarator( valueOnly ? params[0] : b.arrayPattern([params[1], params[0]]) ), ]), valueOnly ? right : b.callExpression( b.memberExpression(right, b.identifier("entries")), [] ), checkStatement(body) ? body : b.expressionStatement(body) ); loop.comments = comments; path.replace(loop); changed = true; } this.traverse(path); }, visitForStatement: visitLoop("init", "test", "update"), visitForInStatement: visitLoop("left", "right"), visitForOfStatement: visitLoop("left", "right"), visitFunction(path) { this.visit(path.get("params")); const old = { replaceReturn }; replaceReturn = false; this.visit(path.get("body")); replaceReturn = old.replaceReturn; return false; }, visitReturnStatement(path) { if (replaceReturn) { assert(!inLoop); // could use labeled continue if this ever fires const { argument, comments } = path.node; if (argument === null) { const s = b.continueStatement(); s.comments = comments; path.replace(s); } else { const s = b.expressionStatement(argument); s.comments = comments; path.replace(s, b.continueStatement()); } return false; } this.traverse(path); }, visitWhileStatement: visitLoop("test"), }); if (changed) { console.log("Writing", file); fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" }); } } Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 06:19:47 +01:00
continue;
}
if (person.is_bot) {
// we don't show presence for bots
js: Automatically convert _.each to for…of. This commit was automatically generated by the following script, followed by lint --fix and a few small manual lint-related cleanups. import * as babelParser from "recast/parsers/babel"; import * as recast from "recast"; import * as tsParser from "recast/parsers/typescript"; import { builders as b, namedTypes as n } from "ast-types"; import { Context } from "ast-types/lib/path-visitor"; import K from "ast-types/gen/kinds"; import { NodePath } from "ast-types/lib/node-path"; import assert from "assert"; import fs from "fs"; import path from "path"; import process from "process"; const checkExpression = (node: n.Node): node is K.ExpressionKind => n.Expression.check(node); const checkStatement = (node: n.Node): node is K.StatementKind => n.Statement.check(node); for (const file of process.argv.slice(2)) { console.log("Parsing", file); const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), { parser: path.extname(file) === ".ts" ? tsParser : babelParser, }); let changed = false; let inLoop = false; let replaceReturn = false; const visitLoop = (...args: string[]) => function(this: Context, path: NodePath) { for (const arg of args) { this.visit(path.get(arg)); } const old = { inLoop }; inLoop = true; this.visit(path.get("body")); inLoop = old.inLoop; return false; }; recast.visit(ast, { visitDoWhileStatement: visitLoop("test"), visitExpressionStatement(path) { const { expression, comments } = path.node; let valueOnly; if ( n.CallExpression.check(expression) && n.MemberExpression.check(expression.callee) && !expression.callee.computed && n.Identifier.check(expression.callee.object) && expression.callee.object.name === "_" && n.Identifier.check(expression.callee.property) && ["each", "forEach"].includes(expression.callee.property.name) && [2, 3].includes(expression.arguments.length) && checkExpression(expression.arguments[0]) && (n.FunctionExpression.check(expression.arguments[1]) || n.ArrowFunctionExpression.check(expression.arguments[1])) && [1, 2].includes(expression.arguments[1].params.length) && n.Identifier.check(expression.arguments[1].params[0]) && ((valueOnly = expression.arguments[1].params[1] === undefined) || n.Identifier.check(expression.arguments[1].params[1])) && (expression.arguments[2] === undefined || n.ThisExpression.check(expression.arguments[2])) ) { const old = { inLoop, replaceReturn }; inLoop = false; replaceReturn = true; this.visit( path .get("expression") .get("arguments") .get(1) .get("body") ); inLoop = old.inLoop; replaceReturn = old.replaceReturn; const [right, { body, params }] = expression.arguments; const loop = b.forOfStatement( b.variableDeclaration("let", [ b.variableDeclarator( valueOnly ? params[0] : b.arrayPattern([params[1], params[0]]) ), ]), valueOnly ? right : b.callExpression( b.memberExpression(right, b.identifier("entries")), [] ), checkStatement(body) ? body : b.expressionStatement(body) ); loop.comments = comments; path.replace(loop); changed = true; } this.traverse(path); }, visitForStatement: visitLoop("init", "test", "update"), visitForInStatement: visitLoop("left", "right"), visitForOfStatement: visitLoop("left", "right"), visitFunction(path) { this.visit(path.get("params")); const old = { replaceReturn }; replaceReturn = false; this.visit(path.get("body")); replaceReturn = old.replaceReturn; return false; }, visitReturnStatement(path) { if (replaceReturn) { assert(!inLoop); // could use labeled continue if this ever fires const { argument, comments } = path.node; if (argument === null) { const s = b.continueStatement(); s.comments = comments; path.replace(s); } else { const s = b.expressionStatement(argument); s.comments = comments; path.replace(s, b.continueStatement()); } return false; } this.traverse(path); }, visitWhileStatement: visitLoop("test"), }); if (changed) { console.log("Writing", file); fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" }); } } Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 06:19:47 +01:00
continue;
}
if (people.is_my_user_id(user_id)) {
status = "active";
}
presence_info.set(user_id, {
status,
last_active: undefined,
});
js: Automatically convert _.each to for…of. This commit was automatically generated by the following script, followed by lint --fix and a few small manual lint-related cleanups. import * as babelParser from "recast/parsers/babel"; import * as recast from "recast"; import * as tsParser from "recast/parsers/typescript"; import { builders as b, namedTypes as n } from "ast-types"; import { Context } from "ast-types/lib/path-visitor"; import K from "ast-types/gen/kinds"; import { NodePath } from "ast-types/lib/node-path"; import assert from "assert"; import fs from "fs"; import path from "path"; import process from "process"; const checkExpression = (node: n.Node): node is K.ExpressionKind => n.Expression.check(node); const checkStatement = (node: n.Node): node is K.StatementKind => n.Statement.check(node); for (const file of process.argv.slice(2)) { console.log("Parsing", file); const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), { parser: path.extname(file) === ".ts" ? tsParser : babelParser, }); let changed = false; let inLoop = false; let replaceReturn = false; const visitLoop = (...args: string[]) => function(this: Context, path: NodePath) { for (const arg of args) { this.visit(path.get(arg)); } const old = { inLoop }; inLoop = true; this.visit(path.get("body")); inLoop = old.inLoop; return false; }; recast.visit(ast, { visitDoWhileStatement: visitLoop("test"), visitExpressionStatement(path) { const { expression, comments } = path.node; let valueOnly; if ( n.CallExpression.check(expression) && n.MemberExpression.check(expression.callee) && !expression.callee.computed && n.Identifier.check(expression.callee.object) && expression.callee.object.name === "_" && n.Identifier.check(expression.callee.property) && ["each", "forEach"].includes(expression.callee.property.name) && [2, 3].includes(expression.arguments.length) && checkExpression(expression.arguments[0]) && (n.FunctionExpression.check(expression.arguments[1]) || n.ArrowFunctionExpression.check(expression.arguments[1])) && [1, 2].includes(expression.arguments[1].params.length) && n.Identifier.check(expression.arguments[1].params[0]) && ((valueOnly = expression.arguments[1].params[1] === undefined) || n.Identifier.check(expression.arguments[1].params[1])) && (expression.arguments[2] === undefined || n.ThisExpression.check(expression.arguments[2])) ) { const old = { inLoop, replaceReturn }; inLoop = false; replaceReturn = true; this.visit( path .get("expression") .get("arguments") .get(1) .get("body") ); inLoop = old.inLoop; replaceReturn = old.replaceReturn; const [right, { body, params }] = expression.arguments; const loop = b.forOfStatement( b.variableDeclaration("let", [ b.variableDeclarator( valueOnly ? params[0] : b.arrayPattern([params[1], params[0]]) ), ]), valueOnly ? right : b.callExpression( b.memberExpression(right, b.identifier("entries")), [] ), checkStatement(body) ? body : b.expressionStatement(body) ); loop.comments = comments; path.replace(loop); changed = true; } this.traverse(path); }, visitForStatement: visitLoop("init", "test", "update"), visitForInStatement: visitLoop("left", "right"), visitForOfStatement: visitLoop("left", "right"), visitFunction(path) { this.visit(path.get("params")); const old = { replaceReturn }; replaceReturn = false; this.visit(path.get("body")); replaceReturn = old.replaceReturn; return false; }, visitReturnStatement(path) { if (replaceReturn) { assert(!inLoop); // could use labeled continue if this ever fires const { argument, comments } = path.node; if (argument === null) { const s = b.continueStatement(); s.comments = comments; path.replace(s); } else { const s = b.expressionStatement(argument); s.comments = comments; path.replace(s, b.continueStatement()); } return false; } this.traverse(path); }, visitWhileStatement: visitLoop("test"), }); if (changed) { console.log("Writing", file); fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" }); } } Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 06:19:47 +01:00
}
}
export function last_active_date(user_id: number): Date | undefined {
const info = presence_info.get(user_id);
if (!info?.last_active) {
return undefined;
}
return new Date(info.last_active * 1000);
}
export function initialize(params: {
presences: Record<number, Omit<RawPresence, "server_timestamp">>;
server_timestamp: number;
}): void {
set_info(params.presences, params.server_timestamp);
}