-
Notifications
You must be signed in to change notification settings - Fork 0
/
Code.ts
584 lines (552 loc) · 17.4 KB
/
Code.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
interface Config {
LINE_CHANNEL_ACCESS_TOKEN?: string | null;
SAVE_IMAGE: boolean;
SAVE_VIDEO: boolean;
SAVE_AUDIO: boolean;
SAVE_FILE: boolean;
SAVE_MESSAGE: boolean;
ALLOW_GET_LINK: boolean;
ALLOW_OVERWRITE: boolean;
COMMAND_GET_LINK: string;
COMMAND_GET_GROUP_ID: string;
COMMAND_GET_USER_ID: string;
COMMAND_PREFIX_SET_COMMANDS: string;
COMMAND_GET_CONFIG: string;
IMAGE_NAME_FORMAT: string;
VIDEO_NAME_FORMAT: string;
AUDIO_NAME_FORMAT: string;
FILE_NAME_FORMAT: string;
IS_LOG_REQUEST?: boolean;
TEST_PAYLOAD?: string;
}
export interface JsonRequest {
destination: string;
events: ChatEvent[];
}
export interface ChatEvent {
type: string;
message: Message;
webhookEventId: string;
deliveryContext: DeliveryContext;
timestamp: number;
source: Source;
replyToken: string;
mode: string;
}
export interface DeliveryContext {
isRedelivery: boolean;
}
export interface Message {
type: string;
id: string;
text?: string;
fileName?: string;
fileSize?: number;
contentProvider?: ContentProvider;
duration?: number;
}
export interface ContentProvider {
type: string;
}
export interface Source {
type: string;
groupId: string;
userId: string;
}
export interface LineUser {
userId: string;
displayName: string;
pictureUrl: string;
language: string;
}
const LINE_CHANNEL_ACCESS_TOKEN = getConfigValue("LINE_CHANNEL_ACCESS_TOKEN");
let jsonRequest: JsonRequest;
let lineUser: LineUser;
function publishConfig() {
const sheet = createSheetIfNotExists("Global Config");
createSheetIfNotExists("Group Config");
const keyColumn = 1;
const defaultConfigValue = defaultConfig();
const lastRow = sheet.getLastRow();
for (const key in defaultConfigValue) {
let isKeyExists = false;
for (let i = 1; i <= lastRow; i++) {
if (sheet.getRange(i, keyColumn).getValue() == key) {
isKeyExists = true;
break;
}
}
if (!isKeyExists) {
sheet.appendRow([key, defaultConfigValue[key]]);
}
}
}
function doPost(e) {
jsonRequest = JSON.parse(e.postData.contents);
if (getConfigValue("IS_LOG_REQUEST")) {
log("Event", e.postData.contents);
}
run();
}
function test() {
jsonRequest = JSON.parse(getConfigValue("TEST_PAYLOAD"));
run();
}
function getEvent() {
return jsonRequest.events[0];
}
function run() {
const event = getEvent();
const messageType = getMessageType();
const selectedId = getSelectedId();
const saveTypes = {
image: getConfigValue("SAVE_IMAGE", selectedId),
audio: getConfigValue("SAVE_AUDIO", selectedId),
video: getConfigValue("SAVE_VIDEO", selectedId),
file: getConfigValue("SAVE_FILE", selectedId),
};
const trueTypes = Object.entries(saveTypes)
.filter(([_, value]) => value === true)
.map(([key, _]) => key);
const messageText = getMessageText();
if (trueTypes.includes(messageType)) {
saveFile();
} else if (messageType === "text" && messageText) {
const userId = getUserId();
if (
getConfigValue("ALLOW_GET_LINK", userId) &&
messageText === getConfigValue("COMMAND_GET_LINK", selectedId)
) {
getLink();
} else if (
messageText === getConfigValue("COMMAND_GET_GROUP_ID", selectedId)
) {
log("Get Group id", `${userId} Get Group id ${getGroupId()}`);
sendMsg(event.replyToken, selectedId);
} else if (
messageText === getConfigValue("COMMAND_GET_USER_ID", selectedId)
) {
log("Get User id", `${userId} Get User id ${getUserId()}`);
sendMsg(event.replyToken, userId);
} else if (
messageText === getConfigValue("COMMAND_GET_CONFIG", selectedId)
) {
log("Get help", `${getUserId()} Get help in ${selectedId}`);
sendMsg(event.replyToken, configList(selectedId));
} else if (
messageText.startsWith(
getConfigValue("COMMAND_PREFIX_SET_COMMANDS", selectedId)
) &&
getConfigValue("ALLOW_OVERWRITE", selectedId)
) {
const key = messageText
.replace(
getConfigValue("COMMAND_PREFIX_SET_COMMANDS", selectedId),
""
)
.split("=")[0]
.trim();
const value = messageText.split("=")[1].trim();
if (
key &&
value &&
key in defaultConfig() &&
typeof defaultConfig()[key] === typeof convertValue(value)
) {
setGroupConfig(key, selectedId, convertValue(value));
sendMsg(event.replyToken, `Set ${key} to ${value}`);
log(
`Set ${key} to ${value}`,
`${userId} Set ${key} to ${value} in ${selectedId}`
);
}
}
if (getConfigValue("SAVE_MESSAGE", selectedId)) {
writeMessageLog();
}
}
}
function getMessageText() {
return getEvent()?.message?.text;
}
function getSelectedId() {
return getGroupId() ?? getUserId();
}
function writeMessageLog() {
const spreadsheet = createSpreadsheetFromFolderId(
getSelectedFolder().getId(),
"log"
);
const logSheet = createSheetIfNotExistsFromSpreadsheetId(
spreadsheet.getId(),
"log"
);
const userSheet = createSheetIfNotExistsFromSpreadsheetId(
spreadsheet.getId(),
"users"
);
const linkSheet = createSheetIfNotExistsFromSpreadsheetId(
spreadsheet.getId(),
"links"
);
if (!userSheet.getRange(1, 1).getValue()) {
userSheet.appendRow([
"userId",
"displayName",
"pictureUrl",
"language",
]);
}
// get displayName from userId
const userId = getUserId();
let displayName = "";
for (let i = 1; i <= userSheet.getLastRow(); i++) {
if (userSheet.getRange(i, 1).getValue() === userId) {
displayName = userSheet.getRange(i, 2).getValue();
break;
}
}
if (!displayName) {
const lineUser = getLineUser();
displayName = lineUser.displayName;
userSheet.appendRow([
lineUser.userId,
lineUser.displayName,
lineUser.pictureUrl,
lineUser.language,
]);
}
if (!logSheet.getRange(1, 1).getValue()) {
logSheet.appendRow([
"datetime",
"user",
"event",
"messageId",
"message",
]);
}
logSheet.appendRow([
new Date(),
displayName,
getMessageType(),
getEvent().message.id,
getMessageText(),
]);
if (!linkSheet.getRange(1, 1).getValue()) {
linkSheet.appendRow(["datetime", "user", "messageId", "link"]);
}
const extractedLinks = extractLinksFromString(getMessageText());
for (const link of extractedLinks) {
linkSheet.appendRow([
new Date(),
displayName,
getEvent().message.id,
link,
]);
}
}
function configList(selectedId) {
const keys = Object.keys(defaultConfig()).filter(
(key) => key !== "LINE_CHANNEL_ACCESS_TOKEN"
);
return keys
.map((key) => `${key} = ${getConfigValue(key, selectedId)}`)
.join("\n");
}
function getMessageType() {
return getEvent().message.type;
}
function getGroupId() {
return getEvent().source.groupId;
}
function getUserId() {
return getEvent().source.userId;
}
function getSelectedFolder() {
return createFolderIfNotExists(getSelectedId(), getCurrentFolder().getId());
}
function saveFile() {
const event = getEvent();
const groupId = getGroupId();
const userId = getUserId();
const groupFolder = getSelectedFolder();
const messageType = getMessageType();
const typeFolder = createFolderIfNotExists(
messageType,
groupFolder.getId()
);
const messageId = event.message.id;
const fileName = event.message.fileName;
const timestamp = event.timestamp;
const file = fetchFile(messageId);
const extension = file.getBlob().getContentType().split("/")[1];
// replace file name pattern
function replaceFileName(fileNamePattern) {
const replaceValue = {
"${userId}": userId,
"${groupId}": groupId,
"${messageId}": messageId,
"${fileName}": fileName,
"${timestamp}": timestamp,
"${extension}": extension,
};
let newFileName = fileNamePattern;
for (const [key, value] of Object.entries(replaceValue)) {
newFileName = newFileName.replace(key, value);
}
return newFileName;
}
// get new file names based on message type and config values
const fileNameFormats = {
file: replaceFileName(getConfigValue("FILE_NAME_FORMAT", groupId)),
image: replaceFileName(getConfigValue("IMAGE_NAME_FORMAT", groupId)),
video: replaceFileName(getConfigValue("VIDEO_NAME_FORMAT", groupId)),
audio: replaceFileName(getConfigValue("AUDIO_NAME_FORMAT", groupId)),
};
const newFileNames = Object.fromEntries(
Object.entries(fileNameFormats).map(([type, format]) => [
type,
replaceFileName(format) ?? fileName,
])
);
// save file with new file name
const newFileName = newFileNames[messageType] ?? fileName;
log(
`Save ${messageType}`,
`${userId} save ${messageType} to ${
groupId ?? userId
}/${typeFolder}/${newFileName}`
);
// save file
typeFolder.createFile(file.getBlob()).setName(newFileName);
}
function getLink() {
const userId = getUserId();
const groupId = getGroupId();
const selectedId = groupId ?? userId;
const replyToken = getEvent().replyToken;
const isGroupFolderExists = getCurrentFolder()
.getFoldersByName(selectedId)
.hasNext();
if (isGroupFolderExists) {
const groupFolder = getCurrentFolder()
.getFoldersByName(groupId ?? userId)
.next();
setFolderAccessToAnyone(groupFolder.getId());
log("Get link", `${userId} Get link ${selectedId}`);
sendMsg(replyToken, groupFolder.getUrl());
} else {
log("Get link failed", `${userId} Get link failed ${selectedId}`);
sendMsg(replyToken, "No file found");
}
}
function checkFolderExists(folderName: string, parentFolderId: string) {
const parentFolder = DriveApp.getFolderById(parentFolderId);
const folders = parentFolder.getFoldersByName(folderName);
return folders.hasNext();
}
function fetchFile(messageId) {
const url = `https://api-data.line.me/v2/bot/message/${messageId}/content`;
const opt = {
headers: {
Authorization: `Bearer ${LINE_CHANNEL_ACCESS_TOKEN}`,
},
};
const response = UrlFetchApp.fetch(url, opt);
return response;
}
function log(event, message) {
createSheetIfNotExists("Log").appendRow([new Date(), event, message]);
}
function createFolderIfNotExists(folderName: string, parentFolderId: string) {
const parentFolder = DriveApp.getFolderById(parentFolderId);
const folders = parentFolder.getFoldersByName(folderName);
if (folders.hasNext()) {
// Folder already exists, return the existing folder
return folders.next();
} else {
// Folder does not exist, create a new folder
const newFolder = parentFolder.createFolder(folderName);
return newFolder;
}
}
function createSpreadsheetFromFolderId(
folderId: string,
spreadsheetName: string
) {
const folder = DriveApp.getFolderById(folderId);
// Check if a spreadsheet with the desired name already exists in the folder
const existingSpreadsheet = folder.getFilesByName(spreadsheetName);
if (existingSpreadsheet.hasNext()) {
// Spreadsheet already exists
const spreadsheet = SpreadsheetApp.open(existingSpreadsheet.next());
return spreadsheet;
} else {
// Create a new spreadsheet
const spreadsheet = SpreadsheetApp.create(spreadsheetName);
// Move the newly created spreadsheet to the desired folder
DriveApp.getFileById(spreadsheet.getId()).moveTo(folder);
return spreadsheet;
}
}
function createSheetIfNotExistsFromSpreadsheetId(
spreadsheetId: string,
sheetName: string
) {
const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
// Check if the sheet already exists in the spreadsheet
let sheet = spreadsheet.getSheetByName(sheetName);
if (sheet) {
// Sheet already exists
return sheet;
} else {
// Create a new sheet
sheet = spreadsheet.insertSheet(sheetName);
return sheet;
}
}
function sendMsg(replyToken: string, msg: string) {
const url = "https://api.line.me/v2/bot/message/reply";
const opt: GoogleAppsScript.URL_Fetch.URLFetchRequestOptions = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${LINE_CHANNEL_ACCESS_TOKEN}`,
},
method: "post",
payload: JSON.stringify({
replyToken: replyToken,
messages: [{ type: "text", text: msg }],
}),
};
UrlFetchApp.fetch(url, opt);
}
function getCurrentFolder() {
const sheet = SpreadsheetApp.getActiveSpreadsheet();
const currentFile = DriveApp.getFileById(sheet.getId());
const currentFolder = currentFile.getParents().next();
return currentFolder;
}
function setFolderAccessToAnyone(folderId) {
const folder = DriveApp.getFolderById(folderId);
folder.setSharing(
DriveApp.Access.ANYONE_WITH_LINK,
DriveApp.Permission.VIEW
);
return folder;
}
function createSheetIfNotExists(sheetName) {
const spreadsheet = SpreadsheetApp.getActive();
let sheet = spreadsheet.getSheetByName(sheetName);
if (!sheet) {
sheet = spreadsheet.insertSheet();
sheet.setName(sheetName);
}
return sheet;
}
function defaultConfig(): Config {
return {
LINE_CHANNEL_ACCESS_TOKEN: null,
SAVE_IMAGE: true,
SAVE_VIDEO: true,
SAVE_AUDIO: true,
SAVE_FILE: true,
SAVE_MESSAGE: true,
ALLOW_GET_LINK: true,
ALLOW_OVERWRITE: true,
COMMAND_GET_LINK: "!link",
COMMAND_GET_GROUP_ID: "!group",
COMMAND_GET_USER_ID: "!user",
COMMAND_PREFIX_SET_COMMANDS: "!set",
IMAGE_NAME_FORMAT: "${timestamp}.${extension}",
VIDEO_NAME_FORMAT: "${timestamp}.${extension}",
AUDIO_NAME_FORMAT: "${timestamp}.${extension}",
FILE_NAME_FORMAT: "${timestamp}_${fileName}",
COMMAND_GET_CONFIG: "!config",
};
}
function getConfigValue(key: string, selectedId: string | null = null) {
const defaultConfigValue = defaultConfig();
const sheet = createSheetIfNotExists("Global Config");
const keyColumn = 1;
const valueColumn = 2;
const lastRow = sheet.getLastRow();
const groupSheet = createSheetIfNotExists("Group Config");
for (let i = 1; i <= lastRow; i++) {
if (
groupSheet.getRange(i, keyColumn).getValue() == key &&
groupSheet.getRange(i, 2).getValue() == selectedId
) {
return convertValue(groupSheet.getRange(i, 3).getValue());
}
}
const scriptProperty =
PropertiesService.getScriptProperties().getProperty(key);
if (scriptProperty) {
return convertValue(scriptProperty);
}
for (let i = 1; i <= lastRow; i++) {
if (sheet.getRange(i, keyColumn).getValue() == key) {
return convertValue(sheet.getRange(i, valueColumn).getValue());
}
}
return defaultConfigValue[key];
}
function setGroupConfig(key, selectedId, value) {
const groupSheet = createSheetIfNotExists("Group Config");
for (let i = 1; i <= groupSheet.getLastRow(); i++) {
if (
groupSheet.getRange(i, 2).getValue() == selectedId &&
groupSheet.getRange(i, 1).getValue() == key
) {
groupSheet.getRange(i, 3).setValue(value);
return;
}
}
groupSheet.appendRow([key, selectedId, value]);
}
function convertValue(value) {
if (typeof value === "string") {
value = value.trim();
const lowerValue = value.toLowerCase();
const converter = {
true: true,
false: false,
yes: true,
no: false,
null: null,
};
if (lowerValue in converter) {
return converter[lowerValue];
}
}
if (typeof value === "boolean") {
return value;
}
if (!isNaN(value)) {
return Number(value);
}
return value.trim();
}
function getLineUser() {
const userId = getUserId();
if (lineUser) {
return lineUser;
}
const url = `https://api.line.me/v2/bot/profile/${userId}`;
const opt = {
headers: {
Authorization: `Bearer ${LINE_CHANNEL_ACCESS_TOKEN}`,
},
};
const response = UrlFetchApp.fetch(url, opt);
lineUser = JSON.parse(response.getContentText());
return lineUser;
}
function extractLinksFromString(text) {
const regex = /(https?:\/\/[^\s]+)/g;
const matches = text.match(regex);
if (matches) {
return matches;
}
return [];
}