Skip to content

Commit

Permalink
fix: Allow server to handle global requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
KararTY committed Aug 11, 2020
1 parent 1d492f1 commit fff9ee8
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 36 deletions.
27 changes: 15 additions & 12 deletions app/Services/Handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,22 @@ import Profile from 'App/Models/Profile'
import User from 'App/Models/User'
import { BASE, BIO, EMOTES, MessageType, NameAndId, ROLLMATCH, UNMATCH } from 'befriendlier-shared'
import { DateTime } from 'luxon'
import TwitchConfig from '../../config/twitch'

class Handler {
/**
* MAKE SURE TO CATCH ERRORS.
*/
public async rollMatch ({ userTwitch, channelTwitch }: ROLLMATCH) {
const { chatOwnerUser, profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch)
public async rollMatch ({ userTwitch, channelTwitch, global }: ROLLMATCH) {
const { chatOwnerUser, profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch, global)

if (profile.rolls.length > 0) {
// Return match
const rau = await this.rollUntilAvailableUser(profile.rolls)

if (rau instanceof Error) {
throw this.error(MessageType.ERROR, userTwitch, channelTwitch,
'looks like you\'re not lucky today, rubber ducky 🦆 Try swiping again in a bit.')
'looks like it\'s not your lucky day today, rubber ducky 🦆 Try rolling a match again in a bit.')
} else {
const {
rolls,
Expand Down Expand Up @@ -62,7 +63,7 @@ class Handler {
if (profiles.length === 0) {
await profile.save()
throw this.error(MessageType.TAKEABREAK, userTwitch, channelTwitch,
`looks like you're not lucky today, rubber ducky 🦆 Try swiping again in ${String(profile.nextRolls.toRelative())}.`)
`looks like you're not lucky today, rubber ducky 🦆 Try rolling a match again in ${String(profile.nextRolls.toRelative())}.`)
}

// Shuffle the array!
Expand All @@ -80,8 +81,8 @@ class Handler {
/**
* MAKE SURE TO CATCH ERRORS.
*/
public async match ({ userTwitch, channelTwitch }: BASE) {
const { user, profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch)
public async match ({ userTwitch, channelTwitch, global }: BASE) {
const { user, profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch, global)

const profileId = profile.rolls.shift()

Expand Down Expand Up @@ -164,8 +165,8 @@ class Handler {
return true
}

public async mismatch ({ userTwitch, channelTwitch }: BASE) {
const { profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch)
public async mismatch ({ userTwitch, channelTwitch, global }: BASE) {
const { profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch, global)

const profileId = profile.rolls.shift()

Expand All @@ -180,8 +181,8 @@ class Handler {
await profile.save()
}

public async setEmotes ({ userTwitch, channelTwitch, emotes }: EMOTES) {
const { profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch)
public async setEmotes ({ userTwitch, channelTwitch, emotes, global }: EMOTES) {
const { profile } = await this.findProfileOrCreateByChatOwner(userTwitch, channelTwitch, global)

profile.favoriteEmotes = emotes

Expand Down Expand Up @@ -209,10 +210,12 @@ class Handler {
return user
}

private async findProfileOrCreateByChatOwner (user: User | NameAndId, channel: User | NameAndId):
private async findProfileOrCreateByChatOwner (user: User | NameAndId, channel: User | NameAndId, global = false):
Promise<{ user: User, chatOwnerUser: User, profile: Profile }> {
const userModel = user instanceof User ? user : await User.findBy('twitchID', user.id)
const chatOwnerUserModel = channel instanceof User ? channel : await User.findBy('twitchID', channel.id)
const chatOwnerUserModel = channel instanceof User ? channel
: await User.findBy('twitchID', global ? TwitchConfig.user.id : channel.id)

let profileModel: Profile | null

if (userModel === null) {
Expand Down
35 changes: 17 additions & 18 deletions app/Services/Ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class Ws {
try {
json = bourne.parse(msg, null, { protoAction: 'remove' })
} catch (error) {
// Data's not JSON.
// Data's not JSON.
Logger.error({ err: error }, 'Ws.onMessage(): Error with parsing websocket data.')
return
}
Expand Down Expand Up @@ -139,21 +139,21 @@ class Ws {

switch (rm.more) {
case More.NONE:
rm.result = { value: `new match's bio: ${profile.bio.length > 64 ? `${String(profile.bio.substr(0, 32))}...` : String(profile.bio)}, reply with %prefix%more, %prefix%match or %prefix%no` }
rm.result = { value: `new ${rm.global === true ? 'global ' : ''}match's bio: ${profile.bio.length > 64 ? `${String(profile.bio.substr(0, 32))}...` : String(profile.bio)}, reply with %prefix%more, %prefix%match or %prefix%no` }
socket.send(this.socketMessage(MessageType.ROLLMATCH, JSON.stringify(rm)))
break
case More.BIO:
rm.result = { value: `full bio: ${String(profile.bio)}` }
rm.result = { value: `${rm.global === true ? 'global\'s ' : ''}full bio: ${String(profile.bio)}` }
socket.send(this.socketMessage(MessageType.ROLLMATCH, JSON.stringify(rm)))
break
case More.FAVORITEEMOTES:
rm.result = { value: `match's favorite emotes: ${profile.favoriteEmotes.length > 0 ? String(profile.favoriteEmotes.map(emote => emote.name).join(' ')) : 'None.'}` }
rm.result = { value: `${rm.global === true ? 'global ' : ''}match's favorite emotes: ${profile.favoriteEmotes.length > 0 ? String(profile.favoriteEmotes.map(emote => emote.name).join(' ')) : 'None.'}` }
socket.send(this.socketMessage(MessageType.ROLLMATCH, JSON.stringify(rm)))
break
case More.FAVORITESTREAMERS: {
await user.preload('favoriteStreamers')

rm.result = { value: `match's favorite streamers: ${user.favoriteStreamers.length > 0 ? String(user.favoriteStreamers.map(streamer => streamer.name).join(', ')) : 'None'}.` }
rm.result = { value: `${rm.global === true ? 'global ' : ''}match's favorite streamers: ${user.favoriteStreamers.length > 0 ? String(user.favoriteStreamers.map(streamer => streamer.name).join(', ')) : 'None'}.` }
socket.send(this.socketMessage(MessageType.ROLLMATCH, JSON.stringify(rm)))
break
}
Expand All @@ -167,18 +167,17 @@ class Ws {
const result = await Handler.match(data)
switch (result.attempt) {
case MessageType.MATCH: {
// Attempted to match. Must wait for receiving end.
// Attempted to match. Must wait for receiving end.
data.result = {
value: 'you are attempting to match with a new user. Good luck! ' +
// eslint-disable-next-line comma-dangle
'You will receive a notification on a successful match!'
value: `you are attempting to match with a ${data.global === true ? 'global ' : ''}user. Good luck! ` +
'You will receive a notification on a successful match!',
}
socket.send(this.socketMessage(MessageType.MATCH, JSON.stringify(data)))
break
}
case MessageType.SUCCESS: {
if (result.matchUser !== undefined) {
// Successfully matched!
// Successfully matched!
data.result = {
matchUsername: result.matchUser.name,
value: 'you have matched with %s%! Send them a message?',
Expand Down Expand Up @@ -224,8 +223,7 @@ class Ws {
if (user === null) {
data.result = {
value: 'user does not exist in the database.' +
// eslint-disable-next-line comma-dangle
'Can only add favorited or otherwise registered users.'
'Can only add favorited or otherwise registered users.',
}
socket.send(this.socketMessage(MessageType.ERROR, JSON.stringify(data)))
return
Expand All @@ -242,9 +240,10 @@ class Ws {
if (res.data !== undefined) {
const data = JSON.parse(res.data)
if (data.requestTime !== undefined) {
// This is a request, probably by the "@@join" command.
this.parseRequestResponse(socket, data)
} else {
// Client has sent back a list of all channels.
// Client has sent back a list of all channels.

const socketChannels: Array<{ id: string, channels: string[] }> = []

Expand Down Expand Up @@ -346,10 +345,10 @@ class Ws {
await Handler.setBio(data)
}
}
// case MessageType.TOKEN: {
// socket.send(this.socketMessage(MessageType.TOKEN, JSON.stringify(this.token)))
// break
// }
// case MessageType.TOKEN: {
// socket.send(this.socketMessage(MessageType.TOKEN, JSON.stringify(this.token)))
// break
// }
}
resolve()
}).catch(error => {
Expand All @@ -361,7 +360,7 @@ class Ws {
socket.send(this.socketMessage(MessageType.ERROR, JSON.stringify(error.data)))
} else if (error.message !== undefined) {
Logger.error({ err: error }, 'Ws.handleMessage()')
// socket.send(this.socketMessage(MessageType.ERROR, JSON.stringify(error)))
// socket.send(this.socketMessage(MessageType.ERROR, JSON.stringify(error)))
}
// Else ignore.
reject(new Error())
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"@adonisjs/view": "^2.0.7",
"@hapi/bourne": "^2.0.0",
"@types/ws": "^7.2.6",
"befriendlier-shared": "github:kararty/befriendlier-shared#semver:6.0.0",
"befriendlier-shared": "github:kararty/befriendlier-shared#semver:6.0.1",
"bulma": "^0.9.0",
"feather-icons": "^4.28.0",
"got": "^11.5.1",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit fff9ee8

Please sign in to comment.