Skip to content

Commit

Permalink
Merge pull request #141 from ZusorCode/auto-predictions
Browse files Browse the repository at this point in the history
Automatically manage predictions
  • Loading branch information
slmnio authored Oct 14, 2022
2 parents 207854c + 24f3539 commit b9264ce
Show file tree
Hide file tree
Showing 15 changed files with 922 additions and 24 deletions.
4 changes: 4 additions & 0 deletions server/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ DISCORD_TOKEN=
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=

TWITCH_CLIENT_ID=
TWITCH_CLIENT_SECRET=
TWITCH_REDIRECT_URI=

DISCORD_REDIRECT_URI=http://localhost:8080/auth/discord/return # NOTE: only use this as an override, use domains otherwise
DISCORD_REDIRECT_DOMAINS=http://localhost:8080,https://dev.slmn.gg,https://slmn.gg

Expand Down
2 changes: 2 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
"nodemon": "^2.0.7"
},
"dependencies": {
"@twurple/api": "^5.2.5",
"@twurple/auth": "^5.2.5",
"airtable": "^0.10.1",
"body-parser": "^1.19.0",
"chalk": "^4.1.0",
Expand Down
18 changes: 14 additions & 4 deletions server/src/action-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ async function load(expressApp, cors, Cache, io) {
if (!authObjects.client) return res.status(403).send({ error: true, errorMessage: "No client data associated with this token" });
}

if (action.optionalParams) {
(action.optionalParams || []).forEach(key => {
params[key] = req.body[key] || null;
});
}
if (action.requiredParams) {
(action.requiredParams || []).forEach(key => {
params[key] = req.body[key];
Expand All @@ -65,16 +70,20 @@ async function load(expressApp, cors, Cache, io) {
try {
await action.handler(
async (data) => res.send({ error: false, ...data }),
async (errorMessage, errorCode) => res.status(errorCode || 400).send({
error: true,
errorMessage
}),
async (errorMessage, errorCode) => {
console.warn(`Error in action [${action.key}] ${errorCode} ${errorMessage}`);
res.status(errorCode || 400).send({
error: true,
errorMessage
});
},
params,
authObjects,
{
updateRecord: (tableName, item, data) => updateRecord(Cache, tableName, item, data),
get: Cache.get,
createRecord: (tableName, data) => createRecord(Cache, tableName, data),
auth: Cache.auth
}
);
} catch (e) {
Expand Down Expand Up @@ -129,6 +138,7 @@ async function load(expressApp, cors, Cache, io) {
updateRecord: (tableName, item, data) => updateRecord(Cache, tableName, item, data),
get: Cache.get,
createRecord: (tableName, data) => createRecord(Cache, tableName, data),
auth: Cache.auth
}
);
} catch (e) {
Expand Down
7 changes: 4 additions & 3 deletions server/src/action-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async function updateRecord(Cache, tableName, item, data) {
await slmngg(tableName).update(item.id, data);
} catch (e) {
console.error("Airtable update failed", e);
return { error: true};
return { error: true };
}
}

Expand All @@ -70,14 +70,15 @@ async function createRecord(Cache, tableName, records) {
// TODO: think about how eager update would work

try {
let newRecords = await slmngg(tableName).create(records);
let newRecords = await slmngg(tableName).create(records.map(recordData => ({ fields: recordData })));
newRecords.forEach(record => {
Cache.set(cleanID(record.id), deAirtable(record.fields), { eager: true });
});
console.log(newRecords.length);
console.log(newRecords);
} catch (e) {
return { error: true };
console.error("Airtable create failed", e);
return { error: true, errorMessage: e.message };
}
}

Expand Down
154 changes: 154 additions & 0 deletions server/src/actions/manage-prediction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
const { ApiClient } = require("@twurple/api");
const { StaticAuthProvider, refreshUserToken } = require("@twurple/auth");

const automaticPredictionTitleStartCharacter = "⬥";

function generatePredictionTitle(map) {
let title;
if (map.number) {
if (map.name) {
title = `Who will win map ${map.number} - ${map.name}?`;
} else {
title = `Who will win map ${map.number}?`;
}

} else if (map.name) {
title = `Who will win ${map.name}?`;
} else {
title = "Who will win the map?";
}
return `${automaticPredictionTitleStartCharacter} ${title}`;
}

function getTargetPrediction(predictions, teams) {
return predictions.find(p =>
["ACTIVE", "LOCKED"].includes(p.status) &&
p.outcomes.every(outcome => [...teams.map(t => t.name), "Draw"].includes(outcome.title)) &&
p.title.startsWith(automaticPredictionTitleStartCharacter)
);
}

module.exports = {
key: "manage-prediction",
auth: ["client"],
requiredParams: ["predictionAction"],
optionalParams: ["autoLockAfter"],
/***
* @param {ActionSuccessCallback} success
* @param {ActionErrorCallback} error
* @param {PredictionAction} predictionAction
* @param {number?} autoLockAfter
* @param {ClientData} client
* @param {CacheGetFunction} get
* @param {CacheAuthFunctions} auth
* @param {SimpleUpdateRecord} updateRecord
* @returns {Promise<void>}
*/
// eslint-disable-next-line no-empty-pattern
async handler(success, error, { predictionAction, autoLockAfter = 120 }, { client }, { get, auth }) {
if (!(["create", "lock", "resolve", "cancel"].includes(predictionAction))) return error("Invalid action");
console.log(predictionAction);

const broadcast = await get(client?.broadcast?.[0]);
if (!broadcast) return error("No broadcast associated");
if (!broadcast.channel) return error("No channel associated with broadcast");

const channel = await auth.getChannel(broadcast?.channel?.[0]);
if (!channel.twitch_refresh_token) return error("No twitch auth token associated with channel");
if (!channel.channel_id || !channel.name || !channel.twitch_scopes) return error("Invalid channel data");
let scopes = channel.twitch_scopes.split(" ");
if (!["channel:manage:predictions", "channel:read:predictions"].every(scope => scopes.includes(scope))) return error("Token doesn't have the required scopes");

console.log(channel);
const accessToken = await auth.getTwitchAccessToken(channel);

const authProvider = new StaticAuthProvider(process.env.TWITCH_CLIENT_ID, accessToken);
const api = new ApiClient({authProvider});

// TODO: move cancel action to here

const match = await get(broadcast?.live_match?.[0]);
if (!match) return error("No match associated");

const team1 = await get(match?.teams?.[0]);
const team2 = await get(match?.teams?.[1]);
if (!team1 || !team2) return error("Did not find two teams!");

const maps = await Promise.all((match.maps || []).map(async m => {
let map = await get(m);

if (map?.map?.[0]) {
let mapData = await get(map?.map?.[0]);
map.map = mapData;
}

if (map?.winner?.[0]) {
let winner = await get(map?.winner?.[0]);
map.winner = winner;
}

return map;
}));
if (maps.length === 0) return error("No maps associated with match");

const { data: predictions } = await api.predictions.getPredictions(channel.channel_id);


if (["create", "lock"].includes(predictionAction)) {
const currentMap = maps.filter(m => !m.dummy && !m.winner && !m.draw && !m.banner)[0];
if (!currentMap) return error("No valid map to start a prediction for");


const targetPrediction = getTargetPrediction(predictions, [team1, team2]);
console.log(targetPrediction);

if (predictionAction === "create") {
if (targetPrediction) return error("Prediction already exists");
const predictionTitle = generatePredictionTitle(currentMap);

let outcomes = [team1.name, team2.name];

if (!(currentMap && currentMap.map.type === "Control")) {
outcomes.push("Draw");
}

const responsePrediction = await api.predictions.createPrediction(channel.channel_id, {
title: predictionTitle,
outcomes: outcomes,
autoLockAfter: autoLockAfter || 120
});
console.log(responsePrediction);
return success(); // TODO: check responsePrediction for errors
}

if (!targetPrediction) return error("Prediction does not exist");

if (predictionAction === "lock") {
const responsePrediction = await api.predictions.lockPrediction(channel.channel_id, targetPrediction.id);
console.log(responsePrediction);
}

} else if (["resolve"].includes(predictionAction)) {
const lastMap = maps.filter(m => !m.dummy && !m.banner && (m.winner || m.draw)).pop();
const targetPrediction = getTargetPrediction(predictions, [team1, team2]);
console.log(targetPrediction);

if (lastMap.draw) {
const responsePrediction = await api.predictions.resolvePrediction(channel.channel_id, targetPrediction.id, targetPrediction.outcomes.find(o => o.title === "Draw").id);
console.log(responsePrediction);
} else {
const responsePrediction = await api.predictions.resolvePrediction(channel.channel_id, targetPrediction.id, targetPrediction.outcomes.find(o => o.title === lastMap.winner.name).id);
console.log(responsePrediction);
}

} else if (["cancel"].includes(predictionAction)) {
const activePredictions = predictions.filter(p => ["ACTIVE", "LOCKED"].includes(p.status));
for (const prediction of activePredictions) {
const responsePrediction = await api.predictions.cancelPrediction(channel.channel_id, prediction.id);
console.log(responsePrediction);
}
}

return success();
}
};
89 changes: 89 additions & 0 deletions server/src/actions/set-title.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
const { ApiClient } = require("@twurple/api");
const { StaticAuthProvider } = require("@twurple/auth");
module.exports = {
key: "set-title",
auth: ["client"],
/***
* @param {ActionSuccessCallback} success
* @param {ActionErrorCallback} error
* @param {PredictionAction} predictionAction
* @param {number?} autoLockAfter
* @param {ClientData} client
* @param {CacheGetFunction} get
* @param {CacheAuthFunctions} auth
* @param {SimpleUpdateRecord} updateRecord
* @returns {Promise<void>}
*/
// eslint-disable-next-line no-empty-pattern
async handler(success, error, { predictionAction, autoLockAfter = 120 }, { client }, { get, auth }) {

const broadcast = await get(client?.broadcast?.[0]);
if (!broadcast) return error("No broadcast associated");
if (!broadcast.channel) return error("No channel associated with broadcast");

const event = await get(broadcast.event?.[0]);
if (!event) return error("No event associated with broadcast");


const channel = await auth.getChannel(broadcast?.channel?.[0]);
if (!channel.twitch_refresh_token) return error("No twitch auth token associated with channel");
if (!channel.channel_id || !channel.name || !channel.twitch_scopes) return error("Invalid channel data");
let scopes = channel.twitch_scopes.split(" ");
if (!["channel:manage:broadcast"].every(scope => scopes.includes(scope))) return error("Token doesn't have the required scopes");

const accessToken = await auth.getTwitchAccessToken(channel);

const authProvider = new StaticAuthProvider(process.env.TWITCH_CLIENT_ID, accessToken);
const api = new ApiClient({authProvider});


const match = await get(broadcast?.live_match?.[0]);
if (!match) return error("No match associated");

const team1 = await get(match?.teams?.[0]);
const team2 = await get(match?.teams?.[1]);
if (!team1 || !team2) return error("Did not find two teams!");

const formatOptions = {
"event": event.name,
"event_long": event.name,
"event_short": event.short,
"team_1_code": team1.code,
"team_1_name": team1.name,
"team_2_code": team2.code,
"team_2_name": team2.name,
"match_sub_event": match.sub_event,
"match_round": match.round,
"match_number": match.match_number,
};

let newTitle = broadcast.title_format;

Object.entries(formatOptions).forEach(([key, val]) => {
newTitle = newTitle.replace(`{${key}}`, val);
});

const gameMap = {
"Overwatch": "Overwatch 2",
"Valorant": "VALORANT",
"League of Legends": "League of Legends"
};

if (event.game && gameMap[event.game]) {
const game = await api.games.getGameByName(gameMap[event.game]);
const channelInfo = api.channels.updateChannelInfo(channel.channel_id, {
title: newTitle,
gameId: game.id
});
console.log(channelInfo);
} else {
const channelInfo = api.channels.updateChannelInfo(channel.channel_id, {
title: newTitle
});
console.log(channelInfo);
}

return success();
// return response?.error ? error("Airtable error", 500) : success();
}
};
2 changes: 1 addition & 1 deletion server/src/actions/update-map-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ module.exports = {
if (map.score_1) fieldData["Score 1"] = map.score_1;
if (map.score_2) fieldData["Score 2"] = map.score_2;

return { fields: fieldData };
return fieldData;
});

if (recordCreations.length) {
Expand Down
2 changes: 1 addition & 1 deletion server/src/airtable-interface.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ function setRebuilding(isRebuilding) {
// Starting with syncing Matches

// const tables = ["Matches", "Teams", "Themes", "Events", "Players", "Player Relationships"];
const tables = ["Broadcasts", "Clients", "Players", "Events", "Event Series", "Teams", "Ad Reads", "Ad Read Groups", "News", "Matches", "Themes", "Socials", "Accolades", "Player Relationships", "Brackets", "Live Guests", "Headlines", "Maps", "Map Data", "Heroes", "Log Files", "Tracks", "Track Groups", "Track Group Roles"];
const tables = ["Broadcasts", "Clients", "Players", "Channels", "Events", "Event Series", "Teams", "Ad Reads", "Ad Read Groups", "News", "Matches", "Themes", "Socials", "Accolades", "Player Relationships", "Brackets", "Live Guests", "Headlines", "Maps", "Map Data", "Heroes", "Log Files", "Tracks", "Track Groups", "Track Group Roles"];
const staticTables = ["Redirects"];

function deAirtable(obj) {
Expand Down
Loading

0 comments on commit b9264ce

Please sign in to comment.