70 lines
1.7 KiB
JavaScript
70 lines
1.7 KiB
JavaScript
'use strict';
|
|
|
|
const fetch = require('node-fetch');
|
|
const mime = require('mime');
|
|
|
|
function scrapeGallery(data) {
|
|
const oldestDate = Math.min(...data.gifs.map(gif => gif.createDate));
|
|
|
|
return {
|
|
album: {
|
|
id: data.id,
|
|
datetime: new Date(oldestDate * 1000),
|
|
},
|
|
items: data.gifs.map(gif => ({
|
|
id: gif.id,
|
|
url: gif.urls.hd,
|
|
description: gif.tags.join(', '),
|
|
type: mime.getType(gif.urls.hd),
|
|
datetime: new Date(gif.createDate * 1000),
|
|
original: gif,
|
|
})),
|
|
};
|
|
}
|
|
|
|
async function fetchGallery(galleryId) {
|
|
const res = await fetch(`https://api.redgifs.com/v2/gallery/${galleryId}`);
|
|
const data = await res.json();
|
|
|
|
if (!data.gifs) {
|
|
return null;
|
|
}
|
|
|
|
return scrapeGallery(data);
|
|
}
|
|
|
|
async function redgifs(host) {
|
|
const res = await fetch(`https://api.redgifs.com/v2/gifs/${host.id.toLowerCase()}`);
|
|
const data = await res.json();
|
|
|
|
if (data.errorMessage) {
|
|
throw new Error(`RedGifs API returned error for source '${host.url}' (${res.status}): ${data.errorMessage.description}`);
|
|
}
|
|
|
|
if (data.id && data.gifs) {
|
|
return scrapeGallery(data);
|
|
}
|
|
|
|
if (!data.gif) {
|
|
return null;
|
|
}
|
|
|
|
if (data.gif.gallery) {
|
|
return fetchGallery(data.gif.gallery);
|
|
}
|
|
|
|
return {
|
|
album: null,
|
|
items: [{
|
|
id: data.gif.id,
|
|
url: data.gif.urls.hd,
|
|
description: data.gif.tags.join(', '),
|
|
type: mime.getType(new URL(data.gif.urls.hd).pathname),
|
|
datetime: new Date(data.gif.createDate * 1000),
|
|
original: data.gif,
|
|
}],
|
|
};
|
|
}
|
|
|
|
module.exports = redgifs;
|