feat(resources/server): refactor matchmaker

This commit is contained in:
Christopher committed 2021-06-09 18:51:10 +02:00
1 parent 44a9595463
commit 6a3bef1e34
6 files changed
+420 -529

No files matched your search

@@ -0,0 +1,48 @@
import { Like, MatchEvents, Profile } from '../../../typings/match';
import MatchService from './match.service';
import { getSource } from '../utils/miscUtils';
import { matchLogger } from './match.utils';
import { config } from '../server';
onNet(MatchEvents.INITIALIZE, () => {
const _source = getSource();
MatchService.handleInitialize(_source).catch((e) =>
matchLogger.error(`Error occurred in initialize event (${_source}), Error: ${e.message}`),
);
});
onNet(MatchEvents.CREATE_MY_PROFILE, (profile: Profile) => {
const _source = getSource();
MatchService.handleCreateMyProfile(_source, profile).catch((e) =>
matchLogger.error(`Error occurred in createMyProfile event (${_source}), Error: ${e.message}`),
);
});
onNet(MatchEvents.UPDATE_MY_PROFILE, (profile: Profile) => {
const _source = getSource();
MatchService.handleUpdateMyProfile(_source, profile).catch((e) =>
matchLogger.error(`Error occurred in updateMyProfile event (${_source}), Error: ${e.message}`),
);
});
onNet(MatchEvents.SAVE_LIKES, (likes: Like[]) => {
const _source = getSource();
MatchService.handleSaveLikes(_source, likes).catch((e) =>
matchLogger.error(`Error occurred in saveLikes event (${_source}), Error: ${e.message}`),
);
});
onNet(MatchEvents.GET_MATCHES, () => {
const _source = getSource();
MatchService.handleGetMatches(_source).catch((e) =>
matchLogger.error(`Error occurred in getMatches event (${_source}), Error: ${e.message}`),
);
});
if (!config.match.allowEditableProfileName && !config.match.generateProfileNameFromUsers) {
const warning =
`Both allowEdtiableProfileName and generateProfileNameFromUsers ` +
`are set false - this means users will likely not have profile names ` +
`for the Match App and won't be able to use it!`;
matchLogger.warn(warning);
}
+231
View File
@@ -0,0 +1,231 @@
import { Like, Match, NewProfile, Profile } from '../../../typings/match';
import { pool } from '../db';
import { ResultSetHeader } from 'mysql2';
import { config } from '../server';
import { generateProfileName } from '../utils/generateProfileName';
import { matchLogger } from './match.utils';
const DEFAULT_IMAGE = 'https://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg';
export class _MatchDB {
/**
* Select profiles that:
* 1. aren't the current player
* 2. haven't been viewed before
* 3. have been viewed before but that was at least 7 days ago
* @param identifier - players identifier
* @returns - array of profiles
*/
async getPotentialProfiles(identifier: string): Promise<Profile[]> {
const query = `
SELECT npwd_match_profiles.*,
UNIX_TIMESTAMP(npwd_match_profiles.updatedAt) AS lastActive,
MaxDates.lastSeen
FROM npwd_match_profiles
LEFT OUTER JOIN (
SELECT id, profile, MAX(createdAt) AS lastSeen
FROM npwd_match_views
WHERE identifier = ?
GROUP BY id, profile
) AS MaxDates ON npwd_match_profiles.id = MaxDates.profile
WHERE npwd_match_profiles.identifier != ?
AND (MaxDates.lastSeen IS NULL OR MaxDates.lastSeen < NOW() - INTERVAL 7 DAY)
ORDER BY npwd_match_profiles.updatedAt DESC
LIMIT 25
`;
const [results] = await pool.query(query, [identifier, identifier]);
return <Profile[]>results;
}
/**
* Save a list of Like objects
* @param identifier - player's identifier
* @param likes - likes to be saved to the database
* @returns ResultSet
*/
async saveLikes(identifier: string, likes: Like[]): Promise<ResultSetHeader[]> {
const query = `INSERT INTO npwd_match_views (identifier, profile, liked)
VALUES ?`;
const formattedLikes = likes.map((like) => [identifier, like.id, like.liked]);
const results = await pool.query(query, [formattedLikes]);
return <ResultSetHeader[]>results;
}
/**
* Determines if a profile we just liked has already liked us in the past which
* indicates a match has occurred
* @param identifier - player's identifier
* @param id - profile ID we just liked
* @returns Profile[] - list of profiles that are a match
*/
async checkForMatchById(identifier: string, id: number): Promise<Profile[]> {
const query = `
SELECT targetProfile.*,
UNIX_TIMESTAMP(targetProfile.updatedAt) AS lastActive
FROM npwd_match_views
LEFT OUTER JOIN npwd_match_profiles AS playerProfile ON npwd_match_views.profile = playerProfile.id
LEFT OUTER JOIN npwd_match_profiles AS targetProfile
ON npwd_match_views.identifier = targetProfile.identifier
WHERE playerProfile.identifier = ?
AND targetProfile.id = ?
AND Liked = 1
`;
const [results] = await pool.query(query, [identifier, id]);
return <Profile[]>results;
}
/**
* Return all matches associated with a player regardless of date/time. A
* match is a case where two profiles have liked each other.
* @param identifier - player's identifier
* @returns Match[] - all matches associated with the current player
*/
async findAllMatches(identifier: string): Promise<Match[]> {
const query = `
SELECT targetProfile.*,
UNIX_TIMESTAMP(targetProfile.updatedAt) AS lastActive,
UNIX_TIMESTAMP(GREATEST(npwd_match_views.createdAt, targetViews.createdAt)) AS matchedAt,
targetUser.phone_number AS phoneNumber
FROM npwd_match_views
LEFT OUTER JOIN npwd_match_profiles AS targetProfile ON npwd_match_views.profile = targetProfile.id
LEFT OUTER JOIN npwd_match_profiles AS myProfile ON npwd_match_views.identifier = myProfile.identifier
LEFT OUTER JOIN npwd_match_views AS targetViews
ON targetProfile.identifier = targetViews.identifier AND
targetViews.profile = myProfile.id
LEFT OUTER JOIN ${config.database.playerTable} AS targetUser ON targetProfile.identifier = targetUser.${config.database.identifierColumn}
WHERE npwd_match_views.identifier = ?
AND npwd_match_views.liked = 1
AND targetViews.liked = 1
ORDER BY matchedAt DESC
`;
const [results] = await pool.query(query, [identifier]);
return <Match[]>results;
}
/**
* Retrieve the current player's profile
* @param identifier - player's identifier
* @returns Profile - player's current profile
*/
async getPlayerProfile(identifier: string): Promise<Profile> {
const query = `
SELECT *,
UNIX_TIMESTAMP(updatedAt) AS lastActive
FROM npwd_match_profiles
WHERE identifier = ?
LIMIT 1
`;
const [results] = await pool.query(query, [identifier]);
const profiles = <Profile[]>results;
return profiles[0];
}
/**
* Create a profile and associate it with the current player
* @param identifier - player's identifier
* @param profile - profile we are going to create
* @returns Profile - the created profile
*/
async createProfile(identifier: string, profile: NewProfile): Promise<Profile> {
const { name, image, bio, location, job, tags } = profile;
const query = `
INSERT INTO npwd_match_profiles (identifier, name, image, bio, location, job, tags)
VALUES (?, ?, ?, ?, ?, ?, ?)
`;
await pool.execute(query, [identifier, name, image, bio, location, job, tags]);
return await this.getPlayerProfile(identifier);
}
/**
* Update the current player's profile
* @param identifier - player's identifier
* @param profile Profile - player's updated profile
*/
async updateProfile(identifier: string, profile: Profile): Promise<Profile> {
const { image, name, bio, location, job, tags } = profile;
const query = `
UPDATE npwd_match_profiles
SET image = ?, name = ?, bio = ?, location = ?, job = ?, tags = ?
WHERE identifier = ?
`;
await pool.execute(query, [image, name, bio, location, job, tags, identifier]);
return await this.getPlayerProfile(identifier);
}
/**
* Create a default profile for a player based on information
* associated with them (name, phone number, etc.)
* @param identifier - player's identifier
* @returns Profile | null - the player's profile or null if it does not exist
* and could not be created
*/
async createDefaultProfile(identifier: string): Promise<Profile | null> {
// case where the server owner wants players to select their own names
if (!config.match.generateProfileNameFromUsers) return null;
const defaultProfileName = await generateProfileName(identifier, ' ');
// case where we tried to generate a profile name but failed due to
// some database misconfiguration or error
if (!defaultProfileName) return null;
const defaultProfile = {
name: defaultProfileName,
image: DEFAULT_IMAGE,
bio: '',
location: '',
job: '',
tags: '',
};
matchLogger.info(`Creating default match profile ${defaultProfileName} for ${identifier}`);
return await this.createProfile(identifier, defaultProfile);
}
/**
* Given a list of likes determine if any of the profiles we liked have also
* liked us which indicates a match has occurred.
* @param identifier - player's identifier
* @param likes - list of new Likes
* @returns Profile[] - list of profiles we matched with
*/
async findNewMatches(identifier: string, likes: Like[]): Promise<Profile[]> {
let matches: Profile[] = [];
for (const like of likes) {
if (!like.liked) continue;
const matchedProfiles = await this.checkForMatchById(identifier, like.id);
matches = matches.concat(matchedProfiles);
}
return matches;
}
/**
* Retrieve the player's profile by their identifier if it exists. If
* not, create it and return it.
* @param identifier - player's identifier
* @returns Profile - player's profile
*/
async getOrCreateProfile(identifier: string): Promise<Profile> {
const profile = await this.getPlayerProfile(identifier);
return profile || (await this.createDefaultProfile(identifier));
}
/**
* We track when the player last used the app so other players can
* be aware of how active that player is when they are liking/disliking
* @param identifier - player's identifier
*/
async updateLastActive(identifier: string): Promise<void> {
const query = `
UPDATE npwd_match_profiles
SET updatedAt = CURRENT_TIMESTAMP()
WHERE identifier = ?
`;
await pool.execute(query, [identifier]);
}
}
const MatchDB = new _MatchDB();
export default MatchDB;
+137
View File
@@ -0,0 +1,137 @@
import { matchLogger } from './match.utils';
import MatchDB, { _MatchDB } from './match.db';
import { Like, MatchEvents, Profile } from '../../../typings/match';
import { getOrCreateProfile } from '../sv_match';
import PlayerService from '../players/player.service';
class _MatchService {
private readonly matchDB: _MatchDB;
constructor() {
this.matchDB = MatchDB;
matchLogger.debug('Match service started');
}
async dispatchPlayerProfile(identifier: string, source: number): Promise<void> {
try {
const profile = await this.matchDB.getOrCreateProfile(identifier);
emitNet(MatchEvents.GET_MY_PROFILE_SUCCESS, source, profile);
} catch (e) {
matchLogger.error(`Failed to get player profile, ${e.message}`);
emitNet(MatchEvents.GET_MY_PROFILE_FAILED, source, {
message: 'APPS_MATCH_GET_MY_PROFILE_FAILED',
type: 'error',
});
}
}
async dispatchProfiles(identifier: string, source: number): Promise<void> {
try {
const profiles = await this.matchDB.getPotentialProfiles(identifier);
emitNet(MatchEvents.GET_PROFILES_SUCCESS, source, profiles);
} catch (e) {
matchLogger.error(`Failed to retrieve profiles, ${e.message}`);
emitNet(MatchEvents.GET_PROFILES_FAILED, source, {
message: 'APPS_MATCH_GET_PROFILES_FAILED',
type: 'error',
});
}
}
async handleInitialize(src: number) {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Initializing match for identifier: ${identifier}`);
await this.dispatchPlayerProfile(identifier, src);
await this.dispatchProfiles(identifier, src);
await this.matchDB.updateLastActive(identifier);
}
async handleCreateMyProfile(src: number, profile: Profile) {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Creating profile for identifier: ${identifier}`);
matchLogger.debug(profile);
try {
if (!profile.name || !profile.name.trim()) {
throw new Error('Profile name must not be blank');
}
const newProfile = await this.matchDB.createProfile(identifier, profile);
emitNet(MatchEvents.CREATE_MY_PROFILE_SUCCESS, src, newProfile);
} catch (e) {
matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
emitNet(MatchEvents.CREATE_MY_PROFILE_FAILED, src, {
message: 'APPS_MATCH_CREATE_PROFILE_FAILED',
type: 'error',
});
}
}
async handleUpdateMyProfile(src: number, profile: Profile) {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Updating profile for identifier: ${identifier}`);
matchLogger.debug(profile);
try {
if (!profile.name || !profile.name.trim()) {
throw new Error('Profile name must not be blank');
}
const updatedProfile = await this.matchDB.updateProfile(identifier, profile);
emitNet(MatchEvents.UPDATE_MY_PROFILE_SUCCESS, src, updatedProfile);
} catch (e) {
matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
emitNet(MatchEvents.UPDATE_MY_PROFILE_FAILED, src, {
message: 'APPS_MATCH_UPDATE_PROFILE_FAILED',
type: 'error',
});
}
}
async handleSaveLikes(src: number, likes: Like[]) {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Saving likes for identifier ${identifier}`);
try {
await this.matchDB.saveLikes(identifier, likes);
} catch (e) {
matchLogger.error(`Failed to save likes, ${e.message}`);
emitNet(MatchEvents.SAVE_LIKES_FAILED, src, {
message: 'APPS_MATCH_SAVE_LIKES_FAILED',
type: 'error',
});
}
try {
const newMatches = await this.matchDB.findNewMatches(identifier, likes);
if (newMatches.length > 0) {
emitNet(MatchEvents.NEW_MATCH, src, {
message: 'APPS_MATCH_NEW_LIKE_FOUND',
type: 'info',
});
}
} catch (e) {
matchLogger.error(`Failed to find new matches, ${e.message}`);
}
}
async handleGetMatches(src: number) {
const identifier = PlayerService.getIdentifier(src);
try {
const matchedProfiles = await this.matchDB.findAllMatches(identifier);
emitNet(MatchEvents.GET_MATCHES_SUCCESS, src, matchedProfiles);
} catch (e) {
matchLogger.error(`Failed to retrieve matches, ${e.message}`);
emitNet(MatchEvents.GET_MATCHES_FAILED, src, {
message: 'APPS_MATCH_GET_MATCHES_FAILED',
type: 'error',
});
}
}
}
const MatchService = new _MatchService();
export default MatchService;
+3
View File
@@ -0,0 +1,3 @@
import { mainLogger } from '../sv_logger';
export const matchLogger = mainLogger.child({ module: 'match' });
+1 -2
View File
@@ -16,11 +16,10 @@ import './photo/photo.controller';
import './messages/messages.controller';
import './marketplace/marketplace.controller';
import './twitter/twitter.controller';
import './match/match.controller';
/*import './sv_twitter';*/
import './sv_main';
import './sv_bank';
import './sv_match';
import { mainLogger } from './sv_logger';
export let ESX: Server = null;
-527
View File
@@ -1,527 +0,0 @@
import { ResultSetHeader } from 'mysql2';
import { pool } from './db';
import { NewTweet, Tweet, Profile } from '../../typings/twitter';
import { config } from './server';
import { reportTweetToDiscord } from './discord';
import { mainLogger } from './sv_logger';
import PlayerService from './players/player.service';
import { TwitterEvents } from '../../typings/twitter';
import { getSource } from './utils/miscUtils';
import { generateProfileName } from './utils/generateProfileName';
const twitterLogger = mainLogger.child({ module: 'twitter' });
const formatTweets = (profileId: number) => (tweet: Tweet): Tweet => ({
...tweet,
isMine: tweet.profile_id === profileId,
isRetweet: tweet.isRetweet === 1,
});
const SELECT_FIELDS = `
npwd_twitter_tweets.id,
npwd_twitter_tweets.identifier,
npwd_twitter_profiles.id AS profile_id,
npwd_twitter_profiles.profile_name,
npwd_twitter_profiles.avatar_url,
npwd_twitter_tweets.likes,
npwd_twitter_tweets.visible,
IFNULL(COALESCE(retweets.message, npwd_twitter_tweets.message), '') AS message,
IFNULL(COALESCE(retweets.images, npwd_twitter_tweets.images), '') AS images,
npwd_twitter_tweets.retweet IS NOT NULL AS isRetweet,
retweets.id AS retweetId,
retweets_profiles.profile_name AS retweetProfileName,
retweets_profiles.avatar_url AS retweetAvatarUrl,
npwd_twitter_likes.id IS NOT NULL AS isLiked,
npwd_twitter_reports.id IS NOT NULL AS isReported,
npwd_twitter_tweets.createdAt,
npwd_twitter_tweets.updatedAt,
TIME_TO_SEC(TIMEDIFF( NOW(), npwd_twitter_tweets.createdAt)) AS seconds_since_tweet
`;
/**
* Retrieve the latest 100 tweets
* @param profileId - twitter profile id of the player
*/
async function fetchAllTweets(profileId: number): Promise<Tweet[]> {
const query = `
SELECT
${SELECT_FIELDS}
FROM npwd_twitter_tweets
LEFT OUTER JOIN npwd_twitter_profiles ON npwd_twitter_tweets.identifier = npwd_twitter_profiles.identifier
LEFT OUTER JOIN npwd_twitter_likes ON npwd_twitter_tweets.id = npwd_twitter_likes.tweet_id AND npwd_twitter_likes.profile_id = ?
LEFT OUTER JOIN npwd_twitter_reports ON npwd_twitter_tweets.id = npwd_twitter_reports.tweet_id AND npwd_twitter_reports.profile_id = ?
LEFT OUTER JOIN npwd_twitter_tweets AS retweets ON retweets.id = npwd_twitter_tweets.retweet
LEFT OUTER JOIN npwd_twitter_profiles AS retweets_profiles ON retweets.identifier = retweets_profiles.identifier
WHERE npwd_twitter_tweets.visible = 1
ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100
`;
const [results] = await pool.query(query, [profileId, profileId]);
const tweets = <Tweet[]>results;
return tweets.map(formatTweets(profileId));
}
/**
* Fetch tweets by some search value submitted by the user. Intended to let
* player's search for tweets by profile, message or more.
* @param profileId - twitter profile id of the player
* @param searchValue - value to search
*/
async function fetchTweetsFiltered(profileId: number, searchValue: string): Promise<Tweet[]> {
const parameterizedSearchValue = `%${searchValue}%`;
const query = `
SELECT
${SELECT_FIELDS}
FROM npwd_twitter_tweets
LEFT OUTER JOIN npwd_twitter_profiles ON npwd_twitter_tweets.identifier = npwd_twitter_profiles.identifier
LEFT OUTER JOIN npwd_twitter_likes ON npwd_twitter_tweets.id = npwd_twitter_likes.tweet_id AND npwd_twitter_likes.profile_id = ?
LEFT OUTER JOIN npwd_twitter_reports ON npwd_twitter_tweets.id = npwd_twitter_reports.tweet_id AND npwd_twitter_reports.profile_id = ?
LEFT OUTER JOIN npwd_twitter_tweets AS retweets ON retweets.id = npwd_twitter_tweets.retweet
LEFT OUTER JOIN npwd_twitter_profiles AS retweets_profiles ON retweets.identifier = retweets_profiles.identifier
WHERE npwd_twitter_tweets.visible = 1 AND (npwd_twitter_profiles.profile_name LIKE ? OR npwd_twitter_tweets.message LIKE ?)
ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100
`;
const [results] = await pool.query(query, [
profileId,
profileId,
parameterizedSearchValue,
parameterizedSearchValue,
]);
const tweets = <Tweet[]>results;
return tweets.map(formatTweets(profileId));
}
/**
* Retrieve a Tweet by ID
* @param profileId Unique id for the twitter profile (NOT user identifier)
* @param tweetId - primary key of the tweet ID
*/
async function getTweet(profileId: number, tweetId: number): Promise<Tweet> {
const query = `
SELECT
${SELECT_FIELDS}
FROM npwd_twitter_tweets
LEFT OUTER JOIN npwd_twitter_likes ON npwd_twitter_tweets.id = npwd_twitter_likes.tweet_id AND npwd_twitter_likes.profile_id = ?
LEFT OUTER JOIN npwd_twitter_reports ON npwd_twitter_tweets.id = npwd_twitter_reports.tweet_id AND npwd_twitter_reports.profile_id = ?
LEFT OUTER JOIN npwd_twitter_tweets AS retweets ON retweets.id = npwd_twitter_tweets.retweet
LEFT OUTER JOIN npwd_twitter_profiles AS retweets_profiles ON retweets.identifier = retweets_profiles.identifier
LEFT OUTER JOIN npwd_twitter_profiles ON npwd_twitter_tweets.identifier = npwd_twitter_profiles.identifier
WHERE npwd_twitter_tweets.id = ?
`;
const [results] = await pool.query(query, [profileId, profileId, tweetId]);
const tweets = <Tweet[]>results;
return tweets.map(formatTweets(profileId))[0];
}
/**
* Creates a tweet in the database and then retrieves the tweet
* @param identifier - player identifier
* @param tweet - tweet to be created
*/
async function createTweet(identifier: string, tweet: NewTweet): Promise<Tweet> {
const profile = await getProfile(identifier);
const query = `
INSERT INTO npwd_twitter_tweets (identifier, message, images, retweet)
VALUES (?, ?, ?, ?)
`;
const [results] = await pool.query(query, [
identifier,
tweet.message,
tweet.images,
tweet.retweet,
]);
// This should not be an any type and instead should be
// a Tweet[] according to mysql2 documentation. But instead
// this exec promise returns the row itself, not an array of rows like it states
// Therefore type assertion doesn't work here for correctly typing this out.
const insertData = <ResultSetHeader>results;
return await getTweet(profile.id, insertData.insertId);
}
async function createTweetReport(tweetId: number, profileId: number): Promise<void> {
const query = `
INSERT INTO npwd_twitter_reports (tweet_id, profile_id)
VALUES (?, ?)
`;
await pool.execute(query, [tweetId, profileId]);
}
/**
* Retrieve a player's twitter profile by their identifier
* @param identifier - player identifier
*/
async function getProfile(identifier: string): Promise<Profile | null> {
const query = `
SELECT * FROM npwd_twitter_profiles
WHERE identifier = ?
LIMIT 1
`;
const [results] = await pool.query(query, [identifier]);
const profiles = <Profile[]>results;
return profiles.length > 0 ? profiles[0] : null;
}
/**
* Create a twitter profile
* @param identifier - player's identifier
* @param profileName - profile name to be created
* @returns
*/
async function createProfile(identifier: string, profileName: string): Promise<Profile> {
const query = `
INSERT INTO npwd_twitter_profiles (identifier, profile_name)
VALUES (?, ?)
`;
await pool.execute(query, [identifier, profileName]);
return await getProfile(identifier);
}
/**
* Create a default twitter profile for a player. This is the intial profile
* that all player's will receive and can then customize.
* @param identifier - player's identifier
*/
async function createDefaultProfile(identifier: string): Promise<Profile | null> {
// case where the server owner wants players to select their own names
if (!config.twitter.generateProfileNameFromUsers) return null;
const defaultProfileName = await generateProfileName(identifier);
// case where we tried to generate a profile name but failed due to
// some database misconfiguration or error
if (!defaultProfileName) return null;
twitterLogger.info(`Creating default Twitter profile ${defaultProfileName} for ${identifier}`);
return await createProfile(identifier, defaultProfileName);
}
/**
* Retrieve the player's profile by their identifier if it exists. If
* not, create it and return it.
* @param identifier - player's identifier
*/
export async function getOrCreateProfile(identifier: string): Promise<Profile> {
const profile = await getProfile(identifier);
return profile || (await createDefaultProfile(identifier));
}
async function updateProfile(identifier: string, profile: Profile) {
const { avatar_url, profile_name, bio, location, job } = profile;
const query = `
UPDATE npwd_twitter_profiles
SET avatar_url = ?, profile_name = ?, bio = ?, location = ?, job = ?
WHERE identifier = ?
`;
await pool.execute(query, [avatar_url, profile_name, bio, location, job, identifier]);
}
/**
* Create a "like" in the database that ties a profile & tweet together
* @param profileId - primary key of the profile conducting the like
* @param tweetId - primary key of the tweet being liked
*/
async function createLike(profileId: number, tweetId: number): Promise<void> {
const query = `
INSERT INTO npwd_twitter_likes (profile_id, tweet_id)
VALUES (?, ?)
`;
await pool.execute(query, [profileId, tweetId]);
}
/**
* Delete a "like" relationship from the database
* @param profileId - primary key of the profile removing the like
* @param tweetId - primary key of the tweet to remove the like from
*/
async function deleteLike(profileId: number, tweetId: number): Promise<void> {
const query = `
DELETE FROM npwd_twitter_likes
WHERE profile_id = ? AND tweet_id = ?
`;
await pool.execute(query, [profileId, tweetId]);
}
/**
* Delete a tweet from the database
* @param identifier - identifier of the source user
* @param tweetId - primary key of the tweet to remove the like from
*/
async function deleteTweet(identifier: string, tweetId: number): Promise<void> {
if (!config.twitter.allowDeleteTweets) return;
const query = `
DELETE FROM npwd_twitter_tweets
WHERE identifier = ? AND id = ?
`;
await pool.execute(query, [identifier, tweetId]);
}
/**
* Check if a "like" relationship between a profile and a tweet exists
* @param profileId - primary key of the profile to check
* @param tweetId - primary key of the tweet to check
*/
async function doesLikeExist(profileId: number, tweetId: number): Promise<boolean> {
const query = `
SELECT * FROM npwd_twitter_likes
WHERE profile_id = ? AND tweet_id = ?
LIMIT 1
`;
const [results] = await pool.query(query, [profileId, tweetId]);
const likes = <any[]>results;
return likes.length > 0;
}
/**
* Check if a tweet has been reported by this profile already
* @param tweetId - primary key of the tweet to check
* @param profileId - primary key of the profile to check
*/
async function doesReportExist(tweetId: number, profileId: number): Promise<boolean> {
const query = `
SELECT * FROM npwd_twitter_reports
WHERE tweet_id = ? AND profile_id = ?
LIMIT 1
`;
const [results] = await pool.query(query, [tweetId, profileId]);
const reports = <any[]>results;
return reports.length > 0;
}
/**
* Check to see if this player has already retweeted this tweet or
* is the original poster of a retweeted tweet
* @param tweetId - ID of the tweet in question
* @param identifier - player identifier of the person performing the retweet
*/
async function doesRetweetExist(tweetId: number, identifier: string): Promise<boolean> {
const query = `
SELECT COUNT(id) as count
FROM npwd_twitter_tweets
WHERE (id = ? OR retweet = ?) AND identifier = ?
`;
const [results] = await pool.query(query, [tweetId, tweetId, identifier]);
const counts = <any[]>results;
return counts[0].count > 0;
}
onNet(TwitterEvents.GET_OR_CREATE_PROFILE, async () => {
const _source = getSource();
const identifier = PlayerService.getIdentifier(_source);
try {
const profile = await getOrCreateProfile(identifier);
// if we got null from getOrCreateProfile it means it doesn't exist and
// we failed to create it. In this case we pass the UI some default
// profile names it can choose from.
// We should be able to comment this out as profile **should** be guranteed,
// as we create a default profile in that process.
// if (!profile) {
// const defaultProfileNames = await getDefaultProfileNames(identifier);
// emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_NULL, _source, defaultProfileNames);
// } else {
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_SUCCESS, _source, profile);
// }
} catch (e) {
twitterLogger.error(`Failed to get or create profile, ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_FAILURE, _source);
}
});
onNet(TwitterEvents.CREATE_PROFILE, async (profile: Profile) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
await createProfile(identifier, profile.profile_name);
emitNet(TwitterEvents.CREATE_PROFILE_RESULT, _source, {
message: 'TWITTER_CREATE_PROFILE_SUCCESS',
type: 'success',
});
} catch (e) {
twitterLogger.error(`Failed to create twitter profile: ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.CREATE_PROFILE_RESULT, _source, {
message: 'TWITTER_CREATE_PROFILE_FAILURE',
type: 'error',
});
}
});
onNet(TwitterEvents.UPDATE_PROFILE, async (profile: Profile) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
await updateProfile(identifier, profile);
emitNet(TwitterEvents.UPDATE_PROFILE_RESULT, _source, {
message: 'TWITTER_EDIT_PROFILE_SUCCESS',
type: 'success',
});
} catch (e) {
twitterLogger.error(`Failed to update twitter profile: ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.UPDATE_PROFILE_RESULT, _source, {
message: 'TWITTER_EDIT_PROFILE_FAILURE',
type: 'error',
});
}
});
onNet(TwitterEvents.FETCH_TWEETS, async () => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
const profile = await getProfile(identifier);
if (!profile) {
twitterLogger.warn(
`Aborted fetching tweets for user ${identifier} because they do not have a profile.`,
);
return;
}
const tweets = await fetchAllTweets(profile.id);
emitNet(TwitterEvents.FETCH_TWEETS_SUCCESS, _source, tweets);
} catch (e) {
twitterLogger.error(`Fetching tweets failed, ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.FETCH_TWEETS_FAILURE, _source);
}
});
onNet(TwitterEvents.FETCH_TWEETS_FILTERED, async (searchValue: string) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
const profile = await getProfile(identifier);
const tweets = await fetchTweetsFiltered(profile.id, searchValue);
emitNet(TwitterEvents.FETCH_TWEETS_FILTERED_SUCCESS, _source, tweets);
} catch (e) {
twitterLogger.error(`Fetch filtered tweets failed, ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.FETCH_TWEETS_FILTERED_FAILURE, _source);
}
});
onNet(TwitterEvents.CREATE_TWEET, async (tweet: Tweet) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
const createdTweet = await createTweet(identifier, tweet);
emitNet(TwitterEvents.CREATE_TWEET_BROADCAST, -1, createdTweet);
} catch (e) {
twitterLogger.error(`Create tweet failed, ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.CREATE_TWEET_RESULT, _source, {
message: 'TWITTER_CREATE_FAILED',
type: 'error',
});
}
});
onNet(TwitterEvents.DELETE_TWEET, async (tweetId: number) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
await deleteTweet(identifier, tweetId);
emitNet(TwitterEvents.DELETE_TWEET_SUCCESS, _source);
} catch (e) {
twitterLogger.error(`Delete tweet failed, ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.DELETE_TWEET_FAILURE, _source);
}
});
onNet(TwitterEvents.TOGGLE_LIKE, async (tweetId: number) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
const profile = await getOrCreateProfile(identifier);
const likeExists = await doesLikeExist(profile.id, tweetId);
if (likeExists) {
await deleteLike(profile.id, tweetId);
} else {
await createLike(profile.id, tweetId);
}
emitNet(TwitterEvents.TOGGLE_LIKE_SUCCESS, _source);
} catch (e) {
twitterLogger.error(`Like failed, ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.TOGGLE_LIKE_FAILURE, _source);
}
});
onNet(TwitterEvents.RETWEET, async (tweetId: number) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
// alert the player that they have already retweeted
// this post (or that they are the original poster)
if (await doesRetweetExist(tweetId, identifier)) {
return emitNet(TwitterEvents.RETWEET_EXISTS, _source, {
message: 'TWITTER_RETWEET_EXISTS',
type: 'error',
});
}
// our message for this row is blank because when we
// query for this tweet it will join off of the retweet
// column and fetch the message from the related tweet
const retweet: NewTweet = { message: '', retweet: tweetId };
const createdTweet = await createTweet(identifier, retweet);
const profile = await getProfile(identifier);
const tweet = await getTweet(profile.id, createdTweet.id);
emitNet(TwitterEvents.CREATE_TWEET_BROADCAST, -1, tweet);
} catch (e) {
twitterLogger.error(`Retweet failed, ${e.message}`, {
source: _source,
});
emitNet(TwitterEvents.RETWEET_FAILURE, _source);
}
});
onNet(TwitterEvents.REPORT, async (tweetId: number) => {
const _source = getSource();
try {
const identifier = PlayerService.getIdentifier(_source);
const profile = await getProfile(identifier);
const tweet = await getTweet(profile.id, tweetId);
const reportExists = await doesReportExist(tweet.id, profile.id);
if (reportExists) {
return twitterLogger.warn('This profile has already reported this tweet');
}
await createTweetReport(tweet.id, profile.id);
await reportTweetToDiscord(tweet, profile);
emitNet(TwitterEvents.REPORT_SUCCESS, _source);
} catch (e) {
emitNet(TwitterEvents.REPORT_FAILURE, _source);
twitterLogger.error(`Twitter report failed, ${e.message}`, {
source: _source,
});
}
});
if (!config.twitter.allowEditableProfileName && !config.twitter.generateProfileNameFromUsers) {
const warning =
`Both allowEdtiableProfileName and generateProfileNameFromUsers ` +
`are set false - this means users will likely not have profile names ` +
`for the Twitter App and won't be able to use it!`;
twitterLogger.warn(warning);
}