-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathreplays.ts
242 lines (215 loc) · 8.04 KB
/
replays.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/**
* Code for uploading and managing replays.
*
* By Zarel.
* Ported to TypeScript by Annika and Mia.
* Ported to Postgres by Zarel.
*/
import {toID, time} from './utils';
import {replayPlayers, replays} from './tables';
import {SQL} from './database';
// must be a type and not an interface to qualify as an SQLRow
// eslint-disable-next-line
export type ReplayRow = {
id: string,
format: string,
/** player names delimited by `,`; starting with `!` denotes that player wants the replay private */
players: string,
log: string,
inputlog: string | null,
uploadtime: number,
views: number,
formatid: string,
rating: number | null,
/**
* 0 = public
* 1 = private (with or without password)
* 2 = NOT USED; ONLY USED IN PREPREPLAY
* 3 = deleted
* 10 = autosaved
*/
private: 0 | 1 | 2 | 3 | 10,
password: string | null,
};
type Replay = Omit<ReplayRow, 'formatid' | 'players' | 'password' | 'views'> & {
players: string[],
views?: number,
password?: string | null,
};
export const Replays = new class {
readonly passwordCharacters = '0123456789abcdefghijklmnopqrstuvwxyz';
toReplay(this: void, row: ReplayRow) {
const replay: Replay = {
...row,
players: row.players.split(',').map(player => player.startsWith('!') ? player.slice(1) : player),
};
// TODO: probably the database driver should be handling these conversions
if (typeof replay.rating === 'string') replay.rating = +replay.rating;
if (typeof replay.uploadtime === 'string') replay.uploadtime = +replay.uploadtime;
if (typeof replay.private === 'string') replay.private = +replay.private as 0;
if (!replay.password && replay.private === 1) replay.private = 2;
return replay;
}
toReplays(this: void, rows: ReplayRow[]) {
return rows.map(row => Replays.toReplay(row));
}
toReplayRow(this: void, replay: Replay) {
const formatid = toID(replay.format);
const replayData: ReplayRow = {
password: null,
views: 0,
...replay,
players: replay.players.join(','),
formatid,
};
if (replayData.private === 1 && !replayData.password) {
replayData.password = Replays.generatePassword();
} else {
if (replayData.private === 2) replayData.private = 1;
replayData.password = null;
}
return replayData;
}
async add(replay: Replay) {
const fullid = replay.id + (replay.password ? `-${replay.password}pw` : '');
// obviously upsert exists but this is the easiest way when multiple things need to be changed
const replayData = this.toReplayRow(replay);
replayData.uploadtime ||= time();
try {
await replays.insert(replayData);
for (const playerName of replay.players) {
await replayPlayers.insert({
playerid: toID(playerName),
formatid: replayData.formatid,
id: replayData.id,
rating: replayData.rating,
uploadtime: replayData.uploadtime,
private: replayData.private,
password: replayData.password,
format: replayData.format,
players: replayData.players,
});
}
} catch (e: any) {
if (e?.routine !== 'NewUniquenessConstraintViolationError') throw e;
await replays.update(replay.id, {
log: replayData.log,
inputlog: replayData.inputlog,
rating: replayData.rating,
private: replayData.private,
password: replayData.password,
});
await replayPlayers.updateAll({
rating: replayData.rating,
private: replayData.private,
password: replayData.password,
})`WHERE id = ${replay.id}`;
}
return fullid;
}
async get(id: string): Promise<Replay | null> {
const replayData = await replays.get(id);
if (!replayData) return null;
await replays.update(replayData.id, {views: SQL`views + 1`});
return this.toReplay(replayData);
}
async edit(replay: Replay) {
const replayData = this.toReplayRow(replay);
await replays.update(replay.id, {private: replayData.private, password: replayData.password});
}
generatePassword(length = 31) {
let password = '';
for (let i = 0; i < length; i++) {
password += this.passwordCharacters[Math.floor(Math.random() * this.passwordCharacters.length)];
}
return password;
}
search(args: {
page?: number, isPrivate?: boolean, byRating?: boolean,
format?: string, usernames?: string[], before?: number,
}): Promise<Replay[]> {
if ((args.page || 0) > 100) return Promise.resolve([]);
const limit1 = 50 * ((args.page || 1) - 1);
const paginate = SQL`LIMIT 51 OFFSET ${limit1}`;
const before = args.before ? SQL`AND uploadtime < ${args.before}` : SQL``;
const isPrivate = args.isPrivate ? 1 : 0;
const format = args.format ? toID(args.format) : null;
if (args.usernames?.length) {
const order = args.byRating ? SQL`ORDER BY rating DESC` : SQL`ORDER BY uploadtime DESC`;
const userid = toID(args.usernames[0]);
if (args.usernames.length > 1) {
const userid2 = toID(args.usernames[1]);
if (format) {
return replays.query()`SELECT
p1.uploadtime AS uploadtime, p1.id AS id, p1.format AS format, p1.players AS players,
p1.rating AS rating, p1.password AS password, p1.private AS private
FROM replayplayers p1 INNER JOIN replayplayers p2 ON p2.id = p1.id
WHERE p1.playerid = ${userid} AND p1.formatid = ${format} AND p1.private = ${isPrivate}
AND p2.playerid = ${userid2}
${before} ${order} ${paginate};`.then(this.toReplays);
} else {
return replays.query()`SELECT
p1.uploadtime AS uploadtime, p1.id AS id, p1.format AS format, p1.players AS players,
p1.rating AS rating, p1.password AS password, p1.private AS private
FROM replayplayers p1 INNER JOIN replayplayers p2 ON p2.id = p1.id
WHERE p1.playerid = ${userid} AND p1.private = ${isPrivate}
AND p2.playerid = ${userid2}
${before} ${order} ${paginate};`.then(this.toReplays);
}
} else {
if (format) {
return replays.query()`SELECT
uploadtime, id, format, players, rating, private, password FROM replayplayers
WHERE playerid = ${userid} AND formatid = ${format} AND "private" = ${isPrivate}
${before} ${order} ${paginate};`.then(this.toReplays);
} else {
return replays.query()`SELECT
uploadtime, id, format, players, rating, private, password FROM replayplayers
WHERE playerid = ${userid} AND private = ${isPrivate}
${before} ${order} ${paginate};`.then(this.toReplays);
}
}
}
if (!format) return this.recent(args);
if (args.byRating) {
return replays.query()`SELECT uploadtime, id, format, players, rating, private, password
FROM replays
WHERE private = ${isPrivate} AND formatid = ${format} ${before} ORDER BY rating DESC ${paginate}`
.then(this.toReplays);
} else {
return replays.query()`SELECT uploadtime, id, format, players, rating, private, password
FROM replays
WHERE private = ${isPrivate} AND formatid = ${format} ${before} ORDER BY uploadtime DESC ${paginate}`
.then(this.toReplays);
}
}
fullSearch(term: string, page = 0): Promise<Replay[]> {
if (page > 0) return Promise.resolve([]);
const patterns = term.split(',').map(subterm => {
const escaped = subterm.replace(/%/g, '\\%').replace(/_/g, '\\_');
return `%${escaped}%`;
});
if (patterns.length !== 1 && patterns.length !== 2) return Promise.resolve([]);
const secondPattern = patterns.length >= 2 ? SQL`AND log LIKE ${patterns[1]} ` : undefined;
const DAYS = 24 * 60 * 60;
return replays.query()`SELECT
uploadtime, id, format, players, rating FROM ps_replays
WHERE private = 0 AND uploadtime > ${time() - 3 * DAYS} AND log LIKE ${patterns[0]} ${secondPattern}
ORDER BY uploadtime DESC LIMIT 50;`.then(this.toReplays);
}
recent(args?: {before?: number}) {
if (args?.before) {
return replays.selectAll(
SQL`uploadtime, id, format, players, rating`
)`WHERE private = 0 AND uploadtime <= ${args.before} ORDER BY uploadtime DESC LIMIT 51`
.then(this.toReplays);
}
return replays.selectAll(
SQL`uploadtime, id, format, players, rating`
)`WHERE private = 0 ORDER BY uploadtime DESC LIMIT 51`.then(this.toReplays);
}
getBatch(ids: string[]) {
return replays.selectAll()`WHERE private = 0 AND id IN (${ids}) LIMIT 51`.then(this.toReplays);
}
};
export default Replays;