-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathapi.js
182 lines (161 loc) · 5.07 KB
/
api.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
/**
AUTHOR: Mario Wenzel
LICENSE: GPL3.0
**/
import Soup from 'gi://Soup'
import GLib from 'gi://GLib';
import Gio from 'gi://Gio';
const api_base = 'https://api.twitch.tv/helix/';
const client_id = "1zat8h7je94boq5t88of6j09p41hg0";
const oauth_token_path = GLib.get_user_cache_dir() + '/twitchlive-extension/oauth_token';
/* OAuth */
export function trigger_oauth(extension_path) {
const url = "https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=" + client_id + "&redirect_uri=http://localhost:8877&scope=user%3Aread%3Afollows";
const oauth_receiver = extension_path + "/oauth_receive.py";
GLib.spawn_command_line_async("xdg-open " + url);
GLib.spawn_sync(null, ["python3", oauth_receiver, oauth_token_path], null, GLib.SpawnFlags.SEARCH_PATH, null);
}
function get_token() {
var tokenfile = Gio.File.new_for_path(oauth_token_path);
if (tokenfile.query_exists(null)) {
let success, content, tag;
[success, content, tag] = tokenfile.load_contents(null);
return new TextDecoder().decode(content);
}
return undefined;
}
/* exported channel, stream */
function load_json_async(httpSession, url, fun) {
let message = Soup.Message.new('GET', url);
let oauth_token = get_token();
message.requestHeaders.append('Client-ID', client_id);
if (oauth_token) {
message.requestHeaders.append('Authorization', "Bearer " + oauth_token);
}
httpSession.send_and_read_async(
message,
GLib.PRIORITY_DEFAULT,
null,
(session, result) => {
let bytes = session.send_and_read_finish(result);
let decoder = new TextDecoder('utf-8');
let response = decoder.decode(bytes.get_data());
let data = JSON.parse(response);
fun(data);
}
);
}
// "chunk" an array into multiple chunks (for 100-per-request limit)
function chunk(arr, len) {
var chunks = [],
i = 0,
n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks;
}
// gets a list of promises, waits on them, then resolves with the data - merged
function promiseAllMerge(promises) {
return new Promise((resolve, reject) => {
Promise.all(promises).then(data => {
resolve([].concat.apply([], data));
}).catch(error => {
reject(error);
});
});
}
// https://dev.twitch.tv/docs/api/reference/#get-users
export function users(session, userLogins) {
return usersLogin(session, userLogins);
}
function usersLogin(session, userLogins) {
const chunks = chunk(userLogins, 100);
const promises = [];
chunks.forEach((chunk) => {
promises.push(_users(session, chunk, "login"));
});
return promiseAllMerge(promises);
}
export function usersID(session, userLogins) {
const chunks = chunk(userLogins, 100);
const promises = [];
chunks.forEach((chunk) => {
promises.push(_users(session, chunk, "id"));
});
return promiseAllMerge(promises);
}
function _users(session, userLogins, key) {
return new Promise((resolve, reject) => {
let url = api_base + 'users?' + key + '=' + userLogins.join('&' + key + '=');
load_json_async(session, url, (data) => {
if (!data.error) {
resolve(data.data);
} else {
reject(data);
}
});
});
}
// https://dev.twitch.tv/docs/api/reference/#get-users-follows
export function follows(session, userId) {
return new Promise((resolve, reject) => {
let url = api_base + 'channels/followed?user_id=' + encodeURI(userId) + '&first=100';
load_json_async(session, url, (data) => {
if (!data.error) {
resolve(data.data);
} else {
reject(data);
}
});
});
}
// https://dev.twitch.tv/docs/api/reference/#get-streams
export function streams(session, userLogins) {
const chunks = chunk(userLogins, 100);
const promises = [];
chunks.forEach((chunk) => {
promises.push(_streams(session, chunk));
});
return promiseAllMerge(promises);
}
function _streams(session, userLogins) {
// TODO: split > 100 into groups and resolve as a promiseAll in this function
return new Promise((resolve, reject) => {
let url = api_base + 'streams?user_login=' + userLogins.map(encodeURI).join('&user_login=');
load_json_async(session, url, (data) => {
if (!data.error) {
resolve(data.data);
} else {
reject(data);
}
});
});
}
// https://dev.twitch.tv/docs/api/reference/#get-games
export function games(session, gameIds) {
const chunks = chunk(gameIds, 100);
const promises = [];
chunks.forEach((chunk) => {
promises.push(_games(session, chunk));
});
return promiseAllMerge(promises);
}
function _games(session, gameIds) {
// TODO: split > 100 into groups and resolve as a promiseAll in this function
return new Promise((resolve, reject) => {
if (gameIds.length === 0) {
// zikeji: I'm lazy and don't want to properly handle 0 gameIds in extension.js so I'm handling it here
resolve([]);
} else {
let url = api_base + 'games?id=' + gameIds.join('&id=');
load_json_async(session, url, (data) => {
if (!data.error) {
resolve(data.data);
} else {
reject(data);
}
});
}
});
}