Appearance improvements, update of endpoints, and implementation of .well-known for checking API URL #3

Merged
sauceyred merged 7 commits from dev into main 2025-05-30 23:21:01 +00:00
14 changed files with 251 additions and 117 deletions

View file

@ -49,4 +49,9 @@ a {
border-radius: .3rem; border-radius: .3rem;
} }
.invisible {
visibility: hidden;
}
</style> </style>

View file

@ -1,19 +1,21 @@
<template> <template>
<div v-if="current" class="channel-list-link-container"> <div v-if="isCurrentChannel" class="channel-list-link-container rounded-corners current-channel">
<NuxtLink class="channel-list-link" :href="props.href"> <NuxtLink class="channel-list-link" :href="props.href">
# {{ name }} # {{ props.name }}
</NuxtLink> </NuxtLink>
</div> </div>
<div v-else class="channel-list-link-container current-channel"> <div v-else class="channel-list-link-container rounded-corners">
<NuxtLink class="channel-list-link" :href="props.href"> <NuxtLink class="channel-list-link" :href="props.href">
# {{ name }} # {{ props.name }}
</NuxtLink> </NuxtLink>
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
const props = defineProps<{ name: string, href: string, current?: boolean }>(); const props = defineProps<{ name: string, uuid: string, currentUuid: string, href: string }>();
const isCurrentChannel = props.uuid == props.currentUuid;
</script> </script>
@ -30,6 +32,7 @@ const props = defineProps<{ name: string, href: string, current?: boolean }>();
display: flex; display: flex;
height: 4dvh; height: 4dvh;
white-space: nowrap; white-space: nowrap;
align-items: center;
} }
.current-channel { .current-channel {

View file

@ -1,6 +1,6 @@
<template> <template>
<div class="message"> <div v-if="props.type == 'normal'" class="message normal-message" :class="{ 'message-margin-bottom': props.marginBottom }">
<div> <div class="left-column">
<img v-if="props.img" class="message-author-avatar" :src="props.img" :alt="username"> <img v-if="props.img" class="message-author-avatar" :src="props.img" :alt="username">
<Icon v-else name="lucide:user" class="message-author-avatar" /> <Icon v-else name="lucide:user" class="message-author-avatar" />
</div> </div>
@ -11,10 +11,6 @@
</span> </span>
<span class="message-date" :title="date.toString()"> <span class="message-date" :title="date.toString()">
{{ messageDate }} {{ messageDate }}
<!--
<div class="message-date-hover" v-if="showHover">
</div>
-->
</span> </span>
</div> </div>
<div class="message-text"> <div class="message-text">
@ -22,17 +18,45 @@
</div> </div>
</div> </div>
</div> </div>
<div v-else ref="messageElement" class="message compact-message">
<div class="left-column">
<div>
<span :class="{ 'invisible': dateHidden }" class="message-date" :title="date.toString()">
{{ messageDate }}
</span>
</div>
</div>
<div class="message-data">
<div class="message-text">
{{ text }}
</div>
</div>
</div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
const props = defineProps<{ class?: string, img?: string | null, username: string, text: string, timestamp: number, format: "12" | "24" }>(); const props = defineProps<{
class?: string,
img?: string | null,
username: string,
text: string,
timestamp: number,
format: "12" | "24",
type: "normal" | "compact",
marginBottom: boolean
}>();
const messageDate = ref<string>(); const messageDate = ref<string>();
const showHover = ref(false);
const messageElement = ref<HTMLDivElement>();
const dateHidden = ref<boolean>(true);
const date = new Date(props.timestamp); const date = new Date(props.timestamp);
console.log("message:", props.text); console.log("Message.vue: message:", props.text);
console.log("Message.vue: message type:", props.type);
let dateHour = date.getHours(); let dateHour = date.getHours();
let dateMinute = date.getMinutes(); let dateMinute = date.getMinutes();
if (props.format == "12") { if (props.format == "12") {
@ -47,7 +71,19 @@ if (props.format == "12") {
} }
} else { } else {
messageDate.value = `${dateHour}:${dateMinute < 10 ? "0" + dateMinute : dateMinute}` messageDate.value = `${dateHour}:${dateMinute < 10 ? "0" + dateMinute : dateMinute}`
} }
onMounted(() => {
messageElement.value?.addEventListener("mouseenter", (e: Event) => {
console.log("mouse enter");
dateHidden.value = false;
});
messageElement.value?.addEventListener("mouseleave", (e: Event) => {
console.log("mouse leave");
dateHidden.value = true;
});
});
//function toggleTooltip(e: Event) { //function toggleTooltip(e: Event) {
// showHover.value = !showHover.value; // showHover.value = !showHover.value;
@ -59,12 +95,15 @@ if (props.format == "12") {
.message { .message {
text-align: left; text-align: left;
/* border: 1px solid lightcoral; */ /* border: 1px solid lightcoral; */
margin-bottom: 1dvh;
display: grid; display: grid;
grid-template-columns: auto 1fr; grid-template-columns: 1fr 19fr;
align-items: center; align-items: center;
} }
.message-margin-bottom {
margin-bottom: 1dvh;
}
.message-metadata { .message-metadata {
display: flex; display: flex;
gap: .5dvw; gap: .5dvw;
@ -86,22 +125,25 @@ if (props.format == "12") {
} }
.message-author-avatar { .message-author-avatar {
margin-right: 1dvw; height: 2.3em;
width: 3em; width: 2.3em;
border-radius: 50%; border-radius: 50%;
} }
.left-column {
margin-right: .5dvw;
text-align: center;
align-content: center;
}
.author-username { .author-username {
margin-right: .5dvw; margin-right: .5dvw;
color: white; color: white;
} }
.message-date { .message-date {
font-size: small; font-size: .7em;
color: rgb(150, 150, 150); color: rgb(150, 150, 150);
}
.message-date:hover {
cursor: default; cursor: default;
} }

View file

@ -1,18 +1,23 @@
<template> <template>
<div id="message-area"> <div id="message-area">
<div id="messages" ref="messagesElement"> <div id="messages" ref="messagesElement">
<Message v-for="message of messages" :username="message.user.display_name ?? message.user.username" :text="message.message" <div v-for="(message, i) of messages">
:timestamp="uuidToTimestamp(message.uuid)" :img="message.user.avatar" format="12" /> <Message :username="message.user.display_name ?? message.user.username"
:text="message.message" :timestamp="messageTimestamps[message.uuid]" :img="message.user.avatar"
format="12" :type="messagesType[message.uuid]"
:margin-bottom="messages[i + 1] && messagesType[messages[i + 1].uuid] == 'normal'" />
</div>
</div>
<div id="message-box" class="rounded-corners">
<form id="message-form" @submit="sendMessage">
<input v-model="messageInput" id="message-box-input" class="rounded-corners" type="text"
name="message-input" autocomplete="off">
<button id="submit-button" type="submit">
<Icon name="lucide:send" />
</button>
</form>
</div>
</div> </div>
<div id="message-box" class="rounded-corners">
<form id="message-form" @submit="sendMessage">
<input v-model="messageInput" id="message-box-input" class="rounded-corners" type="text" name="message-input" autocomplete="off">
<button id="submit-button" type="submit">
<Icon name="lucide:send" />
</button>
</form>
</div>
</div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
@ -21,12 +26,59 @@ import scrollToBottom from '~/utils/scrollToBottom';
const props = defineProps<{ channelUrl: string, amount?: number, offset?: number }>(); const props = defineProps<{ channelUrl: string, amount?: number, offset?: number }>();
const messageTimestamps = ref<Record<string, number>>({});
const messagesType = ref<Record<string, "normal" | "compact">>({});
const messagesRes: MessageResponse[] | undefined = await fetchWithApi( const messagesRes: MessageResponse[] | undefined = await fetchWithApi(
`${props.channelUrl}/messages`, `${props.channelUrl}/messages`,
{ query: { "amount": props.amount ?? 100, "offset": props.offset ?? 0 } } { query: { "amount": props.amount ?? 100, "offset": props.offset ?? 0 } }
); );
if (messagesRes) { if (messagesRes) {
messagesRes.reverse(); messagesRes.reverse();
console.log("messages res:", messagesRes.map(msg => msg.message));
const firstMessageByUsers = ref<Record<string, MessageResponse | undefined>>({});
for (const message of messagesRes) {
messageTimestamps.value[message.uuid] = uuidToTimestamp(message.uuid);
console.log("message:", message.message);
const firstByUser = firstMessageByUsers.value[message.user.uuid];
if (firstByUser) {
console.log("first by user exists");
if (message.user.uuid != firstByUser.user.uuid) {
console.log("message is by new user, setting their first message")
firstMessageByUsers.value[message.user.uuid] = message;
console.log("RETURNING FALSE");
messagesType.value[message.uuid] = "normal";
continue;
}
} else {
console.log("first by user doesn't exist");
console.log(`setting first post by user ${message.user.username} to "${message.message}" with timestamp ${messageTimestamps.value[message.uuid]}`);
firstMessageByUsers.value[message.user.uuid] = message;
console.log("RETURNING FALSE");
messagesType.value[message.uuid] = "normal";
continue;
}
const messageGroupingMaxDifference = useRuntimeConfig().public.messageGroupingMaxDifference;
const prevTimestamp = messageTimestamps.value[firstByUser.uuid];
const timestamp = messageTimestamps.value[message.uuid];
console.log("first message timestamp:", prevTimestamp);
console.log("timestamp:", timestamp);
const diff = (timestamp - prevTimestamp);
console.log("min diff:", messageGroupingMaxDifference);
console.log("diff:", diff);
const lessThanMax = diff <= messageGroupingMaxDifference;
console.log("group?", lessThanMax);
if (!lessThanMax) {
console.log("diff exceeds max");
console.log(`setting first post by user ${message.user.username} to "${message.message}" with timestamp ${messageTimestamps.value[message.uuid]}`)
firstMessageByUsers.value[message.user.uuid] = message;
messagesType.value[message.uuid] = "normal";
continue;
}
console.log("RETURNING " + lessThanMax.toString().toUpperCase());
messagesType.value[message.uuid] = "compact";
}
} }
const messages = ref<MessageResponse[]>([]); const messages = ref<MessageResponse[]>([]);
@ -49,29 +101,28 @@ if (accessToken && apiBase) {
do { do {
console.log("Trying to connect to channel WebSocket..."); console.log("Trying to connect to channel WebSocket...");
ws = new WebSocket(`${apiBase.replace("http", "ws").replace("3000", "8080")}/${props.channelUrl}/socket`, ws = new WebSocket(`${apiBase.replace("http", "ws").replace("3000", "8080")}/${props.channelUrl}/socket`,
["Authorization", accessToken] ["Authorization", accessToken]
); );
if (ws) break; if (ws) break;
await sleep(5000); await sleep(5000);
} while (!ws); } while (!ws);
ws.addEventListener("open", (event) => {
console.log("WebSocket connected!");
});
ws.addEventListener("message", async (event) => {
console.log("event data:", event.data);
messages.value?.push(
JSON.parse(event.data)
);
await nextTick();
if (messagesElement.value) {
console.log("scrolling to bottom");
scrollToBottom(messagesElement);
}
});
ws.addEventListener("open", (event) => {
console.log("WebSocket connected!");
});
ws.addEventListener("message", async (event) => {
console.log("event data:", event.data);
console.log("message uuid:", event.data.uuid);
const parsedData = JSON.parse(event.data);
messageTimestamps.value[parsedData.uuid] = uuidToTimestamp(parsedData.uuid);
messages.value.push(parsedData);
await nextTick();
if (messagesElement.value) {
console.log("scrolling to bottom");
scrollToBottom(messagesElement);
}
});
} else { } else {
await refresh(); await refresh();
@ -82,7 +133,7 @@ function sendMessage(e: Event) {
const text = messageInput.value; const text = messageInput.value;
console.log("text:", text); console.log("text:", text);
if (text) { if (text) {
ws.send(text); ws.send(text);
messageInput.value = ""; messageInput.value = "";
console.log("MESSAGE SENT!!!"); console.log("MESSAGE SENT!!!");
} }
@ -97,13 +148,11 @@ onMounted(async () => {
</script> </script>
<style scoped> <style scoped>
#message-area { #message-area {
display: grid; display: grid;
grid-template-columns: 1fr; grid-template-columns: 1fr;
grid-template-rows: 8fr 1fr; grid-template-rows: 8fr 1fr;
justify-content: space-between; justify-content: space-between;
padding-top: 3dvh;
padding-left: 1dvw; padding-left: 1dvw;
padding-right: 1dvw; padding-right: 1dvw;
overflow: hidden; overflow: hidden;
@ -118,7 +167,7 @@ onMounted(async () => {
padding-bottom: 1dvh; padding-bottom: 1dvh;
padding-top: 1dvh; padding-top: 1dvh;
margin-bottom: 1dvh; margin-bottom: 1dvh;
margin-top: 1dvh; margin-top: 2dvh;
} }
#message-form { #message-form {
@ -152,5 +201,4 @@ onMounted(async () => {
#submit-button:hover { #submit-button:hover {
color: rgb(255, 255, 255); color: rgb(255, 255, 255);
} }
</style> </style>

View file

@ -48,24 +48,30 @@
<script lang="ts" setup> <script lang="ts" setup>
import { FetchError } from 'ofetch'; import { FetchError } from 'ofetch';
const redirectTo = useRoute().query.redirect_to;
const apiVersion = useRuntimeConfig().public.apiVersion; const apiVersion = useRuntimeConfig().public.apiVersion;
const instanceUrl = ref<string | null | undefined>(null); const instanceUrl = ref<string | null | undefined>(null);
const instanceUrlInput = ref<string>(); const instanceUrlInput = ref<string>();
const instanceError = ref<string>(); const instanceError = ref<string>();
const requestUrl = useRequestURL();
const apiBase = useCookie("api_base");
const auth = useAuth(); const auth = useAuth();
if (auth.accessToken.value) { const { status, data: gorbTxt } = await useFetch(`${requestUrl.protocol}//${requestUrl.host}/.well-known/gorb.txt`, { responseType: "text" });
//navigateTo(redirectTo ? redirectTo as string : useAppConfig().baseURL as string); if (status.value == "success" && gorbTxt.value) {
console.log("got gorb.txt:", gorbTxt.value);
const parsed = parseWellKnown(gorbTxt.value as string);
if (parsed.ApiBaseUrl) {
apiBase.value = parsed.ApiBaseUrl;
console.log("set apiBase to:", parsed.ApiBaseUrl);
}
} }
onMounted(() => { onMounted(async () => {
const cookie = useCookie("instance_url").value; const cookie = useCookie("instance_url").value;
instanceUrl.value = cookie; instanceUrl.value = cookie;
console.log(cookie); console.log(cookie);
console.log("set instance url to:", instanceUrl.value); console.log("set instance url to:", instanceUrl.value);
}); });
async function selectInstance(e: Event) { async function selectInstance(e: Event) {
@ -74,14 +80,13 @@ async function selectInstance(e: Event) {
const instanceUrlObj = new URL(`api/v${apiVersion}/stats`, instanceUrlInput.value.endsWith("/") ? instanceUrlInput.value : instanceUrlInput.value + "/"); const instanceUrlObj = new URL(`api/v${apiVersion}/stats`, instanceUrlInput.value.endsWith("/") ? instanceUrlInput.value : instanceUrlInput.value + "/");
try { try {
const res = await $fetch.raw(instanceUrlObj.href); const res = await $fetch.raw(instanceUrlObj.href);
console.log("instance res:", res);
instanceError.value = ""; instanceError.value = "";
const origin = new URL(res.url).origin; const origin = new URL(res.url).origin;
localStorage.setItem("instanceUrl", origin);
instanceUrl.value = origin; instanceUrl.value = origin;
useCookie("instance_url").value = origin; useCookie("instance_url").value = origin;
useCookie("api_base").value = origin + `/api/v${apiVersion}`;
localStorage.setItem("apiBase", origin + `/api/v${apiVersion}`); if (!apiBase.value) apiBase.value = origin + `/api/v${apiVersion}`;
} catch (error: any) { } catch (error: any) {
if (error instanceof FetchError) { if (error instanceof FetchError) {
console.log("Status code:", error.response?.status); console.log("Status code:", error.response?.status);

View file

@ -21,23 +21,12 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { GuildResponse } from '~/types/interfaces';
const loading = useState("loading", () => false); const loading = useState("loading", () => false);
const servers = [ const servers: GuildResponse[] | undefined = await fetchWithApi("/me/guilds");
{
name: "Test",
uuid: "0197088b-e4e8-7033-8e6b-7ceb065e9acd"
},
{
name: "Test",
uuid: "0197088b-e4e8-7033-8e6b-7ceb065e9acd"
},
{
name: "Test",
uuid: "0197088b-e4e8-7033-8e6b-7ceb065e9acd"
}
];
//const servers = await fetchWithApi("/servers") as { uuid: string, name: string, description: string }[]; //const servers = await fetchWithApi("/servers") as { uuid: string, name: string, description: string }[];
//console.log("servers:", servers); //console.log("servers:", servers);
@ -80,14 +69,6 @@ const members = [
} }
]; ];
function sendMessage(e: Event) {
e.preventDefault();
const textInput = document.getElementById("message-box-input") as HTMLInputElement;
const text = textInput.value;
console.log("MESSAGE SENT!!!");
console.log("text:", text);
}
</script> </script>
<style> <style>

View file

@ -26,7 +26,8 @@ export default defineNuxtConfig({
}, },
runtimeConfig: { runtimeConfig: {
public: { public: {
apiVersion: 1 apiVersion: 1,
messageGroupingMaxDifference: 300000
} }
}, },
/* nitro: { /* nitro: {

View file

@ -15,13 +15,15 @@
<button type="submit">Login</button> <button type="submit">Login</button>
</div> </div>
</form> </form>
<div> <div v-if="registrationEnabled">
Don't have an account? <NuxtLink :href="registerUrl">Register</NuxtLink> one! Don't have an account? <NuxtLink :href="registerUrl">Register</NuxtLink> one!
</div> </div>
</NuxtLayout> </NuxtLayout>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { StatsResponse } from '~/types/interfaces';
definePageMeta({ definePageMeta({
layout: "auth" layout: "auth"
@ -36,6 +38,18 @@ const form = reactive({
const query = useRoute().query as Record<string, string>; const query = useRoute().query as Record<string, string>;
const searchParams = new URLSearchParams(query); const searchParams = new URLSearchParams(query);
const instanceUrl = useCookie("instance_url").value;
const registrationEnabled = ref<boolean>(true);
if (instanceUrl) {
const statsUrl = new URL("/stats", instanceUrl).href;
const { status, data } = await useFetch<StatsResponse>(statsUrl);
if (status.value == "success" && data.value) {
registrationEnabled.value = data.value.registration_enabled;
}
}
const registerUrl = `/register?${searchParams}` const registerUrl = `/register?${searchParams}`
const { login } = useAuth(); const { login } = useAuth();

View file

@ -1,6 +1,6 @@
<template> <template>
<NuxtLayout> <NuxtLayout>
<form @submit="register"> <form v-if="registrationEnabled" @submit="register">
<div> <div>
<!-- <!--
<span class="form-error" v-if="errors.username.length > 0"> <span class="form-error" v-if="errors.username.length > 0">
@ -32,6 +32,9 @@
<button type="submit">Register</button> <button type="submit">Register</button>
</div> </div>
</form> </form>
<div v-else>
<h3>This instance has disabled registration.</h3>
</div>
<div> <div>
Already have an account? <NuxtLink :href="loginUrl">Log in</NuxtLink>! Already have an account? <NuxtLink :href="loginUrl">Log in</NuxtLink>!
</div> </div>
@ -39,11 +42,22 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { StatsResponse } from '~/types/interfaces';
definePageMeta({ definePageMeta({
layout: "auth" layout: "auth"
}) })
const instanceUrl = useCookie("instance_url").value;
const registrationEnabled = ref<boolean>(false);
if (instanceUrl) {
const statsUrl = new URL("/stats", instanceUrl).href;
const { status, data, error } = await useFetch<StatsResponse>(statsUrl);
if (status.value == "success" && data.value) {
registrationEnabled.value = data.value.registration_enabled;
}
}
const form = reactive({ const form = reactive({
username: "", username: "",
email: "", email: "",

View file

@ -18,10 +18,9 @@
</h3> </h3>
</div> </div>
<div id="channels-list"> <div id="channels-list">
<Channel v-for="channel of channels" v-if="route.params.channelId == channel?.uuid" :name="channel.name" <Channel v-for="channel of channels" :name="channel.name"
:href="route.path" :current="true" /> :uuid="channel.uuid" :current-uuid="(route.params.channelId as string)"
<Channel v-for="channel of channels" v-else :name="channel.name" :href="`/guilds/${route.params.serverId}/channels/${channel.uuid}`" />
:href="`/servers/${route.params.serverId}/channels/${channel.uuid}`" />
</div> </div>
</div> </div>
<MessageArea :channel-url="channelUrlPath" /> <MessageArea :channel-url="channelUrlPath" />
@ -41,7 +40,7 @@ const route = useRoute();
const loading = useState("loading"); const loading = useState("loading");
const channelUrlPath = `servers/${route.params.serverId}/channels/${route.params.channelId}`; const channelUrlPath = `/channels/${route.params.channelId}`;
const server = ref<GuildResponse | undefined>(); const server = ref<GuildResponse | undefined>();
const channels = ref<ChannelResponse[] | undefined>(); const channels = ref<ChannelResponse[] | undefined>();
@ -102,19 +101,15 @@ const members = [
]; ];
onMounted(async () => { onMounted(async () => {
loading.value = true;
console.log("channelid: set loading to true"); console.log("channelid: set loading to true");
server.value = await fetchWithApi(`servers/${route.params.serverId}`); server.value = await fetchWithApi(`servers/${route.params.serverId}`);
channels.value = await fetchWithApi( channels.value = await fetchWithApi(`/channels`);
`servers/${route.params.serverId}/channels` console.log("channels:", channels.value);
); channel.value = await fetchWithApi(route.path);
channel.value = await fetchWithApi( console.log("channel:", channel.value);
route.path
);
console.log("channelid: channel:", channel); console.log("channelid: channel:", channel);
loading.value = false;
console.log("channelid: set loading to false"); console.log("channelid: set loading to false");
}); });
@ -151,4 +146,10 @@ function toggleInvitePopup(e: Event) {
border-left: 1px solid rgb(70, 70, 70); border-left: 1px solid rgb(70, 70, 70);
} }
#channels-list {
display: flex;
flex-direction: column;
gap: 1dvh;
}
</style> </style>

View file

@ -5,7 +5,7 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
const server = await fetchWithApi(`/servers/${useRoute().params.serverId}`); const server = await fetchWithApi(`/guilds/${useRoute().params.serverId}`);
console.log("server:", server); console.log("server:", server);
</script> </script>

View file

@ -53,3 +53,12 @@ export interface UserResponse {
email?: string, email?: string,
email_verified?: boolean email_verified?: boolean
} }
export interface StatsResponse {
accounts: number,
uptime: number,
version: string,
registration_enabled: boolean,
email_verification_required: boolean,
build_number: string
}

View file

@ -1,6 +1,6 @@
import type { UserResponse } from "~/types/interfaces" import type { UserResponse } from "~/types/interfaces"
export default async (serverId: string, memberId: string): Promise<UserResponse> => { export default async (serverId: string, memberId: string): Promise<UserResponse> => {
const user = await fetchWithApi(`/servers/${serverId}/members/${memberId}`) as UserResponse; const user = await fetchWithApi(`/guilds/${serverId}/members/${memberId}`) as UserResponse;
return user; return user;
} }

11
utils/parseWellKnown.ts Normal file
View file

@ -0,0 +1,11 @@
export default (wellKnownText: string): Record<string, string> => {
const lines = wellKnownText.trim().replaceAll(" ", "").split("\n");
const settings: Record<string, string> = {};
for (const line of lines) {
const separatorIndex = line.search(":");
const key = line.slice(0, separatorIndex);
const value = line.slice(separatorIndex + 1, line.length);
settings[key] = value;
}
return settings;
}