-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathviewer.html
More file actions
241 lines (186 loc) · 8.17 KB
/
viewer.html
File metadata and controls
241 lines (186 loc) · 8.17 KB
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
<html>
<body>
<script>
// hey streamer! all of the config stuff is here
const CLIENT_ID = "ID"
const CLIENT_SECRET = "Secret"
const BROADCASTER_NAME = "Broadcaster"
const TOP_OR_RANDOM = "top"
const VOLUME_PERCENT = 50
const SHOW_CLIP_CREATORS = "false"
const PREFERRED_VIDEO_QUALITY = "1080"
// TOP_OR_RANDOM can be either "top" to prioritise top clips or "random" to get random clips out of your top 1000
// note that "random" clip mode requires a tiny bit of buffer time when the page is first loaded to collect a list of clips
// below is just all the code that makes this work. once you've configured the settings above, you're good to go!
// -ShaderWave
// Utility functions
async function authenticatedFetch(url, options) {
options = options || {};
options.headers = options.headers || {}
options.headers["Client-ID"] = CLIENT_ID
options.headers["Authorization"] = `Bearer ${(await getTwitchCredentials()).access_token}`
return await fetch(url, options);
}
let OAUTH = null;
async function getTwitchCredentials() {
if (OAUTH) return OAUTH;
const response = await fetch(`https://id.twitch.tv/oauth2/token?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&grant_type=client_credentials`, {
method: "POST"
})
OAUTH = await response.json();
return OAUTH;
}
let BROADCASTER_ID = null;
async function getBroadcasterId() {
if (BROADCASTER_ID) return BROADCASTER_ID;
const response = await authenticatedFetch(`https://api.twitch.tv/helix/users?login=${BROADCASTER_NAME}`)
BROADCASTER_ID = (await response.json()).data[0].id;
return BROADCASTER_ID;
}
let CLIPS_PAGINATION = null
async function getTopClips() {
let response = await authenticatedFetch(`https://api.twitch.tv/helix/clips?first=100&broadcaster_id=${await getBroadcasterId()}${CLIPS_PAGINATION ? `&after=${CLIPS_PAGINATION}` : ""}`);
let body = await response.json();
CLIPS_PAGINATION = body.pagination.cursor;
return body;
}
async function getRandomClips() {
let clips = []
const max = 10
let pagination = null;
for (let i = 0; i < max; i++) { // top 1000 clips
let response = await authenticatedFetch(`https://api.twitch.tv/helix/clips?first=100&broadcaster_id=${await getBroadcasterId()}${pagination ? `&after=${pagination}` : ""}`);
let body = await response.json()
pagination = body.pagination.cursor;
clips = clips.concat(body.data)
const status = document.getElementById("status")
status.innerText = "Loading Clips: " + Math.floor(((i + 1) / max) * 100) + "%"
}
return clips;
}
async function getClipStreamURL(clip) {
const result = await getClipInfo(clip.id)
// console.log(`Selected target: ${JSON.stringify(result)}`)
const uri = result.sourceUrl + "?token=" + encodeURIComponent(result.token) + "&sig=" + encodeURIComponent(result.signature)
// console.log(`Video URI: ${uri}`)
return uri
}
async function getClipInfo(clipId) {
const content = JSON.stringify(buildGraphQLQuery(clipId))
const response = await fetch("https://gql.twitch.tv/gql", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Client-ID": "kimne78kx3ncx6brgo4mv6wki5h1ko"
},
body: content
})
const responseBody = await response.text()
// console.log(`GraphQL Response: ${responseBody}`)
return parseGraphQLResponse(responseBody)
}
function buildGraphQLQuery(clipId) {
return {
operationName: "VideoAccessToken_Clip",
variables: {
slug: clipId
},
extensions: {
persistedQuery: {
version: 1,
sha256Hash: "36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11"
}
}
}
}
function parseGraphQLResponse(responseBody) {
const jsonResponse = JSON.parse(responseBody);
const videoQualities = jsonResponse.data.clip.videoQualities;
const preferredQualityIndex = videoQualities.findIndex(video => video.quality == PREFERRED_VIDEO_QUALITY);
const sourceUrlIndex = preferredQualityIndex == -1 ? 0 : preferredQualityIndex;
const playbackAccessToken = jsonResponse.data.clip.playbackAccessToken;
return {
sourceUrl: videoQualities[sourceUrlIndex].sourceURL,
signature: playbackAccessToken.signature,
token: playbackAccessToken.value
}
}
let CLIPS_TO_PLAY = []
let CLIP_PLAYING = null
function setupPlayer() {
const player = document.getElementById("player")
player.load()
player.loop = false;
player.controls = false;
player.volume = VOLUME_PERCENT / 100
player.addEventListener("ended", playRandom)
}
async function playRandom() {
const player = document.getElementById("player")
const overlayText = document.getElementById("overlay")
if (CLIP_PLAYING) {
CLIPS_TO_PLAY.splice(CLIPS_TO_PLAY.indexOf(CLIP_PLAYING), 1)
}
if (CLIPS_TO_PLAY.length == 0) {
const status = document.getElementById("status")
status.className = "statusText"
CLIPS_TO_PLAY = TOP_OR_RANDOM == "top" ? (await getTopClips()).data : await getRandomClips()
status.className = "statusText hide"
}
let random = Math.floor(Math.random() * Object.keys(CLIPS_TO_PLAY).length)
const clip = CLIPS_TO_PLAY[Object.keys(CLIPS_TO_PLAY)[random]]
CLIP_PLAYING = clip
player.pause()
player.src = await getClipStreamURL(clip)
player.play()
if (SHOW_CLIP_CREATORS.toLowerCase() == "true") {
let date = new Date(clip.created_at)
let day = ('0' + date.getDate()).slice(-2);
let month = ('0' + (date.getMonth()+1)).slice(-2);
let year = date.getFullYear();
overlayText.innerText = `Clipped on ${year}-${month}-${day} by ${clip.creator_name}`
}
}
function run() {
setupPlayer()
playRandom()
}
window.addEventListener("load", run);
</script>
<div class="container">
<video id="player" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: -1;"></video>
<div id="overlay" class="overlayText"></div>
<h1 id="status" class="statusText">Loading Clips</h1>
</div>
</body>
<head>
<style>
.statusText {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
background-color: black;
padding: 4px 8px 4px 8px;
border-radius: 4px;
}
.statusText.hide {
display: none;
}
.container {
position: relative;
width: 100%;
height: 100%;
}
.overlayText {
position: absolute;
/*These calcs are used to track the bottom corner of the video as it holds its aspect ratio while the window is resized*/
top: calc((100vh - min(100vh/9, 100vw/16)*9)/2 + min(100vh/9, 100vw/16)*9 - 40px);
left: calc((100vw - min(100vh/9, 100vw/16)*16)/2 + 1.2vw);
color: white;
font-size: large;
}
</style>
</head>
</html>