-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.ts
127 lines (111 loc) · 2.8 KB
/
handler.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
import axios from 'axios'
const deviceID = process.env.DEVICE_ID
const apiToken = process.env.API_TOKEN
const userAgent = 'Eli Gundry <https://github.com/eligundry/tidbyt>'
if (!deviceID) {
throw new Error(`DEVICE_ID env var must be set`)
}
if (!apiToken) {
throw new Error(`API_TOKEN env var must be set`)
}
const widgets = {
Feelings:
'https://raw.githubusercontent.com/eligundry/tidbyt/main/feelings.star',
Dril: 'https://raw.githubusercontent.com/eligundry/tidbyt/main/dril.star',
}
const log = (
level: 'log' | 'info' | 'warning' | 'error',
msg: string,
data: any
) =>
console[level](
JSON.stringify({
level,
ts: new Date().toISOString(),
msg,
data,
})
)
const generateWidget = async (widgetURL: string): Promise<string> =>
axios
.get<string>('https://axilla.netlify.app/', {
responseType: 'text',
params: {
applet: widgetURL,
output: 'base64',
},
headers: {
'user-agent': userAgent,
},
timeout: 60 * 1000,
})
.then((resp) => resp.data)
const uploadWidget = async (name: string, image: string) =>
axios.post(
`https://api.tidbyt.com/v0/devices/${deviceID}/push`,
{
deviceID,
installationID: name,
background: true,
image,
},
{
headers: {
authorization: `Bearer ${apiToken}`,
'content-type': 'application/json',
'user-agent': userAgent,
},
timeout: 60 * 1000,
}
)
export const tidbyt = async () => {
const successful: string[] = []
const failed: Record<string, unknown> = {}
await Promise.all(
Object.entries(widgets).map(async ([name, widgetURL]) => {
log('info', 'generating image', { name })
try {
var image = await generateWidget(widgetURL)
log('info', 'successfully generated image', { name })
} catch (e) {
if (e.response) {
failed[name] = e.response.data
} else {
failed[name] = e.message
}
log('error', 'failed to generate image', {
name,
error: failed[name],
})
return
}
log('info', 'uploading image to tidbyt', { name })
try {
const resp = await uploadWidget(name, image)
log('info', 'successfully uploaded image to tidbyt', {
name,
response: resp.data,
})
successful.push(name)
} catch (e) {
if (e.response) {
failed[name] = e.response.data
} else {
failed[name] = e.message
}
log('error', 'failed to upload image to tidbyt', {
name,
error: failed[name],
})
}
})
)
return {
statusCode: Object.keys(failed).length > 0 ? 500 : 200,
body: JSON.stringify({
successful,
failed,
}),
}
}
tidbyt()