forked from wholespace214/crash-game-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitch-service.js
215 lines (180 loc) · 6.29 KB
/
twitch-service.js
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
const dotenv = require('dotenv');
dotenv.config();
const axios = require("axios");
let clientId = process.env.TWITCH_CLIENT_ID;
let clientSecret = process.env.TWITCH_CLIENT_SECRET;
const Event = require("../models/Event");
let credentials = {
access_token: null,
expired_in: null,
expires_at: null
};
const updateToken = async () => {
let authURL = `https://id.twitch.tv/oauth2/token?client_id=${clientId}&client_secret=${clientSecret}&grant_type=client_credentials`;
console.log("Logging in to twitch using url ", authURL);
let tokenResponse = await axios.post(authURL);
credentials.access_token = tokenResponse.data.access_token;
credentials.expired_in = tokenResponse.data.expired_in;
credentials.expires_at = Date.now() + credentials.expired_in - 200;
};
const isTokenExpired = () => {
return credentials.expires_at == null || Date.now() > credentials.expires_at;
};
const getAccessToken = async () => {
if (isTokenExpired()) {
await updateToken();
}
return credentials.access_token;
};
const twitchRequest = async (url) => {
let token = await getAccessToken();
let response = await axios.get(url, {
headers: {
"Client-Id": clientId,
"Authorization": `Bearer ${token}`
}
})
return response.data;
};
const getTwitchUser = async (twitchUsername) => {
let userData = await twitchRequest(`https://api.twitch.tv/helix/users?login=${twitchUsername}`);
return userData.data[0];
};
const getTwitchTags = async (broadcaster_id) => {
let tagsData = await twitchRequest(`https://api.twitch.tv/helix/streams/tags?broadcaster_id=${broadcaster_id}`);
return tagsData.data.map((i) => {
return {name: i.localization_names["en-us"]}
});
};
const getTwitchChannel = async (broadcaster_id) => {
let channelData = await twitchRequest(`https://api.twitch.tv/helix/channels?broadcaster_id=${broadcaster_id}`);
return channelData.data[0];
};
const getEventFromTwitchUrl = async (streamUrl) => {
let index = streamUrl.lastIndexOf("/");
let username = index == -1 ? streamUrl : streamUrl.substring(+1)
let userData = await getTwitchUser(username);
let channelData = await getTwitchChannel(userData.id);
let tags = await getTwitchTags(userData.id);
const metadata = {
'twitch_id': userData.id,
'twitch_login': userData.login,
'twitch_name': userData.display_name,
'twitch_game_id': channelData.game_id,
'twitch_game_name': channelData.game_name,
'twitch_channel_title': channelData.title
};
// first check if event exists
let event = await Event.findOne({streamUrl}).exec();
if (!event) {
event = new Event({
name: userData.display_name,
previewImageUrl: userData.offline_image_url,
streamUrl,
tags,
date: Date.now(),
type: 'streamed',
category: channelData.game_name,
metadata: {
...metadata,
'twitch_last_synced': null,
'twitch_subscribed_online': "false",
'twitch_subscribed_offline': "false"
}
});
await event.save();
} else {
event.metadata = event.metadata || {
'twitch_last_synced': null,
'twitch_subscribed_online': "false",
'twitch_subscribed_offline': "false"
};
event.metadata = {...event.metadata, ...metadata};
event.tags = tags;
event.category = channelData.game_name;
await event.save();
}
return event;
}
const subscribeForOnlineNotifications = async (broadcaster_user_id) => {
if (!process.env.BACKEND_URL || !process.env.TWITCH_CALLBACK_SECRET) {
console.log("WARNING: Attempted to subscribe to twich events without backend properly configured.");
return;
}
let token = await getAccessToken();
let data = {
"type": "stream.online",
"version": "1",
"condition": {
"broadcaster_user_id": broadcaster_user_id
},
"transport": {
"method": "webhook",
"callback": `${process.env.BACKEND_URL}/webhooks/twitch/`,
"secret": process.env.TWITCH_CALLBACK_SECRET
}
};
try {
await axios.post("https://api.twitch.tv/helix/eventsub/subscriptions", data, {
headers: {
"Client-Id": clientId,
"Authorization": `Bearer ${token}`
}
});
return "pending";
} catch (err) {
if (err.response.statusText === "Conflict") {
// already subscribed. Store info and continue;
return "true";
} else {
console.log("Could not subscribe to twitch online events", err.response);
}
}
return "false";
};
const subscribeForOfflineNotifications = async (broadcaster_user_id) => {
if (!process.env.BACKEND_URL || !process.env.TWITCH_CALLBACK_SECRET) {
console.log("WARNING: Attempted to subscribe to twich events without backend properly configured.");
return;
}
let token = await getAccessToken();
let data = {
"type": "stream.offline",
"version": "1",
"condition": {
"broadcaster_user_id": broadcaster_user_id
},
"transport": {
"method": "webhook",
"callback": `${process.env.BACKEND_URL}/webhooks/twitch/`,
"secret": process.env.TWITCH_CALLBACK_SECRET
}
};
try {
await axios.post("https://api.twitch.tv/helix/eventsub/subscriptions", data, {
headers: {
"Client-Id": clientId,
"Authorization": `Bearer ${token}`
}
});
return "pending";
} catch (err) {
if (err.response.statusText === "Conflict") {
// already subscribed. Store info and continue;
return "true";
} else {
console.log("Could not subscribe to twitch offline events", err.response);
}
}
return "false";
};
module.exports = {
getEventFromTwitchUrl,
subscribeForOnlineNotifications,
subscribeForOfflineNotifications
}
// for quick cli tests:
const main = async () => {
console.log(await getEventFromTwitchUrl("https://www.twitch.tv/gmhikaru"))
}
//main();