-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
279 lines (234 loc) · 6.11 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
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
'use strict'
const shajs = require('sha.js')
const memoize = require('memoizee')
const debug = require('debug')('butter-provider')
const defaultMemopts = {
maxAge: 10 * 60 * 1000,
/* 10 minutes */
preFetch: 0.5,
/* recache every 5 minutes */
primitive: true,
promise: 'then'
}
const defaultArgs = {
memopts: defaultMemopts
}
const defaultConfig = {
argTypes: {},
filters: {}
}
function sha256 (text) {
const hash = shajs('sha256')
hash.update(text)
return hash.digest('hex')
}
function parseArgs (uri, argTypes = {}) {
// XXX: Reimplement querystring.parse to not escape
const [name, args] = uri.split('?')
const parsed = { name }
if (args) {
args.split('&').map(v => {
const [key, value] = v.split('=')
const type = argTypes[key] || Provider.ArgType.UNKNOWN
parsed[key] = parseArgForType(type, value)
})
}
return parsed
}
function parseArgForType (type, arg) {
debug(`parsing ${arg} as ${type}`)
try {
switch (type) {
case Provider.ArgType.NUMBER:
return Number(arg)
case Provider.ArgType.ARRAY:
case Provider.ArgType.OBJECT:
return JSON.parse(arg)
case Provider.ArgType.BOOLEAN:
return !!arg
case Provider.ArgType.UNKNOWN:
debug('parsing unknown arg')
try {
return JSON.parse(arg)
} catch (e) {
debug(arg, 'is not an object')
}
return arg
case Provider.ArgType.STRING:
default:
return arg
}
} catch (err) {
console.error(`Error parsing argument: ${arg}, error: ${err}`)
}
}
function processArgs (argString, config) {
debug(`processing arg: ${JSON.stringify(argString)}`)
const { argTypes, defaults } = config
const parsed = typeof argString === 'string'
? parseArgs(argString, argTypes)
: undefined
debug(`parsed: ${JSON.stringify(parsed)}`)
const args = Object.assign({}, defaults, parsed)
argTypes && Object.keys(argTypes).map(k => {
if (!args || !args[k]) {
console.error(`Value ${k} was not provided`)
}
})
return args
}
class Provider {
constructor (args = defaultArgs, config = defaultConfig) {
config.filters = Object.assign(
{},
Provider.DefaultFilters,
config.filters
)
args = Object.assign({}, defaultArgs, args, processArgs(args, config))
const sha = sha256(JSON.stringify(args))
this.config = Object.assign({}, { name: args.name }, config)
this.id = `${config.name}_${sha}`
const { memopts } = args
this.fetch = this._makeCached(
this.fetch.bind(this),
Object.assign({
length: 1,
resolvers: [Object],
normalizer: function (args) {
return JSON.stringify(args[0])
}
}, memopts))
this.detail = this._makeCached(
this.detail.bind(this),
Object.assign({
length: 2,
resolvers: [String, Object]
}, memopts))
Object.assign(this, args)
this.args = args // backward compatibility
if (this.random) this.random = this.random.bind(this)
if (this.update) this.update = this.update.bind(this)
}
_makeCached (method, memopts) {
debug('make cached', memopts)
const memoizedMethod = memoize(method, memopts)
return (...args) => {
return memoizedMethod(...args)
.catch(err => {
// Delete the cached result if we get an error so retry will work
memoizedMethod.delete(...args)
return Promise.reject(err)
})
}
}
_warnDefault (fn, support) {
let msg = `You are using the default ${fn} implementation`
if (support) {
msg += `, you will probably want to use your own to support: ${support}.`
}
console.warn(msg)
}
resolveStream (src) {
this._warnDefault('resolveStream', 'multiple languages')
return src
}
random () {
this._warnDefault('random', 'faster random')
return this.fetch({})
.then(({ results }) => {
const random = Math.floor(Math.random() * results.length)
return results[random]
})
.then(data => this.detail(data.id, data))
}
extractIds (items = { results: [] }) {
this._warnDefault('extractIds')
return items.results.map(r => r.id)
}
detail (id, oldData) {
this._warnDefault(
`detail: ${id}`, 'better performing fetch and detail calls'
)
return Promise.resolve(oldData)
}
fetch (filters) {
this._warnDefault(
`fetch: ${JSON.stringify(filters)}`, 'fetching of the data'
)
const err = new Error('Implement your own version of the \'fetch\' method')
return Promise.reject(err)
}
toString () {
return JSON.stringify(this)
}
}
Provider.DefaultFilters = {
genres: {
all: 'All',
action: 'Action',
adventure: 'Adventure',
animation: 'Animation',
biography: 'Biography',
comedy: 'Comedy',
crime: 'Crime',
documentary: 'Documentary',
drama: 'Drama',
family: 'Family',
fantasy: 'Fantasy',
filmNoir: 'Film-Noir',
history: 'History',
horror: 'Horror',
music: 'Music',
musical: 'Musical',
mystery: 'Mystery',
romance: 'Romance',
sciFi: 'Sci-Fi',
short: 'Short',
sport: 'Sport',
thriller: 'Thriller',
war: 'War',
western: 'Western'
},
sorters: {
popularity: 'Popularity',
trending: 'Trending',
lastAdded: 'Last Added',
year: 'Year',
title: 'Title',
rating: 'Rating'
}
}
Provider.ArgType = {
ARRAY: 'BUTTER_PROVIDER_ARG_TYPE_ARRAY',
OBJECT: 'BUTTER_PROVIDER_ARG_TYPE_OBJECT',
STRING: 'BUTTER_PROVIDER_ARG_TYPE_STRING',
BOOLEAN: 'BUTTER_PROVIDER_ARG_TYPE_BOOLEAN',
NUMBER: 'BUTTER_PROVIDER_ARG_TYPE_NUMBER',
UNKNOWN: 'BUTTER_PROVIDER_ARG_TYPE_UNKNOWN'
}
Provider.ItemType = {
MOVIE: 'movie',
TVSHOW: 'tvshow',
TVSHOW2: 'tvshow2' /* newer TVSHOW API */
}
Provider.OrderType = {
ASC: 'asc',
DESC: 'desc',
NULL: null
}
Provider.SorterType = {
NAME: 'name',
RATING: 'rating',
POPULARITY: 'popularity',
NULL: null
}
Provider.QualityType = {
DEFAULT: '0',
LOW: '480p',
MEDIUM: '720p',
HIGH: '1080p',
NULL: null
}
Provider.parseArgs = parseArgs
Provider.parseArgForType = parseArgForType
module.exports = Provider