-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.js
97 lines (86 loc) · 2.6 KB
/
utils.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
const {promisify} = require('util')
const fetch = require('node-fetch')
const {GoogleSpreadsheet} = require('google-spreadsheet')
const sleep = module.exports.sleep = promisify(setTimeout)
module.exports.doWithRetry = async function doWithRetry(func) {
let result
let tries = 0
while (tries < 2) {
try {
return await func()
} catch (err) {
if (err.response && err.response.status === 429) {
console.log('ratelimited. waiting 10s...')
await sleep(10000)
tries++
continue
} else {
throw err
}
}
}
return await func()
}
const getStreamType = module.exports.getStreamType = function getStreamType(urlStr) {
let url
try {
url = new URL(urlStr)
} catch (err) {
console.warn('invalid url', urlStr)
return
}
let {host} = url
host = host.replace(/^www\./, '')
if (host === 'youtube.com' || host === 'youtu.be') {
return 'YouTube'
} else if (host === 'facebook.com' || host === 'm.facebook.com') {
return 'Facebook'
} else if (host === 'twitch.tv') {
return 'Twitch'
} else if (host === 'periscope.tv' || host === 'pscp.tv') {
return 'Periscope'
} else if (host === 'instagram.com') {
return 'Instagram'
}
}
module.exports.getLinkInfo = async function getLinkInfo(url) {
const streamType = getStreamType(url)
if (streamType === 'Twitch') {
const channelName = url.split('twitch.tv/')[1]
const embed = `https://player.twitch.tv/?channel=${channelName}&parent=twitch.tv`
return {streamType, channelName, embed}
} else if (streamType === 'YouTube') {
const videoID = url.startsWith('https://youtu.be') ? url.split('youtu.be/')[1] : url.split('v=')[1]
const embed = `https://www.youtube.com/embed/${videoID}?autoplay=1`
return {streamType, videoID, embed}
} else if (streamType === 'Facebook') {
const embed = `https://www.facebook.com/plugins/video.php?href=${url}`
return {streamType, embed}
}
return {streamType}
}
module.exports.getSheetTab = async function getSheetTab(creds, sheetID, tabName) {
const doc = new GoogleSpreadsheet(sheetID)
await doc.useServiceAccountAuth(creds)
await doc.loadInfo()
const sheet = Object.values(doc.sheetsById).find(s => s.title === tabName)
await sheet.loadHeaderRow()
return sheet
}
function* reverseKeys(arr) {
let key = arr.length - 1;
while (key >= 0) {
yield key;
key -= 1;
}
}
function* reverseValues(arr) {
for (let key of reverseKeys(arr)) {
yield arr[key];
}
}
module.exports.reverseEntries = function* reverseEntries(arr) {
for (let key of reverseKeys(arr)) {
yield [key, arr[key]];
}
}