diff options
| author | schneefux <schneefux+commit@schneefux.xyz> | 2017-05-05 17:06:58 +0200 |
|---|---|---|
| committer | schneefux <schneefux+commit@schneefux.xyz> | 2017-05-05 17:06:58 +0200 |
| commit | 0e5a0b876aa36786430d313f8ded843aa849eb00 (patch) | |
| tree | 3aefd018044938772b43c8ff0c491ad668ee5e8d | |
| parent | 5045641b065bfea9a0db39dd4814b2cf2269e723 (diff) | |
| download | discordbot-0e5a0b876aa36786430d313f8ded843aa849eb00.tar.gz discordbot-0e5a0b876aa36786430d313f8ded843aa849eb00.zip | |
refactor
| -rw-r--r-- | api.js | 97 | ||||
| -rw-r--r-- | commands/vainsocial/guild_add.js | 16 | ||||
| -rw-r--r-- | commands/vainsocial/guild_create.js | 18 | ||||
| -rw-r--r-- | commands/vainsocial/guild_view.js | 12 | ||||
| -rw-r--r-- | commands/vainsocial/me.js | 13 | ||||
| -rw-r--r-- | responses.js | 85 |
6 files changed, 98 insertions, 143 deletions
@@ -39,14 +39,33 @@ function getMap(url) { }); } -function getFE(url) { - return request({ - uri: API_FE_URL + url, +async function getFE(url, params={}, ttl=60, cachekey=undefined) { + if (cachekey == undefined) cachekey = url + JSON.stringify(params); + return await cache.wrap(cachekey, async () => { + try { + return await request({ + uri: API_FE_URL + url, + qs: params, + json: true, + forever: true + }); + } catch (err) { + return undefined; + } + }, { ttl: ttl }); +} + +async function postFE(url, params={}) { + return await request.post(API_FE_URL + url, { + form: params, json: true, forever: true }); } +module.exports.get = getFE; +module.exports.post = postFE; + function postBE(url) { return request.post({ uri: API_BE_URL + url, @@ -87,35 +106,36 @@ async function getMappings() { }, { ttl: 60 * 30 }); } -module.exports.mapGameMode = async function(id) { - return (await getMappings())["gamemode"][id]; -} +module.exports.mapGameMode = async (id) => + (await getMappings())["gamemode"][id]; -module.exports.mapActor = async function(api_name) { - return (await getMappings())["hero"][api_name]; -} +module.exports.mapActor = async (api_name) => + (await getMappings())["hero"][api_name]; // return a set of IGN of supporters -module.exports.getGamers = async function() { - return await cache.wrap("gamers", async () => { - return (await getFE("/gamer")).map((gamer) => gamer.name); - }, { ttl: 60 * 30 }); -} +module.exports.getGamers = async () => + (await getFE("/gamer", {}, 60 * 30)).map((gamer) => gamer.name); // be an async iterator // next() returns promises that are awaited until there is an update -module.exports.subscribeUpdates = function(name, timeout=UPDATE_TIMEOUT) { +module.exports.subscribeUpdates = async (name, refresh=true, timeout=UPDATE_TIMEOUT) => { const channel = new Channel(), subscription = subscribe("player." + name, channel); + if (refresh) { + // trigger backend + if (await module.exports.getPlayer(name) == undefined) + await module.exports.searchPlayer(name); + else await module.exports.updatePlayer(name); + } + // stop updates after timeout setTimeout(() => channel.close(), timeout*1000); let msg; return { next: async function () { - do { - msg = await channel.take(); - } while([Channel.DONE, "search_fail", "search_success", + do msg = await channel.take(); + while([Channel.DONE, "search_fail", "search_success", "stats_update", "matches_update"].indexOf(msg) == -1); // bust caches if (["stats_update"].indexOf(msg) != -1) @@ -133,40 +153,25 @@ module.exports.subscribeUpdates = function(name, timeout=UPDATE_TIMEOUT) { } // search an unknown player -module.exports.searchPlayer = async function(name) { - return await postBE("/player/" + name + "/search"); -} +module.exports.searchPlayer = (name) => + postBE("/player/" + name + "/search"); // update a known player -module.exports.updatePlayer = async function(name) { - return await postBE("/player/" + name + "/update"); -} +module.exports.updatePlayer = (name) => + postBE("/player/" + name + "/update"); // return player -module.exports.getPlayer = async function(name) { - return await cache.wrap("player+" + name, async () => { - try { - return await getFE("/player/" + name); - } catch (err) { - return undefined; - } - }, { ttl: 60 }); -} +module.exports.getPlayer = (name) => + getFE("/player/" + name, {}, 60, "player+" + name); // return matches -module.exports.getMatches = async function(name) { - return await cache.wrap("matches+" + name, async () => { - try { - return await getFE("/player/" + name + "/matches/1.1.1.1"); - } catch (err) { - return undefined; - } - }, { ttl: 60 }); +module.exports.getMatches = async (name) => { + const data = await getFE("/player/" + name + "/matches/2.3.1.1", {}, + 60 * 60, "matches+" + name); + if (data == undefined) return []; + return data[0].data; } // return single match -module.exports.getMatch = async function(id) { - return await cache.wrap("match+" + id, async () => - getFE("/match/" + id), - { ttl: 60 * 60 }); -} +module.exports.getMatch = (id) => + getFE("/match/" + id, {}, 60 * 60); diff --git a/commands/vainsocial/guild_add.js b/commands/vainsocial/guild_add.js index 7f6aac7..8dc2ab8 100644 --- a/commands/vainsocial/guild_add.js +++ b/commands/vainsocial/guild_add.js @@ -5,12 +5,9 @@ const Commando = require("discord.js-commando"), oneLine = require("common-tags").oneLine, Promise = require("bluebird"), - request = require("request-promise"), api = require("../../api"), util = require("../../util"); -const API_FE_URL = process.env.API_FE_URL || "http://vainsocial.dev/bot/api"; - module.exports = class AddGuildMemberCommand extends Commando.Command { constructor(client) { super(client, { @@ -44,9 +41,11 @@ Register IGNs to your Guild. let player = await api.getPlayer(user); if (player == undefined) { await progress(`Loading ${user}'s data into VainSocial…`); - // if not, wait for backend to fetch + // if not, wait for backend to fetch name <-> api_id + // - not interested in match history (hence no update), const waiter = api.subscribeUpdates(user); await api.searchPlayer(user); + let success = false, notif; // wait until search success while (true) { @@ -63,12 +62,9 @@ Register IGNs to your Guild. } // all good, register to self guild - await request.post(API_FE_URL + "/guild/members", { - forever: true, - form: { - user_token: msg.author.id, - member_name: user - } + await api.post("/guild/members", { + user_token: msg.author.id, + member_name: user }); await progress(`Added ${user}.`, true); }); diff --git a/commands/vainsocial/guild_create.js b/commands/vainsocial/guild_create.js index 9114703..1e5a368 100644 --- a/commands/vainsocial/guild_create.js +++ b/commands/vainsocial/guild_create.js @@ -4,11 +4,9 @@ const Commando = require("discord.js-commando"), oneLine = require("common-tags").oneLine, - request = require("request-promise"), + api = require("../../api"), util = require("../../util"); -const API_FE_URL = process.env.API_FE_URL || "http://vainsocial.dev/bot/api"; - module.exports = class RegisterGuildCommand extends Commando.Command { constructor(client) { super(client, { @@ -49,15 +47,11 @@ Create a Guild with your VainSocial profile as leader. // register a VainSocial Guild to a Discord account async run(msg, args) { util.trackAction(msg, "vainsocial-guild-create"); - console.log(API_FE_URL + "/guild"); - await request.post(API_FE_URL + "/guild", { - forever: true, - form: { - shard_id: args.region, - name: args.name, - identifier: args.tag, - user_token: msg.author.id - } + await api.post("/guild", { + shard_id: args.region, + name: args.name, + identifier: args.tag, + user_token: msg.author.id }); await msg.reply(oneLine` You can now use ${util.usg(msg, "vgadd")} to add members to your Guild. diff --git a/commands/vainsocial/guild_view.js b/commands/vainsocial/guild_view.js index c459590..e692402 100644 --- a/commands/vainsocial/guild_view.js +++ b/commands/vainsocial/guild_view.js @@ -4,11 +4,9 @@ const Commando = require("discord.js-commando"), oneLine = require("common-tags").oneLine, - request = require("request-promise"), + api = require("../../api"), util = require("../../util"); -const API_FE_URL = process.env.API_FE_URL || "http://vainsocial.dev/bot/api"; - module.exports = class ViewGuildCommand extends Commando.Command { constructor(client) { super(client, { @@ -36,13 +34,7 @@ Show a summary of your Guild. async run(msg, args) { util.trackAction(msg, "vainsocial-guild-view"); // get this user's guild - const guild = await request(API_FE_URL + "/guild", { - forever: true, - json: true, - qs: { - user_token: msg.author.id - } - }); + const guild = await api.get("/guild", { user_token: msg.author.id }); if (guild == undefined) { await msg.reply("You are not registered in any guilds."); return; diff --git a/commands/vainsocial/me.js b/commands/vainsocial/me.js index 02818be..400bc70 100644 --- a/commands/vainsocial/me.js +++ b/commands/vainsocial/me.js @@ -4,11 +4,9 @@ const Commando = require("discord.js-commando"), oneLine = require("common-tags").oneLine, - request = require("request-promise"), + api = require("../../api"), util = require("../../util"); -const API_FE_URL = process.env.API_FE_URL || "http://vainsocial.dev/bot/api"; - module.exports = class RegisterUserCommand extends Commando.Command { constructor(client) { super(client, { @@ -36,12 +34,9 @@ Store your in game name for quicker access to other commands and for Guild manag async run(msg, args) { const ign = args.name; util.trackAction(msg, "vainsocial-me", ign); - await request.post(API_FE_URL + "/user", { - forever: true, - form: { - name: ign, - user_token: msg.author.id - } + await api.post("/user", { + name: ign, + user_token: msg.author.id }); await msg.reply(oneLine` You are now able to use ${util.usg(msg, "v")} to access your profile faster. diff --git a/responses.js b/responses.js index 49302a4..ef749eb 100644 --- a/responses.js +++ b/responses.js @@ -117,9 +117,10 @@ Currently running on ${msg.client.guilds.size} servers.`) } // return the sqlite stored ign for this user -function nameByUser(msg) { - throw "nope that's not possible yet"; - //return msg.guild.settings.get("remember+" + msg.author.id); +async function nameByUser(msg) { + const user = await api.get("/user", { user_token: msg.author.id }); + if (user) return user.name; + return undefined; } // show player profile and last match @@ -133,36 +134,24 @@ module.exports.showUser = async (msg, args) => { // shorthand // "?" is not accepted as user input, but the default for empty if (ign == "?") { - ign = nameByUser(msg); + ign = await nameByUser(msg); if (ign == undefined) { await msg.reply(util.formatSorryUnknown(msg)); return; } } - // TODO refactor the update flow a bit - // trigger backend - if (await api.getPlayer(ign) == undefined) - await api.searchPlayer(ign); - else await api.updatePlayer(ign); - - const waiter = api.subscribeUpdates(ign); + const waiter = await api.subscribeUpdates(ign, true); do { - const [player, data] = await Promise.all([ + const [player, matches] = await Promise.all([ api.getPlayer(ign), api.getMatches(ign) ]); - if (player == undefined) { + if (player == undefined || matches.length == 0) { response = await util.respond(msg, "Loading your data…", response); continue; } - if (data == undefined || data[0].data.length == 0) { - response = await util.respond(msg, - "No match history for you yet", response); - continue; - } - const matches = data[0]; const moreHelp = oneLine` *${emoji.symbols.information_source} or ${util.usg(msg, "vm " + ign)} for detail, @@ -170,14 +159,15 @@ ${emoji.symbols["1234"]} or ${util.usg(msg, "vh " + ign)} for more*` const embed = util.vainsocialEmbed(`${ign} - ${player.shard_id}`, "player/" + ign, "vainsocial-user") .setThumbnail(ROOTURL + "images/game/skill_tiers/" + - matches.data[0].skill_tier + ".png") + matches[0].skill_tier + ".png") .setDescription("") .addField("Profile", await formatPlayer(player), true) - .addField("Last match", await formatMatch(matches.data[0]) + moreHelp, true) - .setTimestamp(new Date(matches.data[0].created_at)); + .addField("Last match", await formatMatch(matches[0]) + moreHelp, true) + .setTimestamp(new Date(matches[0].created_at)); response = await util.respond(msg, embed, response); if (!reactionsAdded) { + // build reaction buttton bar reactionsAdded = true; let reactionWaiter = util.awaitReactions(response, [emoji.symbols.information_source, emoji.symbols["1234"]]); @@ -187,7 +177,7 @@ ${emoji.symbols["1234"]} or ${util.usg(msg, "vh " + ign)} for more*` if (rmoji == undefined) break; // timeout if (rmoji == emoji.symbols.information_source) { util.trackAction(msg, "reaction-match", ign); - await respondMatch(msg, ign, matches.data[0].match_api_id); + await respondMatch(msg, ign, matches[0].match_api_id); } if (rmoji == emoji.symbols["1234"]) { util.trackAction(msg, "reaction-matches", ign); @@ -223,33 +213,22 @@ module.exports.showMatch = async (msg, args) => { // shorthand if (ign == "?") { - ign = nameByUser(msg); + ign = await nameByUser(msg); if (ign == undefined) { await msg.reply(util.formatSorryUnknown(msg)); return; } } - // trigger backend - if (await api.getPlayer(ign) == undefined) - await api.searchPlayer(ign); - else await api.updatePlayer(ign); - - const waiter = api.subscribeUpdates(ign); + const waiter = await api.subscribeUpdates(ign, true); do { - const data = await api.getMatches(ign); - if (data == undefined || data[0].data.length == 0) { - response = await util.respond(msg, "No matches for you yet", + const matches = await api.getMatches(ign); + if (index > matches.length) { + response = await util.respond(msg, "Not enough matches yet.", response); continue; } - const matches = data[0]; - if (index - 1 > matches.data.length) { - response = await util.respond(msg, "Not enough matches yet", - response); - continue; - } - let id = matches.data[index -1].match_api_id; + const id = matches[index - 1].match_api_id; response = await respondMatch(msg, ign, id, response); responded = true; } while (await waiter.next() != undefined); @@ -264,10 +243,15 @@ async function respondMatches(msg, ign, response=undefined) { emoji.symbols.seven, emoji.symbols.eight, emoji.symbols.nine, emoji.symbols.ten ]; - const data = await api.getMatches(ign), - matches = data[0].data.slice(0, MATCH_HISTORY_LEN), // TODO + const match_data = await api.getMatches(ign), + matches = match_data.slice(0, MATCH_HISTORY_LEN), matches_num = matches.length; + // not enough data + if (matches_num == 0) return await util.respond(msg, + "No match history yet.", response); + + // build embed let embed = util.vainsocialEmbed(ign, "player/" + ign, "vainsocial-matches") .setDescription(` Last ${matches_num} casual and ranked matches. @@ -279,6 +263,7 @@ Last ${matches_num} casual and ranked matches. ); response = await util.respond(msg, embed, response); + // reaction button bar const reactionWaiter = util.awaitReactions(response, count.slice(0, matches_num)); (async () => { @@ -301,27 +286,15 @@ module.exports.showMatches = async (msg, args) => { // shorthand if (ign == "?") { - ign = nameByUser(msg); + ign = await nameByUser(msg); if (ign == undefined) { await msg.reply(util.formatSorryUnknown(msg)); return; } } - // trigger backend - if (await api.getPlayer(ign) == undefined) - await api.searchPlayer(ign); - else await api.updatePlayer(ign); - - const waiter = api.subscribeUpdates(ign); + const waiter = await api.subscribeUpdates(ign, true); do { - const data = await api.getMatches(ign); - if (data == undefined || data[0].data.length == 0) { - response = await util.respond(msg, "No matches for you yet", - response); - continue; - } - const matches = data[0]; response = await respondMatches(msg, ign, response); responded = true; } while (await waiter.next() != undefined); |
