-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
88 lines (73 loc) · 3.1 KB
/
mod.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
import { InputFile } from "https://deno.land/x/[email protected]/mod.ts"
type MaybePromise<T> = Promise<T> | T;
const map = new Map<string, MaybePromise<string>>()
// deno-lint-ignore no-explicit-any
async function getFileID(response: Promise<any>, media: string): Promise<string> {
const result = await response;
const fileId = result.result[media][media === 'photo' ? 0 : ''].file_id
return fileId;
}
/**
* Caches media files before making API requests.
*
* Example Usage:
* ```ts
* bot.api.config.use(CacheMedias())
* ```
* ---
* - Api Documentation: https://github.com/OfficialCodinary/grammy-file-cacher
* @returns {Function} The transformer function
*/
// @ts-ignore - Idk how to type this
const CacheMedias = () => async (prev, method, payload, signal) => {
let response;
const mediaTypes = ['photo', 'audio', 'video', 'animation', 'document', 'video_note', 'voice'];
if (method === 'sendPhoto' || method === 'sendAudio' || method === 'sendVideo' || method === 'sendAnimation' || method === 'sendDocument' || method === 'sendVideoNote' || method === 'sendVoice') {
const media = mediaTypes.find(type => type in payload);
if (!media) return prev(method, payload, signal)
const mediaString = payload[media] instanceof InputFile ? payload[media].fileData : payload[media]
if (map.has(mediaString)) {
payload[media] = await map.get(mediaString)
response = prev(method, payload, signal)
} else {
response = prev(method, payload, signal)
map.set(mediaString, getFileID(response, media))
}
} else if (method === 'sendMediaGroup' || method === 'editMessageMedia') {
const tempMedias: string | (null)[] = []
for (const i in payload.media) {
const media = payload.media[i]
const mediaString = media.media instanceof InputFile ? media.media.fileData : media.media
if (map.has(mediaString)) {
payload.media[i].media = map.get(mediaString)
tempMedias.push(null);
} else {
tempMedias.push(mediaString)
}
}
response = prev(method, payload, signal)
const resp = response
if (!resp.length) {
const type = mediaTypes.find(type => type in resp);
if (!type) return response
if (tempMedias[0] !== null) {
const mediaString = tempMedias[0]
map.set(mediaString, getFileID(resp, type))
}
} else {
for (const i in resp) {
const media = resp[i] || resp
const type = mediaTypes.find(type => type in media);
if (!type) return response
const mediaString = tempMedias[Number(i)]
if (mediaString !== null) {
map.set(mediaString, getFileID(media, type))
}
}
}
} else {
response = prev(method, payload, signal)
}
return response
}
export { CacheMedias }