typing indicator, mentions + bug fixes

This commit is contained in:
Zoe
2023-01-14 06:37:13 -06:00
parent c39da0678d
commit f1c5537697
23 changed files with 629 additions and 190 deletions

View File

@@ -1,8 +1,15 @@
<template>
<li>
<button
class="w-full cursor-pointer bg-[hsl(225,7.7%,10.2%)] hover:bg-[hsl(225,7.7%,17.4%)] text-left px-3 py-1.5 rounded-md flex items-center">
class="w-full cursor-pointer bg-[hsl(225,7.7%,10.2%)] hover:bg-[hsl(225,7.7%,17.4%)] text-left px-3 py-1.5 rounded-md flex items-center justify-between transition-colors"
:class="(danger) ? 'hover:bg-[hsl(359,66.7%,54.1%)]' : ''">
<slot />
</button>
</li>
</template>
</template>
<script>
export default {
props: ['danger']
}
</script>

View File

@@ -23,8 +23,7 @@ export default {
transform-origin: bottom center;
}
.dropdown-inverse > ul {
display: flex;
.dropdown-inverse > div > ul {
flex-direction: column-reverse;
}

View File

@@ -1,5 +1,5 @@
<template>
<div class="w-6/12 bg-[hsl(223,6.9%,19.8%)] p-4 rounded-md shadow-md mr-2">
<div class="w-6/12 bg-[hsl(223,6.9%,19.8%)] mb-1 mt-0.5 p-4 rounded-md shadow-md mr-2">
<p class="text-sm font-semibold text-zinc-100">You've been invited to join a
server</p>
<span class="text-xl font-bold capitalize leading-loose">{{ invite.server.name }}</span>
@@ -47,6 +47,7 @@ export default {
const { server } = await $fetch('/api/guilds/joinGuild', { method: 'POST', body: { inviteId: invite.id }, headers })
if (!server) return;
this.servers?.push(server)
this.invite.server.participants.push(this.user)
},
}
}

View File

