forked from julianlam/nodebb-plugin-tenor-gif
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.js
91 lines (71 loc) · 2.14 KB
/
library.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
'use strict';
var controllers = require('./lib/controllers');
var websockets = require('./websockets');
var meta = require.main.require('./src/meta');
var winston = require.main.require('winston');
var request = require('request');
var plugin = {
_settings: {
key: null,
},
};
plugin.init = function (params, callback) {
var router = params.router;
var hostMiddleware = params.middleware;
router.get('/admin/plugins/tenor-gif', hostMiddleware.admin.buildHeader, controllers.renderAdminPage);
router.get('/api/admin/plugins/tenor-gif', controllers.renderAdminPage);
websockets.init();
plugin.refreshSettings(callback);
};
plugin.refreshSettings = function (callback) {
meta.settings.get('tenor-gif', function (err, settings) {
Object.assign(plugin._settings, settings);
if (!settings.key || !settings.key.length) {
winston.warn('[plugin/tenor-gif] Invalid or missing API Key, plugin disabled');
}
callback(err);
});
};
plugin.addAdminNavigation = function (header, callback) {
header.plugins.push({
route: '/plugins/tenor-gif',
icon: 'fa-tint',
name: 'Tenor GIF',
});
callback(null, header);
};
plugin.registerFormatting = function (payload, callback) {
if (!plugin._settings.key) {
return setImmediate(callback, null, payload);
}
payload.options.push({ name: 'gif', className: 'fa fa-tenor-gif', title: 'Insert GIF' });
callback(null, payload);
};
plugin.query = function (query, callback) {
request({
url: 'https://api.tenor.com/v1/search?q=' + query + '&key=' + plugin._settings.key,
method: 'get',
json: true,
}, function (err, res, body) {
if (!plugin._settings.key || (body && body.hasOwnProperty('error'))) {
err = new Error('[[error:invalid-login-credentials]]');
}
// Malformed return handling
if (!body || !body.results) {
return callback(new Error('[[error:invalid-data]]'));
}
if (err) {
return callback(err);
}
// Collapse results down to array of images
var gifs = body.results.reduce(function (memo, cur) {
memo.push({
url: cur.media[0].gif.url,
thumb: cur.media[0].tinygif.url,
});
return memo;
}, []);
callback(null, gifs);
});
};
module.exports = plugin;