-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
316 lines (294 loc) · 10.4 KB
/
index.html
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<html>
<head>
<style>
* {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div id="ytplayer" style="display: block"></div>
<div id="twitch-embed" style="display: block">
<iframe
id="twitch-iframe"
height="720"
width="1280"
frameborder="0"
scrolling="no">
</iframe>
</div>
<script type="text/javascript" src='./node_modules/obs-websocket-js/dist/obs-websocket.min.js'></script>
<script type="text/javascript" src='./config.js'></script>
<!-- obs controller -->
<script>
const obs = new OBSWebSocket();
obs.connect({ address: 'localhost:4444'});
function setScene(sceneName) {
obs.send('GetCurrentScene').then((output) => {
if(output.name !== sceneName) {
obs.send('SetCurrentScene', {'scene-name': sceneName});
}
})
}
async function stopStream() {
setScene('End');
clearTimeout();
await new Promise(resolve => setTimeout(resolve, 30000)); // sleep for 30 seconds
obs.send('StopStreaming');
}
function updateClipInfo(name, channel) {
return obs.send('SetTextGDIPlusProperties', { // need to change to SetTextFreetype2Properties for Linux
source: 'ClipInfo',
text: `${name}\nBy - ${channel}`
}).then(console.log('ClipInfo updated'));
}
function restartBrowser() {
return obs.send('SetSceneItemProperties', { // hide
item: 'Browser',
visible: false,
}).then(() => {
obs.send('SetSceneItemProperties', { //show
item: 'Browser',
visible: true,
});
});
}
function updateStatusText(text) {
return obs.send('SetTextGDIPlusProperties', { // need to change to SetTextFreetype2Properties for Linux
source: 'StatusText',
text,
}).then(console.log('StatusText updated'));
}
</script>
<!-- main functions -->
<script>
let errorCount = 0;
let currentClip;
let player; // youtube embed
async function startTwitch() {
player.stopVideo();
player.clearVideo();
document.getElementById('ytplayer').style.display = 'none';
document.getElementById('twitch-embed').style.display = 'block';
document.getElementById('twitch-iframe').setAttribute('src', `https://clips.twitch.tv/embed?clip=${currentClip.code}`);
await new Promise(resolve => setTimeout(resolve, 31000)); // sleep for 31 seconds (bit of a hack but there is no other way currently)
updateClipNext({_id: currentClip._id}).then(() => {
nextVideo();
}).catch((error) => {
updateStatusText('Could not update clip');
// probably need to exit here
});
}
function startYoutube() {
document.getElementById('twitch-embed').style.display = 'none';
document.getElementById('twitch-iframe').setAttribute('src', '');
document.getElementById('ytplayer').style.display = 'block';
player.loadVideoById(currentClip.code);
player.setPlaybackQuality('hd720');
}
function getNextVideo() {
return new Promise((resolve, reject) => {
fetch(`${apiUrl}/clips/current`, {
headers: new Headers({
'Authorization': apiKey,
}),
}).then((res) => {
return res.json();
}).then((output) => {
resolve(output);
}).catch((error) => {
reject(error);
});
});
}
function getTwitchVideoData(id) {
return new Promise((resolve, reject) => {
fetch(`https://api.twitch.tv/helix/clips?id=${id}`, {
headers: new Headers({
'client-id': twitchToken,
}),
}).then((res) => {
return res.json();
}).then((data) => {
if (!data.data[0]) {
resolve(undefined);
} else {
resolve(data.data[0]);
}
}).catch((error) => {
console.log(error);
reject(error);
});
});
}
function getYoutubeVideoData(id) {
return new Promise((resolve, reject) => {
gapi.client.youtube.videos.list({
part: 'snippet',
id,
}).then((output) => {
if (output.result.items.length === 0) {
resolve(undefined); // not found
} else {
resolve(output.result.items[0].snippet);
}
}).catch((error) => {
console.log(error);
reject(error);
});
});
}
</script>
<script src='https://apis.google.com/js/client.js'></script>
<script>
function updateClipNext() {
console.log('Next clip called');
return fetch(`${apiUrl}/clips/next`,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': apiKey
},
}
);
}
function updateClip(body) {
console.log(`Updating clip: ${currentClip.url} ${JSON.stringify(body)}`);
return fetch(`${apiUrl}/clips/${currentClip._id}`,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': apiKey
},
method: 'PUT',
body: JSON.stringify(body),
}
);
}
async function nextVideo() {
updateStatusText(' ');
// get next video id from db
getNextVideo().then((output) => {
console.log(`Retrieved next clip ${output.url}`);
errorCount = 0;
if (!output) {
updateStatusText('No clips found, exiting');
stopStream();
}
currentClip = output;
if (output.url.includes('youtube.com') || output.url.includes('youtu.be')) {
getYoutubeVideoData(output.code).then((output) => {
if (!output) { // undefined if doesn't exist
console.log('Clip does not exist, skipping');
updateClip({_id: currentClip._id, error: 1}).finally(() => {
nextVideo();
});
} else {
startYoutube();
updateClipInfo(output.title, output.channelTitle);
}
}).catch(async (error) => {
console.error(error)
// check here for gapi undefined in which case dont error
if(error.name !== 'TypeError') { // genereally shouldn't get here anyway
updateClip({_id: currentClip._id, error: 1}).finally(() => {
nextVideo();
});
} else {
await new Promise((resolve) => setTimeout(() => resolve(), 500)); // sleep for a bit
updateClipInfo('Unable to get clip info', 'ERROR');
nextVideo();
}
});
} else if (output.url.includes('twitch.tv')) {
getTwitchVideoData(output.code).then((output) => {
if(!output) { // undefined when clip doesnt exist
console.log('Clip does not exist, skipping');
updateClip({_id: currentClip._id, error: 1}).finally(() => {
nextVideo();
});
} else {
// update the ClipInfo text
startTwitch();
updateClipInfo(output.title, output.broadcaster_name);
}
}).catch((error) => {
console.error(error)
updateClipInfo('Unable to get clip info', 'ERROR');
});
} else {
// update video with error
console.error('invalid video');
updateClip({_id: currentClip._id, error: 1}).finally(() => {
nextVideo();
});
}
}).catch(async (error) => {
setScene('Error');
errorCount += 1;
// error, restart browser, update status text
if (errorCount === 10) {
updateStatusText('Failed to reconnect\nexiting stream');
await new Promise(resolve => setTimeout(resolve, 5000)); // sleep for 5 seconds
stopStream(); // exit stream
} else {
updateStatusText('Error, trying to reconnect');
await new Promise(resolve => setTimeout(resolve, 2000)); // sleep for 2 seconds
restartBrowser().finally(() => {
nextVideo();
});
}
});
};
// Load the IFrame Player API code asynchronously.
let tag = document.createElement('script');
tag.src = 'https://www.youtube.com/player_api';
let firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubePlayerAPIReady() {
gapi.client.setApiKey(youtubeApiKey);
gapi.client.load('youtube', 'v3');
player = new YT.Player('ytplayer', {
height: '720',
width: '1280',
playerVars: {
vq: 'hd720',
controls: 0,
},
events: {
// This is the main entry point. We need to ensure that the player has fully loaded before we begin
'onReady': (event) => {
nextVideo();
},
'onStateChange': (event) => {
if(event.data === YT.PlayerState.ENDED) {
// update previous video lastPlayed field
updateClipNext({_id: currentClip._id}).finally(() => {
nextVideo();
});
}
},
'onError': (event) => {
const code = event.data;
if (code === 2) {
// invalid parameter
} else if (code === 100) {
// video removed or private
} else if (code === 101 || code === 150) {
// video cannot be embeded
}
console.error('Youtube Player Error');
console.error(event);
updateClip({_id: currentClip._id, error: 1}).finally(() => {
nextVideo();
});
}
}
});
}
</script>
</body>
</html>