CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/database/postgres/file-use-times.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { callback2 } from "@cocalc/util/async-utils";
7
import { PostgreSQL } from "./types";
8
import { query } from "./query";
9
10
interface Options {
11
project_id: string;
12
path: string;
13
account_id: string; // who the request is about
14
user_account_id: string; // who is making the request
15
limit: number; // at most this many timestamps
16
access_times?: boolean; // if true, include access times
17
edit_times?: boolean; // if true, return edit times.
18
}
19
20
type Response = { access_times?: number[]; edit_times?: number[] };
21
22
export async function file_use_times(
23
db: PostgreSQL,
24
opts: Options
25
): Promise<Response> {
26
if (!opts.access_times && !opts.edit_times) {
27
// trivial edge case.
28
return {};
29
}
30
// Verify that that user has access. Throws exception if not allowed.
31
if (
32
!(await callback2(db.user_is_in_project_group.bind(db), {
33
account_id: opts.user_account_id,
34
project_id: opts.project_id,
35
cache: true,
36
}))
37
) {
38
throw Error("user does not have read access to the given project");
39
}
40
41
const resp: Response = {};
42
43
if (opts.access_times) {
44
// Query the file_access_log file.
45
const file_access_times: { time: Date }[] = await query({
46
db,
47
table: "file_access_log",
48
select: ["time"],
49
where: {
50
project_id: opts.project_id,
51
filename: opts.path,
52
account_id: opts.account_id,
53
},
54
one: false,
55
order_by: "time desc",
56
limit: opts.limit,
57
});
58
resp.access_times = [];
59
for (const d of file_access_times) {
60
resp.access_times.push(d.time.valueOf());
61
}
62
}
63
64
// The patches data
65
if (opts.edit_times) {
66
const string_id = db.sha1(opts.project_id, opts.path);
67
const edit_times: { time: Date }[] = await query({
68
db,
69
table: "patches",
70
select: ["time"],
71
where: { string_id },
72
one: false,
73
order_by: "time desc",
74
limit: opts.limit,
75
});
76
resp.edit_times = [];
77
for (const d of edit_times) {
78
resp.edit_times.push(d.time.valueOf());
79
}
80
}
81
82
return resp;
83
}
84
85