/
tenor.js
61 lines (55 loc) · 1.47 KB
/
tenor.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
/* @flow */
import { Host } from '../../core/host';
import { ajax } from '../../environment';
export default new Host('tenor', {
name: 'tenor',
domains: ['tenor.co'],
logo: 'https://www.tenor.co/favicon.ico',
detect: (() => {
const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const alphabetMap = alphabet
.split('')
.reduce((obj, c, i) => {
obj[c] = i;
return obj;
}, {});
function parseViewShortId(s) {
return s
.split('')
.reduce((n, c) => (n * alphabet.length) + alphabetMap[c], 0);
}
return ({ hostname, pathname }) => {
if (hostname === 'tenor.co') {
// short URL
const pathMatch = (/^\/([a-zA-Z0-9]+)\.gif$/i).exec(pathname);
return pathMatch && { id: parseViewShortId(pathMatch[1]) };
} else if (hostname === 'media.tenor.co') {
return { id: null };
} else {
const pathMatch = (/^\/view\/.+\-(\d+)(\.gif)?$/i).exec(pathname);
return pathMatch && { id: pathMatch[1] };
}
};
})(),
async handleLink(href, { id }) {
if (id === null) {
// Some files on our CDN are named "raw", with no file extension,
// so they won't load without this.
return {
type: 'IMAGE',
src: href,
};
}
const { results: [gif] } = await ajax({
url: 'https://api.tenor.co/v1/gifs',
query: { key: 'JJHDC7UK73EH', ids: id },
type: 'json',
});
return {
type: 'IMAGE',
src: gif.media[0].gif.url,
title: gif.h1_title,
caption: gif.generatedcaption,
};
},
});