forked from lannonbr/LiveCodersDataAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (89 loc) · 2.93 KB
/
index.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
const fetch = require("node-fetch")
const moment = require("moment")
const AWS = require("aws-sdk")
AWS.config.update({ region: "us-east-2" })
const ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" })
require("dotenv").config()
const twitchClientID = process.env.CLIENT_ID
const twitchClientSecret = process.env.CLIENT_SECRET
const team = process.env.TEAM_NAME
const dbName = process.env.DB_NAME
const { getTwitchAccessToken } = require("@jlengstorf/get-twitch-oauth")
exports.handler = async function () {
const { access_token } = await getTwitchAccessToken({
client_id: twitchClientID,
client_secret: twitchClientSecret,
})
return new Promise(async (resolve, reject) => {
let rootResolve = resolve
let rootReject = reject
const timestamp = moment().unix().toString()
try {
let teamURL = `https://api.twitch.tv/kraken/teams/${team}`
let resp = await fetch(teamURL, {
headers: {
Accept: "application/vnd.twitchtv.v5+json",
"Client-ID": twitchClientID,
Authorization: `OAuth ${access_token}`,
},
})
let data = await resp.json()
let members = data.users
let uids = members.map((member) => member._id)
let onlineUsersEntries = []
for (let i = 0; i < Math.ceil(uids.length / 50); i++) {
let idStr = uids.slice(i * 50, i * 50 + 50).join("&user_id=")
let activeStreamsURL = `https://api.twitch.tv/helix/streams?user_id=${idStr}`
resp = await fetch(activeStreamsURL, {
headers: {
"Client-ID": twitchClientID,
Authorization: `Bearer ${access_token}`,
},
})
data = await resp.json()
let liveEntries = data.data.map((user) => {
let { user_name, game_id } = user
if (game_id === "") {
game_id = "0"
}
return {
user: user_name,
game_id,
}
})
onlineUsersEntries.push(...liveEntries)
}
console.log({ onlineUsersEntries })
// Terminate early if no one is online
if (onlineUsersEntries.length === 0) {
rootResolve(200)
}
const params = {
RequestItems: {
[dbName]: onlineUsersEntries.map((user) => ({
PutRequest: {
Item: {
username: { S: user.user },
timestamp: { N: timestamp },
game_id: { S: user.game_id },
},
},
})),
},
}
let response = await ddb.batchWriteItem(params).promise()
while (
response.UnprocessedItems.LiveCodersStreamPoints &&
response.UnprocessedItems.LiveCodersStreamPoints.length > 0
) {
params.RequestItems = response.UnprocessedItems
response = await ddb.batchWriteItem(params).promise()
}
rootResolve(200)
} catch (err) {
console.error(err)
rootReject(err)
}
})
}
exports.handler()