@@ -1,29 +1,66 @@
<template>
<div class="h-full bg-[hsl(220,calc(1*7.7%),22.9%)] relative text-white">
<div class="bg-[hsl(220,calc(1*7.7%),22.9%)] absolute w-full shadow px-4 py-3 flex items-center z-[1] shadow-zinc-900/50">
<span>
<svg class="text-zinc-300/80 my-auto" xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24">
<path fill="currentColor"
d="m5.41 21l.71-4h-4l.35-2h4l1.06-6h-4l.35-2h4l.71-4h2l-.71 4h6l.71-4h2l-.71 4h4l-.35 2h-4l-1.06 6h4l-.35 2h-4l-.71 4h-2l.71-4h-6l-.71 4h-2M9.53 9l-1.06 6h6l1.06-6h-6Z" />
</svg>
</span>
<span class="text-zinc-100 font-semibold">{{ server.name }}</span>
<div class="bg-[hsl(220,calc(1*7.7%),22.9%)] absolute w-full shadow px-4 py-3 z-[1] shadow-zinc-900/50">
<div v-if="!server.DM"
class="flex items-center">
<span class="mr-1">
<svg class="text-zinc-300/80 my-auto"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24">
<path fill="currentColor"
d="m5.41 21l.71-4h-4l.35-2h4l1.06-6h-4l.35-2h4l.71-4h2l-.71 4h6l.71-4h2l-.71 4h4l-.35 2h-4l-1.06 6h4l-.35 2h-4l-.71 4h-2l.71-4h-6l-.71 4h-2M9.53 9l-1.06 6h6l1.06-6h-6Z" />
</svg>
</span>
<span class="text-zinc-100 font-semibold">{{ server.name }}</span>
</div>
<div v-else
class="flex items-center">
<span class="mr-1">
<svg class="text-zinc-300/80 my-auto"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24">
<g fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2">
<circle cx="12"
cy="12"
r="4" />
<path d="M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-5.5 8.28" />
</g>
</svg>
</span>
<span class="text-zinc-100 font-semibold">{{
server.dmParticipants.find((e: IUser) => e.id !==
user.id).username
}}</span>
</div>
</div>
<div class="w-full h-[calc(100%-60px)] overflow-y-scroll pb-1"
<div class="w-full h-[calc(100%-76px-48px)] top-[48px] absolute overflow-y-scroll pb-1"
id="conversation-pane">
<div>
<div v-if="conversation.length === 0">
<p>No messages yet</p>
</div>
<div v-else
v-for="message in conversation">
<div class="message-container">
v-for="(message, i) in conversation">
<div class="transition-[backdrop-filter] hover:backdrop-brightness-110 ease-[cubic-bezier(.37,.64,.59,.33)] duration-150 my-4 px-7 py-2"
:class="(i === 0 || conversation[i - 1].creator.id !== message.creator.id) ?
(i === conversation.length - 1 || conversation[i + 1].creator.id !== message.creator.id) ?
/* above and below message is not ours */ '' :
/* below message is ours */ 'mb-0 pb-0.5' :
(i === conversation.length - 1 || conversation[i + 1].creator.id !== message.creator.id) ?
/* above message is ours */ 'mt-0 pt-0.5 pb-1' :
/* above and below message is ours */ 'mt-0 mb-0 py-0.5'">
<div>
<div class="message-sender-text">
<p class="mb-1.5 font-semibold">
<p class="mb-1 font-semibold"
v-if="i === 0 || conversation[i - 1].creator.id !== message.creator.id">
{{ message.creator.username }}
</p>
<p class="break-words max-w-full">{{ message.body }}</p>
@@ -36,10 +73,22 @@
</div>
</div>
</div>
<div class="conversation-input w-[calc(100vw-88px-240px)] h-[61.1px]">
<form @submit.prevent="sendMessage"
<div v-if="showSearch"
class="absolute bottom-[calc(75px+0.5rem)] mx-4 w-[calc(100vw-88px-240px-32px)] py-3 px-4 bg-[hsl(223,6.9%,19.8%)] rounded-lg shadow-md z-5">
<div class="relative flex flex-col">
<div v-for="user in searchResults"
class="mx-2 my-1 w-[calc(100vw-88px-240px-64px-16px)] px-4 py-3 hover:bg-[hsl(223,6.9%,24.3%)] select-none rounded-md transition-colors"
@click="completeMention(user)">
{{ user.username }}
</div>
</div>
</div>
<div class="conversation-input w-[calc(100vw-88px-240px)] h-[75px]">
<form @keyup="checkForMentions"
@keypress="typing($event)"
@submit.prevent="sendMessage"
@keydown.enter.exact.prevent="sendMessage"
class="relative px-4 w-full pt-1.5">
class="relative px-4 w-full pt-1.5 h-fit pb-1">
<div id="textbox"
class="px-4 rounded-md w-full h-[44px] bg-[hsl(218,calc(1*7.9%),27.3%)] placeholder:text-[hsl(218,calc(1*4.6%),46.9%)] flex flex-row">
<textarea type="text"
@@ -63,15 +112,30 @@
d="M10 14L21 3m0 0l-6.5 18a.55.55 0 0 1-1 0L10 14l-7-3.5a.55.55 0 0 1 0-1L21 3" />
</svg></label>
</div>
<div class="w-full">
<p class="text-sm"
v-if="usersTyping.length > 0">
<span v-if="usersTyping.length < 4">
<span v-for="(username, i) in usersTyping"
class="font-semibold">
<span v-if="i === usersTyping.length - 1 && usersTyping.length > 1">and </span>
{{ username }}
<span v-if="i !== usersTyping.length - 1 && usersTyping.length > 1">, </span>
</span>
is typing
</span>
<span v-else>Several users are typing</span>
</p>
</div>
</form>
</div>
</div>
</template>
<script lang="ts">
import { Server } from 'socket.io';
import { useGlobalStore } from '~/stores/store';
import { io } from 'socket.io-client'
import { IChannel, IInviteCode, IMessage } from '~/types';
import { IMessage, IUser } from '~/types';
export default {
props: ['server'],
@@ -81,12 +145,16 @@ export default {
messageContent: '',
conversation: this.server.messages as IMessage[],
canSendNotifications: false,
servers: storeToRefs(useGlobalStore()).servers
servers: storeToRefs(useGlobalStore()).servers,
usersTyping: [] as string[],
socket: storeToRefs(useGlobalStore()).socket as unknown as Server,
showSearch: false,
searchResults: [] as IUser[],
search: ''
}
},
mounted() {
const route = useRoute()
const socket = io();
Notification.requestPermission().then((result) => {
const permission = (result === 'granted') ? true : false
@@ -97,13 +165,25 @@ export default {
if (!conversationDiv) throw new Error('conversation div not found')
this.scrollToBottom()
socket.on(`message-${route.params.id}`, (ev) => {
this.socket.on(`message-${route.params.id}`, (ev: { message: IMessage }) => {
const { message } = ev
if (message.creator.id === this.user.id) return;
if (!document.hasFocus()) {
new Notification(`Message from @${message.creator.username}`, { body: message.body, tag: message.serverId });
new Notification(`Message from @${message.creator.username}`, { body: message.body, tag: route.params.id });
}
const mentions = message.body.match(/<@([a-z]|[0-9]){25}>/g);
if (mentions) {
const participants = (this.server.DM) ? this.server.dmParticipants : this.server.participants;
mentions.forEach((e: string) => {
if (!e) return
const id = e.split('<@')[1]?.split('>')[0];
if (!id) return;
const user = participants.find((e) => e.id === id)
message.body = message.body.split(e).join(`@${user.username}`)
});
}
this.conversation.push(message)
const lastElementChild = conversationDiv.children[0]?.lastElementChild
@@ -114,10 +194,20 @@ export default {
conversationDiv.scrollTop = conversationDiv.scrollHeight;
})
});
let timeout: NodeJS.Timeout;
this.socket.on(`typing-${route.params.id}`, (ev: string) => {
if (ev === this.user.username) return;
clearTimeout(timeout)
timeout = setTimeout(() => {
this.usersTyping = this.usersTyping.filter(username => username !== ev)
}, 750);
if (this.usersTyping.includes(ev)) return;
this.usersTyping.push(ev);
})
},
unmounted() {
const socket = io();
socket.removeAllListeners();
this.socket.removeAllListeners();
},
methods: {
async sendMessage() {
@@ -130,7 +220,22 @@ export default {
if (!message) return;
if (this.conversation.includes(message)) return;
const mentions = message.body.match(/<@([a-z]|[0-9]){25}>/g);
if (mentions) {
const participants = (this.server.DM) ? this.server.dmParticipants : this.server.server.participants;
console.log(participants)
mentions.forEach((e: string) => {
if (!e) return
const id = e.split('<@')[1]?.split('>')[0];
if (!id) return;
const user = participants.find((e) => e.id === id)
message.body = message.body.split(e).join(`@${user.username}`)
console.log(id)
});
}
this.conversation.push(message)
console.log('sent')
this.messageContent = '';
const conversationDiv = document.getElementById('conversation-pane');
if (!conversationDiv) throw new Error('wtf');
@@ -142,6 +247,76 @@ export default {
const conversationDiv = document.getElementById('conversation-pane');
if (!conversationDiv) throw new Error('wtf');
conversationDiv.scrollTo(0, conversationDiv.scrollHeight);
},
typing(event: KeyboardEvent) {
const specialKeys = [
"Backspace",
"Enter",
"Shift",
"Control"
]
if (specialKeys.indexOf(event.key) !== -1) {
return
}
if (event.ctrlKey) {
return
}
const route = useRoute()
this.socket.emit(`typing`, route.params.id);
},
checkForMentions() {
const input = document.getElementById('messageBox') as HTMLTextAreaElement;
const startPosition = input.selectionStart;
const endPosition = input.selectionEnd;
if (startPosition === endPosition && this.inMention(startPosition)) {
let participants
if (this.server.DM) {
participants = this.server.dmParticipants
} else {
participants = this.server.server.participants
}
this.search = this.messageContent.split(' ')[this.messageContent.substring(0, startPosition).split(' ').length - 1].slice(1);
if (this.search.length === 0) {
this.showSearch = false
return;
}
const results = participants.filter((e: IUser) => e.username.includes(this.search)).sort((a: IUser, b: IUser) => {
const usernameA = a.username.toLowerCase();
const usernameB = b.username.toLowerCase();
if (usernameA < usernameB) {
return -1
} else if (usernameA > usernameB) {
return 1
} else {
return 0
}
})
if (results.length === 0) {
this.showSearch = false;
return;
}
this.searchResults = results
this.showSearch = true;
} else {
this.showSearch = false
}
},
inMention(cursorPos: number): boolean {
if (this.messageContent[cursorPos - 1] === '@') return true;
if (this.messageContent[cursorPos - 1] === ' ') return false;
if (cursorPos === 0) return false;
return this.inMention(cursorPos - 1)
},
completeMention(user: IUser) {
this.messageContent = this.messageContent.replace('@' + this.search, `<@${user.id}>`)
this.showSearch = false;
document.getElementById('messageBox')?.focus()
}
// resizeTextarea() {
// const textArea = document.getElementById('messageBox')
@@ -182,8 +357,4 @@ export default {
.message-container:hover {
backdrop-filter: brightness(1.15);
}
.message-sender-you {
font-weight: 600;
}
</style>

View File

@@ -3,7 +3,7 @@
class="p-4 bg-[hsl(216,calc(1*7.2%),13.5%)] grid grid-cols-1 grid-rows-[56px_1fr_56px] h-screen min-w-[88px] text-white relative">
<div>
<nuxt-link to="/channel/@me">
<div @click="openServer('@me', 'dms')"
<div
class="bg-zinc-600/80 p-3 rounded-full transition-all hover:rounded-2xl ease-in-out hover:bg-zinc-500/60 duration-300">
<span>
<svg width="32"
@@ -36,7 +36,6 @@
<nuxt-link v-for="server in servers"
:to="'/channel/' + server.channels[0].id">
<div :key="server.id"
@click="openServer(server.id, 'servers')"
class="bg-zinc-600/80 p-3 rounded-full transition-all hover:rounded-2xl ease-in-out hover:bg-zinc-500/60 duration-300 h-[56px] w-[56px]">
<svg width="32"
height="32"
@@ -123,9 +122,6 @@ export default {
this.serverName = '';
globalStore.addServer(server)
},
openServer(id: string, type: "servers" | "dms"): void {
useGlobalStore().setActive(type, id)
}
},
}
</script>

View File

@@ -7,7 +7,7 @@
:to="'/channel/@me/' + dm.id">
<div
class="mx-2 my-4 hover:bg-[hsl(223,calc(1*6.9%),25.8%)] px-2 py-2 w-[calc(240px-1rem)] max-h-10 h-10 overflow-ellipsis rounded-md transition-colors">
{{ (dm.name).split('-').find((e: string) => e !== user.id) }}
{{ dm.dmParticipants.find((e) => e.id !== user.id).username }}
</div>
</nuxt-link>
</div>
@@ -55,7 +55,10 @@
<ul class="flex flex-col gap-y-1">
<DropdownItem v-if="userIsOwner || userIsAdmin"
@click="createInvite">
<span class="mr-1.5 h-fit">
<span>
Invite a friend
</span>
<span class="h-fit">
<svg xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
@@ -72,9 +75,6 @@
</g>
</svg>
</span>
<span>
Invite a friend
</span>
</DropdownItem>
</ul>
</div>
@@ -102,7 +102,8 @@
@click="openCreateChannelModel"
class="flex text-center hover:bg-[hsl(223,calc(1*6.9%),26.4%)] px-2 py-1.5 w-full transition-colors rounded drop-shadow-sm cursor-pointer items-center">
<span>
<svg class="text-zinc-300/80 my-auto" xmlns="http://www.w3.org/2000/svg"
<svg class="text-zinc-300/80 my-auto"
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24">
@@ -127,6 +128,9 @@
<ul class="flex flex-col gap-y-1">
<DropdownItem v-if="userIsOwner || userIsAdmin"
@click="createInvite">
<span>
Invite a friend
</span>
<span class="mr-1.5 h-fit">
<svg xmlns="http://www.w3.org/2000/svg"
width="20"
@@ -144,8 +148,26 @@
</g>
</svg>
</span>
</DropdownItem>
<DropdownItem @click="logout" danger="true">
<span>
Invite a friend
Logout
</span>
<span class="mr-1.5 h-fit">
<svg xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24">
<g fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2">
<path
d="M14 8V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2-2v-2" />
<path d="M7 12h14l-3-3m0 6l3-3" />
</g>
</svg>
</span>
</DropdownItem>
</ul>
@@ -206,9 +228,10 @@
<script lang="ts">
import { useGlobalStore } from '~/stores/store';
import { IChannel, IRole, IServer } from '~/types';
import { IChannel, IRole } from '~/types';
export default {
props: ['server'],
data() {
return {
server: storeToRefs(useGlobalStore()).activeServer,
@@ -251,6 +274,14 @@ export default {
const headers = useRequestHeaders(['cookie']) as Record<string, string>
const inviteCode = await $fetch(`/api/guilds/${this.server.id}/createInvite`, { method: 'POST', headers })
},
async logout() {
await $fetch(`/api/user/logout`)
useCookie('sessionToken').value = null;
useCookie('userId').value = null;
useGlobalStore().logout();
navigateTo('/login')
}
},
}
</script>

View File

@@ -18,6 +18,7 @@
import { Nav, Sidebar } from '~/.nuxt/components'
import { useGlobalStore } from '~/stores/store'
import { SafeUser } from '~/types'
import { io } from 'socket.io-client'
export default {
data() {
@@ -42,17 +43,21 @@ export default {
globalStore.setServers(servers)
globalStore.setDms(dms)
console.log('params', route.params.id)
if (route.params.id && typeof route.params.id === 'string') {
globalStore.setActive(route.path.includes('@me') ? 'dms' : 'servers', route.params.id)
}
const server = globalStore.activeServer
return {
server
}
}
},
mounted() {
const globalStore = useGlobalStore()
const sessionToken = useCookie('sessionToken')
const socket = io({
auth: (cb) => {
cb({ token: sessionToken.value })
}
});
globalStore.setSocket(socket)
}
}
</script>

View File

@@ -21,6 +21,26 @@ export default {
if (typeof route.params.id !== 'string') throw new Error('route.params.id must be a string, but got an array presumably?')
useGlobalStore().setActive('dms', route.params.id);
function parseBody(body) {
const mentions = body.match(/<@([a-z]|[0-9]){25}>/g);
if (mentions) {
mentions.forEach((e: string) => {
if (!e) return
const id = e.split('<@')[1]?.split('>')[0];
if (!id) return;
const user = server.dmParticipants.find((e) => e.id === id)
body = body.split(e).join(`@${user.username}`)
});
}
return body
}
server.messages?.forEach((e) => {
e.body = parseBody(e.body)
})
return {
server
}

View File

@@ -20,7 +20,6 @@ export default {
}
},
mounted() {
console.log('mounted')
useGlobalStore().setActive('dms', '@me')
},
methods: {

View File

@@ -24,8 +24,28 @@ export default {
if (typeof route.params.id !== 'string') throw new Error('route.params.id must be a string, but got an array presumiably?')
useGlobalStore().setActive('servers', route.params.id)
function parseBody(body) {
const mentions = body.match(/<@([a-z]|[0-9]){25}>/g);
if (mentions) {
mentions.forEach((e: string) => {
if (!e) return
const id = e.split('<@')[1]?.split('>')[0];
if (!id) return;
const user = realServer?.participants.find((e) => e.id === id)
body = body.split(e).join(`@${user.username}`)
});
}
return body
}
server.messages?.forEach((e) => {
e.body = parseBody(e.body)
})
return {
server
server,
}
},
async updated() {
@@ -36,7 +56,9 @@ export default {
this.server = await $fetch(`/api/channels/${route.params.id}`, { headers });
if (typeof route.params.id !== 'string') throw new Error('route.params.id must be a string, but got an array presumiably?')
if (useGlobalStore().activeServer.id !== this.server.id) useGlobalStore().setActive('servers', route.params.id)
if (useGlobalStore().activeServer.id !== this.server.id) {
useGlobalStore().setActive('servers', route.params.id)
}
}
}
</script>

View File

@@ -1,21 +1,26 @@
<template>
<div class="w-screen h-screen bg-[hsl(216,calc(1*7.2%),10%)] relative">
<div class="-translate-y-1/2 -translate-x-1/2 top-1/2 left-1/2 absolute bg-[hsl(216,calc(1*7.2%),16%)] p-4 rounded-md shadow-lg">
<div
class="-translate-y-1/2 -translate-x-1/2 top-1/2 left-1/2 absolute bg-[hsl(216,calc(1*7.2%),16%)] p-4 rounded-md shadow-lg">
<h2 class="text-xl font-semibold text-center">Login</h2>
<form class="flex flex-col gap-y-2 my-2"
@submit.prevent="signup()">
<input class="border border-[hsl(218,calc(1*7.9%),23.7%)] px-4 py-2 rounded w-full bg-[hsl(218,calc(1*7.9%),27.3%)] placeholder:text-[hsl(218,calc(1*4.6%),46.9%)] focus:outline-none"
@submit.prevent="signup()">
<input
class="border border-[hsl(218,calc(1*7.9%),23.7%)] px-4 py-2 rounded w-full bg-[hsl(218,calc(1*7.9%),27.3%)] placeholder:text-[hsl(218,calc(1*4.6%),46.9%)] focus:outline-none"
name="username"
v-model="username"
placeholder="username" />
<input class="border border-[hsl(218,calc(1*7.9%),23.7%)] px-4 py-2 rounded w-full bg-[hsl(218,calc(1*7.9%),27.3%)] placeholder:text-[hsl(218,calc(1*4.6%),46.9%)] focus:outline-none"
<input
class="border border-[hsl(218,calc(1*7.9%),23.7%)] px-4 py-2 rounded w-full bg-[hsl(218,calc(1*7.9%),27.3%)] placeholder:text-[hsl(218,calc(1*4.6%),46.9%)] focus:outline-none"
name="password"
type="password"
v-model="password"
placeholder="password" />
<input type="submit" class="w-full bg-[#5865F2] py-2 px-4 rounded cursor-pointer" />
<input type="submit"
class="w-full bg-[#5865F2] py-2 px-4 rounded cursor-pointer" />
</form>
<div class="text-center">Or <nuxt-link class="hover:underline text-blue-500" to="/signup">Signup</nuxt-link></div>
<div class="text-center">Or <nuxt-link class="hover:underline text-blue-500"
to="/signup">Signup</nuxt-link></div>
</div>
</div>
</template>
@@ -37,14 +42,13 @@ export default {
},
methods: {
async signup() {
const headers = useRequestHeaders(['cookie'])
const globalStore = useGlobalStore();
if (!this.username || !this.password) return;
const user = await $fetch('/api/login', {
method: 'post', body: {
username: this.username,
password: this.password
},
headers
}) as { userId: string; token: string; user: SafeUser; }
const userId = useCookie('userId')
@@ -52,9 +56,19 @@ export default {
const token = useCookie('sessionToken')
token.value = user.token
useGlobalStore().setUser(user.user)
setTimeout(async () => {
const headers = { Cookie: `sessionToken=${token.value}` }
const { servers, dms } = await $fetch('/api/user/getServers', { headers })
navigateTo('/channel/@me')
if (!servers || !dms) return;
globalStore.setServers(servers)
globalStore.setDms(dms)
globalStore.setUser(user.user)
navigateTo('/channel/@me')
})
}
}
}

View File

@@ -48,7 +48,7 @@ export default {
},
methods: {
async signup() {
const headers = useRequestHeaders(['cookie']) as Record<string, string>
const globalStore = useGlobalStore();
if (!this.username || !this.password || !this.email) return;
const user = await $fetch('/api/signup', {
method: 'post', body: {
@@ -56,7 +56,6 @@ export default {
email: this.email,
password: this.password
},
headers
}) as { userId: string; token: string; user: SafeUser; }
const userId = useCookie('userId')
@@ -64,6 +63,12 @@ export default {
const token = useCookie('sessionToken')
token.value = user.token
const headers = { Cookie: `sessionToken=${token.value}`}
const { servers, dms } = await $fetch('/api/user/getServers', { headers })
globalStore.setServers(servers)
globalStore.setDms(dms)
useGlobalStore().setUser(user.user)
navigateTo('/channel/@me')

View File

@@ -65,13 +65,13 @@ model InviteCode {
expiryDate DateTime?
maxUses Int @default(0)
serverId String
Message Message? @relation(fields: [messageId], references: [id])
message Message? @relation(fields: [messageId], references: [id])
messageId String?
}
model Session {
id String @id @default(cuid())
token String
token String @unique
userId String
user User @relation(fields: [userId], references: [id])
}

View File

@@ -26,7 +26,14 @@ export default defineEventHandler(async (event) => {
name: true,
server: {
select: {
id: true
id: true,
name: true,
participants: {
select: {
id: true,
username: true
}
}
}
},
messages: {
@@ -41,12 +48,16 @@ export default defineEventHandler(async (event) => {
},
invites: {
select: {
id: true,
id: true,
server: {
select: {
id: true,
name: true,
participants: true
participants: {
select: {
id: true
}
}
}
}
}

View File

@@ -55,12 +55,37 @@ export default defineEventHandler(async (event) => {
]
}
},
include: {
channels: true,
participants: true,
roles: true
select: {
id: true,
name: true,
channels: {
select: {
id: true,
DM: true,
name: true
}
},
participants: {
select: {
id: true,
username: true
}
},
roles: {
select: {
id: true,
name: true,
administrator: true,
owner: true,
users: {
select: {
id: true
}
}
}
}
}
}) as IServer;
}) as unknown as IServer;
return server
})

View File

@@ -62,8 +62,17 @@ export default defineEventHandler(async (event) => {
dmParticipants: { connect: [{ id: event.context.user.id }, { id: partner.id }] },
DM: true
},
include: {
dmParticipants: true
select: {
id: true,
name: true,
messages: false,
DM: true,
dmParticipants: {
select: {
id: true,
username: true
}
}
}
}) as IChannel

View File

@@ -1,6 +1,7 @@
import { IChannel, IServer, SafeUser, IMessage } from '~/types'
import { Server } from 'socket.io'
import { PrismaClient } from '@prisma/client'
import { registerRuntimeHelpers } from '@vue/compiler-core'
const prisma = new PrismaClient()
declare global {
@@ -28,20 +29,67 @@ export default defineEventHandler(async (event) => {
where: {
id: channelId
},
include: {
dmParticipants: true
select: {
id: true,
name: true,
messages: false,
DM: true,
dmParticipants: {
select: {
id: true,
username: true
}
}
}
}) as IChannel
}) as IChannel | null;
if (!channel) {
event.node.res.statusCode = 404;
return {
message: `Channel with id "${channelId}" not found.`
}
}
if (!channel.DM) {
const server = await prisma.server.findFirst({
where: {
id: channel.serverId
},
include: {
participants: true
select: {
id: true,
name: true,
channels: {
select: {
id: true,
DM: true,
name: true
}
},
participants: {
select: {
id: true,
username: true
}
},
roles: {
select: {
id: true,
name: true,
administrator: true,
owner: true,
users: {
select: {
id: true
}
}
}
}
}
}) as IServer
}) as IServer | null;
if (!server) {
throw new Error(`server with id "${channel.serverId}" is not found but channel with id "${channel.id}" is not a dm?`)
}
const userInServer: SafeUser | undefined = server.participants.find((e: SafeUser) => e.id === event.context.user.id)
@@ -69,11 +117,11 @@ export default defineEventHandler(async (event) => {
}
}
const matches = body.match(/<&([a-z]|[0-9]){25}>/g);
const inviteCodes = body.match(/<&([a-z]|[0-9]){25}>/g);
let invites: { id: string; }[] = [];
if (matches) {
matches.forEach((e: string) => {
if (inviteCodes) {
inviteCodes.forEach((e: string) => {
if (!e) return
const opBody = body;
body = body.split(e).join('')

View File

@@ -71,10 +71,35 @@ export default defineEventHandler(async (event) => {
]
}
},
include: {
participants: true,
channels: true,
roles: true
select: {
id: true,
name: true,
channels: {
select: {
id: true,
DM: true,
name: true
}
},
participants: {
select: {
id: true,
username: true
}
},
roles: {
select: {
id: true,
name: true,
administrator: true,
owner: true,
users: {
select: {
id: true
}
}
}
}
}
}) as unknown as IServer

View File

@@ -25,51 +25,8 @@ export default defineEventHandler(async (event) => {
username: true,
passwordhash: true,
email: true,
channels: {
select: {
id: true,
name: true,
messages: false,
DM: true,
dmParticipants: true,
serverId: true
}
},
servers: {
select: {
id: true,
name: true,
channels: {
select: {
id: true,
DM: true,
name: true,
serverId: true
}
},
participants: {
select: {
id: true,
username: true
}
},
roles: {
select: {
id: true,
name: true,
administrator: true,
owner: true,
users: {
select: {
id: true
}
}
}
}
},
}
},
}) as unknown
}) as unknown as IUser
const isCorrect = await bcryptjs.compare(body.password, user.passwordhash)

View File

@@ -1,7 +1,7 @@
import bcryptjs from "bcryptjs";
import { v4 as uuidv4 } from "uuid";
import { PrismaClient } from '@prisma/client'
import { SafeUser } from "~/types";
import { IUser, SafeUser } from "~/types";
const prisma = new PrismaClient()
export default defineEventHandler(async (event) => {
@@ -45,53 +45,8 @@ export default defineEventHandler(async (event) => {
select: {
id: true,
username: true,
passwordhash: true,
email: true,
channels: {
select: {
id: true,
name: true,
messages: false,
DM: true,
dmParticipants: true,
serverId: true
}
},
servers: {
select: {
id: true,
name: true,
channels: {
select: {
id: true,
DM: true,
name: true,
serverId: true
}
},
participants: {
select: {
id: true,
username: true
}
},
roles: {
select: {
id: true,
name: true,
administrator: true,
owner: true,
users: {
select: {
id: true
}
}
}
}
},
}
},
}) as unknown
}) as unknown as IUser
const token = uuidv4()

23
server/api/user/logout.ts Normal file
View File

@@ -0,0 +1,23 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export default defineEventHandler(async (event) => {
const { sessionToken } = parseCookies(event)
if (!sessionToken) {
event.node.res.statusCode = 400;
return {
message: 'A session token is required to logout duh'
}
}
await prisma.session.delete({
where: {
token: sessionToken
},
})
return {
message: `successfully logged out`
}
})

View File

@@ -1,14 +1,119 @@
// server/middleware/socket.ts
import { Server } from 'socket.io'
import { PrismaClient } from '@prisma/client'
import { IChannel, IServer, IUser, SafeUser } from '~~/types'
const prisma = new PrismaClient()
declare global {
var io: Server | undefined
let io: Server | undefined
}
export default defineEventHandler(({ node }) => {
if (!global.io) {
global.io = new Server(node.res.socket?.server);
global.io.on('connection', (socket) => { })
global.io.on('connection', async (socket) => {
const token = socket.handshake.auth.token;
if (!token) {
return;
}
console.time()
const { user } = await prisma.session.findFirst({
where: {
token
},
select: {
user: {
select: {
id: true,
username: true,
servers: {
select: {
id: true,
name: true,
participants: {
select: {
id: true,
username: true,
roles: {
select: {
id: true,
administrator: true,
owner: true
}
}
}
},
channels: {
select: {
id: true,
DM: true,
server: {
select: {
id: true,
name: true,
participants: {
select: {
id: true,
username: true,
roles: {
select: {
id: true,
administrator: true,
owner: true
}
}
}
},
}
}
}
}
}
},
channels: {
select: {
id: true,
DM: true,
dmParticipants: {
select: {
id: true,
username: true
}
},
}
}
}
}
}
}) as { user: IUser } | null;
console.timeEnd();
if (!user) {
return;
}
socket.on('typing', async (ev) => {
if (!ev) {
return;
}
let channel = user.channels.find((c: IChannel) => c.id === ev) || user.servers.find((s: IServer) => s.channels.some((c: IChannel) => c.id === ev))
if (channel.DM === undefined) {
// assume its a server
channel = channel.channels.find((c: IChannel) => c.id === ev)
}
if (!channel) return;
if (!channel.dmParticipants?.find((e: SafeUser) => e.id === user.id)) {
if (!channel.server || !channel.server.participants.find((e: SafeUser) => e.id === user.id)) {
return
}
}
global.io.emit(`typing-${channel.id}`, user.username)
})
})
}
})

View File

@@ -1,3 +1,4 @@
import { Socket } from "socket.io-client";
import { SafeUser, IServer, IChannel } from "../types";
export const useGlobalStore = defineStore('global', {
@@ -6,7 +7,8 @@ export const useGlobalStore = defineStore('global', {
activeServerType: '' as "dms" | "servers" | undefined,
user: {} as SafeUser,
dms: [] as IChannel[],
servers: [] as IServer[]
servers: [] as IServer[],
socket: null as unknown
}),
actions: {
setUser(user: SafeUser) {
@@ -26,6 +28,9 @@ export const useGlobalStore = defineStore('global', {
setDms(dms: Array<IChannel>) {
this.dms = dms
},
setSocket(socket: Socket) {
this.socket = socket
},
setActive(type: "servers" | "dms", channelId: string) {
if (channelId === '@me') {
this.activeServer = {} as IServer | IChannel
@@ -50,5 +55,11 @@ export const useGlobalStore = defineStore('global', {
this.activeServer = this.servers[activeServerIndex]
},
logout() {
this.dms = []
this.servers = []
this.socket = null
this.activeServer = {} as IServer | IChannel
}
},
})