Compare commits

...

19 Commits

Author SHA1 Message Date
888d3cb5ba 🐛 Fix authorize redirect 2025-09-26 01:34:26 +08:00
f8ad92ccf2 🐛 Trying to fix authorize page 2025-09-26 01:31:23 +08:00
847fecc67b 🍱 Add favicon 2025-09-26 01:15:17 +08:00
c9f90bdc33 💄 Optimize footer display 2025-09-26 01:13:31 +08:00
5c5b35b1b5 🐛 Fix authorization 2025-09-26 01:11:58 +08:00
0c36ff1bcd 🐛 Fix authorize 2025-09-26 01:00:07 +08:00
f95d6778c2 🗑️ Remove the route 2025-09-26 00:08:13 +08:00
744622addf 💄 Optimize readability of swagger 2025-09-25 23:59:18 +08:00
2de1e12c33 🐛 Fix bugs 2025-09-25 02:22:53 +08:00
54e8ffea6f Swagger docs 2025-09-25 02:18:13 +08:00
16a5207c02 🐛 Fix api route 2025-09-24 01:15:36 +08:00
52971c2d67 🐛 Fix 2025-09-24 00:58:15 +08:00
056010e8b6 🐛 Fix package 2025-09-24 00:53:26 +08:00
7e8cdb6348 Files 2025-09-24 00:45:31 +08:00
531a082d94 Magic spell 2025-09-24 00:21:41 +08:00
42f1d42506 💄 Optimize posts 2025-09-24 00:04:13 +08:00
8ce154eef2 🐛 Fix reaction 2025-09-21 00:31:47 +08:00
07ec5ffc55 🐛 Remove lock 2025-09-21 00:15:08 +08:00
db6c023651 🗑️ Remove package manager lock 2025-09-21 00:11:43 +08:00
25 changed files with 823 additions and 15396 deletions

View File

@@ -1,6 +1,10 @@
<template> <template>
<nuxt-loading-indicator /> <nuxt-loading-indicator :color="colorMode.value == 'dark' ? 'white' : '#3f51b5'" />
<nuxt-layout> <nuxt-layout>
<nuxt-page /> <nuxt-page />
</nuxt-layout> </nuxt-layout>
</template> </template>
<script setup lang="ts">
const colorMode = useColorMode()
</script>

View File

@@ -1,5 +1,5 @@
<template> <template>
<v-card> <v-card class="px-4 py-3">
<v-card-text> <v-card-text>
<div class="flex flex-col gap-3"> <div class="flex flex-col gap-3">
<post-header :item="props.item" /> <post-header :item="props.item" />
@@ -20,7 +20,11 @@
<div v-html="htmlContent" /> <div v-html="htmlContent" />
</article> </article>
<div v-if="props.item.attachments.length > 0" class="d-flex gap-2 flex-wrap" @click.stop> <div
v-if="props.item.attachments.length > 0"
class="d-flex gap-2 flex-wrap"
@click.stop
>
<attachment-item <attachment-item
v-for="attachment in props.item.attachments" v-for="attachment in props.item.attachments"
:key="attachment.id" :key="attachment.id"
@@ -32,8 +36,8 @@
<div @click.stop> <div @click.stop>
<post-reaction-list <post-reaction-list
:parent-id="props.item.id" :parent-id="props.item.id"
:reactions="(props.item as any).reactions || {}" :reactions="props.item.reactionsCount"
:reactions-made="(props.item as any).reactionsMade || {}" :reactions-made="props.item.reactionsMade"
:can-react="true" :can-react="true"
@react="handleReaction" @react="handleReaction"
/> />
@@ -45,7 +49,14 @@
<script lang="ts" setup> <script lang="ts" setup>
import { ref, watch } from "vue" import { ref, watch } from "vue"
import { Marked } from "marked" import { unified } from "unified"
import remarkParse from "remark-parse"
import remarkMath from "remark-math"
import remarkRehype from "remark-rehype"
import remarkBreaks from "remark-breaks"
import remarkGfm from "remark-gfm"
import rehypeKatex from "rehype-katex"
import rehypeStringify from "rehype-stringify"
import type { SnPost } from "~/types/api" import type { SnPost } from "~/types/api"
import PostHeader from "./PostHeader.vue" import PostHeader from "./PostHeader.vue"
@@ -54,7 +65,14 @@ import PostReactionList from "./PostReactionList.vue"
const props = defineProps<{ item: SnPost }>() const props = defineProps<{ item: SnPost }>()
const marked = new Marked() const processor = unified()
.use(remarkParse)
.use(remarkMath)
.use(remarkBreaks)
.use(remarkGfm)
.use(remarkRehype)
.use(rehypeKatex)
.use(rehypeStringify)
const htmlContent = ref<string>("") const htmlContent = ref<string>("")
@@ -87,9 +105,9 @@ function handleReaction(symbol: string, attitude: number, delta: number) {
watch( watch(
props.item, props.item,
async (value) => { (value) => {
if (value.content) if (value.content)
htmlContent.value = await marked.parse(value.content, { breaks: true }) htmlContent.value = String(processor.processSync(value.content))
}, },
{ immediate: true, deep: true } { immediate: true, deep: true }
) )

View File

@@ -165,30 +165,38 @@ const reactionDialog = ref(false)
// Available reaction templates // Available reaction templates
const availableReactions: ReactionTemplate[] = [ const availableReactions: ReactionTemplate[] = [
{ symbol: "like", emoji: "👍", attitude: 1 }, { symbol: "thumb_up", emoji: "👍", attitude: 0 },
{ symbol: "love", emoji: "❤️", attitude: 2 }, { symbol: "thumb_down", emoji: "👎", attitude: 2 },
{ symbol: "laugh", emoji: "😂", attitude: 1 }, { symbol: "just_okay", emoji: "😅", attitude: 1 },
{ symbol: "wow", emoji: "😮", attitude: 1 }, { symbol: "cry", emoji: "😭", attitude: 1 },
{ symbol: "sad", emoji: "😢", attitude: -1 }, { symbol: "confuse", emoji: "🧐", attitude: 1 },
{ symbol: "angry", emoji: "😠", attitude: -2 }, { symbol: "clap", emoji: "👏", attitude: 0 },
{ symbol: "fire", emoji: "🔥", attitude: 2 }, { symbol: "laugh", emoji: "😂", attitude: 0 },
{ symbol: "clap", emoji: "👏", attitude: 1 }, { symbol: "angry", emoji: "😡", attitude: 2 },
{ symbol: "think", emoji: "🤔", attitude: 0 }, { symbol: "party", emoji: "🎉", attitude: 0 },
{ symbol: "pray", emoji: "🙏", attitude: 1 }, { symbol: "pray", emoji: "🙏", attitude: 0 },
{ symbol: "celebrate", emoji: "🎉", attitude: 2 }, { symbol: "heart", emoji: "❤️", attitude: 0 }
{ symbol: "heart", emoji: "💖", attitude: 2 }
] ]
function camelToSnake(str: string): string {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
}
function getReactionEmoji(symbol: string): string { function getReactionEmoji(symbol: string): string {
const reaction = availableReactions.find((r) => r.symbol === symbol) let reaction = availableReactions.find((r) => r.symbol === symbol)
if (reaction) return reaction.emoji
// Try camelCase to snake_case conversion
const snakeSymbol = camelToSnake(symbol)
reaction = availableReactions.find((r) => r.symbol === snakeSymbol)
return reaction?.emoji || "❓" return reaction?.emoji || "❓"
} }
function getReactionColor(symbol: string): string { function getReactionColor(symbol: string): string {
const attitude = const attitude =
availableReactions.find((r) => r.symbol === symbol)?.attitude || 0 availableReactions.find((r) => r.symbol === symbol)?.attitude || 1
if (attitude > 0) return "success" if (attitude === 0) return "success"
if (attitude < 0) return "error" if (attitude === 2) return "error"
return "primary" return "primary"
} }

View File

@@ -14,17 +14,12 @@
Service Status Service Status
</a> </a>
<span class="font-bold">·</span> <span class="font-bold">·</span>
<a <nuxt-link class="link" target="_blank" to="/swagger"> API </nuxt-link>
class="link"
target="_blank"
href="https://solian.app/swagger/index.html"
>
API
</a>
</div> </div>
<p class="mt-2 opacity-80"> <p class="mt-2 opacity-80">
The FloatingIsland do not provides all the features the Solar Network has, The FloatingIsland do not provides all the features the Solar Network has,
for further usage, see <a href="https://web.solian.app" class="font-bold underline">Solian</a> for further usage, see
<a href="https://web.solian.app" class="font-bold underline">Solian</a>
</p> </p>
</div> </div>
</template> </template>

View File

@@ -8,12 +8,15 @@ export const useSolarNetwork = (withoutProxy = false) => {
baseURL: apiBase, baseURL: apiBase,
credentials: "include", credentials: "include",
// Add Authorization header with Bearer token // Add Authorization header with Bearer token
onRequest: ({ options }) => { onRequest: ({ request, options }) => {
const side = process.server ? 'SERVER' : 'CLIENT'
console.log(`[useSolarNetwork] onRequest for ${request} on ${side}`)
// Get token from user store // Get token from user store
const userStore = useUserStore() const userStore = useUserStore()
const token = userStore.token const token = userStore.token
if (token) { if (token) {
console.log('[useSolarNetwork] Token found, adding Authorization header.')
if (!options.headers) { if (!options.headers) {
options.headers = new Headers() options.headers = new Headers()
} }
@@ -23,6 +26,8 @@ export const useSolarNetwork = (withoutProxy = false) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
;(options.headers as any)["Authorization"] = `Bearer ${token}` ;(options.headers as any)["Authorization"] = `Bearer ${token}`
} }
} else {
console.log('[useSolarNetwork] No token found, skipping Authorization header.')
} }
// Transform request data from camelCase to snake_case // Transform request data from camelCase to snake_case

View File

@@ -1,17 +1,28 @@
<template> <template>
<v-app :theme="colorMode.preference"> <v-app :theme="colorMode.preference">
<v-app-bar flat height="48">
<v-container class="mx-auto d-flex align-center justify-center">
<p class="text-sm">Solar Network</p>
</v-container>
</v-app-bar>
<v-main> <v-main>
<slot /> <slot />
</v-main> </v-main>
<nuxt-link to="/">
<v-footer app fixed flat height="48">
<v-container class="mx-auto d-flex align-center justify-between">
<img
:src="Icon"
alt="Cloudy Lamb"
height="24"
width="24"
class="mr-2"
/>
<p class="text-sm">Solar Network</p>
</v-container>
</v-footer>
</nuxt-link>
</v-app> </v-app>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import Icon from "~/assets/images/cloudy-lamb.png"
const colorMode = useColorMode() const colorMode = useColorMode()
</script> </script>

View File

@@ -181,7 +181,14 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from "vue" import { computed, ref, watch } from "vue"
import { Marked } from "marked" import { unified } from "unified"
import remarkParse from "remark-parse"
import remarkMath from "remark-math"
import remarkBreaks from "remark-breaks"
import remarkRehype from "remark-rehype"
import rehypeKatex from "rehype-katex"
import rehypeStringify from "rehype-stringify"
import remarkGfm from "remark-gfm"
const route = useRoute() const route = useRoute()
@@ -239,15 +246,22 @@ const perkSubscriptionNames: Record<string, PerkSubscriptionInfo> = {
} }
} }
const marked = new Marked() const processor = unified()
.use(remarkParse)
.use(remarkMath)
.use(remarkBreaks)
.use(remarkGfm)
.use(remarkRehype)
.use(rehypeKatex)
.use(rehypeStringify)
const htmlBio = ref<string | undefined>(undefined) const htmlBio = ref<string | undefined>(undefined)
watch( watch(
user, user,
async (value) => { (value) => {
htmlBio.value = value?.profile.bio htmlBio.value = value?.profile.bio
? await marked.parse(value.profile.bio, { breaks: true }) ? String(processor.processSync(value.profile.bio))
: undefined : undefined
}, },
{ immediate: true, deep: true } { immediate: true, deep: true }
@@ -316,21 +330,29 @@ useHead({
}), }),
meta: computed(() => { meta: computed(() => {
if (user.value) { if (user.value) {
const description = `View the profile of ${user.value.nick || user.value.name} on Solar Network.` const description = `View the profile of ${
return [ user.value.nick || user.value.name
{ name: 'description', content: description }, } on Solar Network.`
] return [{ name: "description", content: description }]
} }
return [] return []
}) })
}) })
defineOgImage({ defineOgImage({
component: 'ImageCard', component: "ImageCard",
title: computed(() => user.value ? user.value.nick || user.value.name : 'User Profile'), title: computed(() =>
description: computed(() => user.value ? `View the profile of ${user.value.nick || user.value.name} on Solar Network.` : ''), user.value ? user.value.nick || user.value.name : "User Profile"
),
description: computed(() =>
user.value
? `View the profile of ${
user.value.nick || user.value.name
} on Solar Network.`
: ""
),
avatarUrl: computed(() => userPicture.value), avatarUrl: computed(() => userPicture.value),
backgroundImage: computed(() => userBackground.value), backgroundImage: computed(() => userBackground.value)
}) })
</script> </script>

View File

@@ -7,7 +7,7 @@
<div class="pa-8"> <div class="pa-8">
<div class="mb-4"> <div class="mb-4">
<img <img
:src="$vuetify.theme.current.dark ? IconDark : IconLight" :src="colorMode.value == 'dark' ? IconDark : IconLight"
alt="CloudyLamb" alt="CloudyLamb"
height="60" height="60"
width="60" width="60"
@@ -34,32 +34,36 @@
<!-- App Info Section --> <!-- App Info Section -->
<div v-if="clientInfo" class="mb-6"> <div v-if="clientInfo" class="mb-6">
<div class="d-flex align-center mb-4"> <div class="d-flex align-center mb-4 text-left">
<v-avatar
v-if="clientInfo.picture"
:src="clientInfo.picture.url"
:alt="clientInfo.client_name"
size="large"
class="mr-3"
/>
<div> <div>
<h3 class="text-xl font-semibold"> <h3 class="text-xl font-semibold">
{{ clientInfo.client_name || 'Unknown Application' }} {{ clientInfo.clientName || "Unknown Application" }}
</h3> </h3>
<p class="text-base"> <p class="text-base">
{{ isNewApp ? 'wants to access your Solar Network account' : 'wants to access your account' }} {{
isNewApp
? "wants to access your Solar Network account"
: "wants to access your account"
}}
</p> </p>
</div> </div>
</div> </div>
<!-- Requested Permissions --> <!-- Requested Permissions -->
<v-card variant="outlined" class="pa-4 mb-4"> <v-card variant="outlined" class="pa-4 mb-4 text-left">
<h4 class="font-medium mb-2"> <h4 class="font-medium mb-2">
This will allow {{ clientInfo.client_name || 'the app' }} to: This will allow
{{ clientInfo.clientName || "the app" }} to
</h4> </h4>
<ul class="space-y-1"> <ul class="space-y-1">
<li v-for="scope in requestedScopes" :key="scope" class="d-flex align-start"> <li
<v-icon class="mt-1 mr-2" color="success">mdi-check-box</v-icon> v-for="scope in requestedScopes"
:key="scope"
class="d-flex align-start"
>
<v-icon class="mt-1 mr-2" color="success" size="18"
>mdi-check</v-icon
>
<span>{{ scope }}</span> <span>{{ scope }}</span>
</li> </li>
</ul> </ul>
@@ -86,27 +90,6 @@
Deny Deny
</v-btn> </v-btn>
</div> </div>
<div class="mt-4 text-sm text-center">
By authorizing, you agree to the
<v-btn
variant="text"
size="small"
@click="openTerms"
class="px-1 text-capitalize"
>
Terms of Service
</v-btn>
and
<v-btn
variant="text"
size="small"
@click="openPrivacy"
class="px-1 text-capitalize"
>
Privacy Policy
</v-btn>
</div>
</div> </div>
</div> </div>
</v-col> </v-col>
@@ -118,12 +101,14 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted } from 'vue' import { ref, computed, onMounted } from "vue"
import { useRoute } from 'vue-router' import { useRoute } from "vue-router"
import { useSolarNetwork } from '~/composables/useSolarNetwork' import { useSolarNetwork } from "~/composables/useSolarNetwork"
import IconLight from '~/assets/images/cloudy-lamb.png' import IconLight from "~/assets/images/cloudy-lamb.png"
import IconDark from '~/assets/images/cloudy-lamb@dark.png' import IconDark from "~/assets/images/cloudy-lamb@dark.png"
const colorMode = useColorMode()
const route = useRoute() const route = useRoute()
const api = useSolarNetwork() const api = useSolarNetwork()
@@ -137,11 +122,9 @@ const isLoading = ref(true)
const isAuthorizing = ref(false) const isAuthorizing = ref(false)
const error = ref<string | null>(null) const error = ref<string | null>(null)
const clientInfo = ref<{ const clientInfo = ref<{
client_name?: string clientName?: string
home_uri?: string homeUri?: string
picture?: { url: string } picture?: { url: string }
terms_of_service_uri?: string
privacy_policy_uri?: string
scopes?: string[] scopes?: string[]
} | null>(null) } | null>(null)
const isNewApp = ref(false) const isNewApp = ref(false)
@@ -158,7 +141,8 @@ async function fetchClientInfo() {
clientInfo.value = await api(`/id/auth/open/authorize?${queryString}`) clientInfo.value = await api(`/id/auth/open/authorize?${queryString}`)
checkIfNewApp() checkIfNewApp()
} catch (err: any) { } catch (err: any) {
error.value = err.message || 'An error occurred while loading the authorization request' error.value =
err.message || "An error occurred while loading the authorization request"
} finally { } finally {
isLoading.value = false isLoading.value = false
} }
@@ -173,19 +157,19 @@ function checkIfNewApp() {
async function handleAuthorize() { async function handleAuthorize() {
isAuthorizing.value = true isAuthorizing.value = true
try { try {
const data = await api<{ redirect_uri?: string }>('/auth/open/authorize', { const data = await api<{ redirectUri?: string }>(
method: 'POST', "/id/auth/open/authorize",
body: { {
...route.query, method: "POST",
authorize: 'true', body: new URLSearchParams(window.location.search.slice(1))
}, }
}) )
if (data.redirect_uri) { if (data.redirectUri) {
window.location.href = data.redirect_uri window.location.href = data.redirectUri
} }
} catch (err: any) { } catch (err: any) {
error.value = err.message || 'An error occurred during authorization' error.value = err.message || "An error occurred during authorization"
} finally { } finally {
isAuthorizing.value = false isAuthorizing.value = false
} }
@@ -195,29 +179,21 @@ function handleDeny() {
// Redirect back to the client with an error // Redirect back to the client with an error
// Ensure redirect_uri is always a string (not an array) // Ensure redirect_uri is always a string (not an array)
const redirectUriStr = Array.isArray(route.query.redirect_uri) const redirectUriStr = Array.isArray(route.query.redirect_uri)
? route.query.redirect_uri[0] || clientInfo.value?.home_uri || '/' ? route.query.redirect_uri[0] || clientInfo.value?.homeUri || "/"
: route.query.redirect_uri || clientInfo.value?.home_uri || '/' : route.query.redirect_uri || clientInfo.value?.homeUri || "/"
const redirectUri = new URL(redirectUriStr) const redirectUri = new URL(redirectUriStr)
// Ensure state is always a string (not an array) // Ensure state is always a string (not an array)
const state = Array.isArray(route.query.state) const state = Array.isArray(route.query.state)
? route.query.state[0] || '' ? route.query.state[0] || ""
: route.query.state || '' : route.query.state || ""
const params = new URLSearchParams({ const params = new URLSearchParams({
error: 'access_denied', error: "access_denied",
error_description: 'The user denied the authorization request', error_description: "The user denied the authorization request",
state: state, state: state
}) })
window.open(`${redirectUri}?${params}`, "_self") window.open(`${redirectUri}?${params}`, "_self")
} }
function openTerms() {
window.open(clientInfo.value?.terms_of_service_uri || '#', "_blank")
}
function openPrivacy() {
window.open(clientInfo.value?.privacy_policy_uri || '#', "_blank")
}
// Lifecycle // Lifecycle
onMounted(() => { onMounted(() => {
fetchClientInfo() fetchClientInfo()

246
app/pages/files/[id].vue Normal file
View File

@@ -0,0 +1,246 @@
<template>
<div class="d-flex align-center justify-center fill-height">
<v-card class="pa-6" max-width="1200" width="100%">
<v-progress-circular
v-if="!fileInfo && !error"
indeterminate
size="32"
></v-progress-circular>
<v-alert
type="error"
title="No file was found"
:text="error"
v-else-if="error"
></v-alert>
<div v-else>
<v-row>
<v-col cols="12" md="6">
<div v-if="fileInfo.isEncrypted">
<v-alert type="info" title="Encrypted file" class="mb-4">
The file has been encrypted. Preview not available. Please enter
the password to download it.
</v-alert>
</div>
<div v-else>
<v-img
v-if="fileType === 'image'"
:src="fileSource"
class="w-full"
/>
<video
v-else-if="fileType === 'video'"
:src="fileSource"
controls
class="w-full"
/>
<audio
v-else-if="fileType === 'audio'"
:src="fileSource"
controls
class="w-full"
/>
<v-alert
type="warning"
title="Preview Unavailable"
text="How can you preview this file?"
v-else
/>
</div>
</v-col>
<v-col cols="12" md="6">
<div class="mb-3">
<v-card
title="File Information"
prepend-icon="mdi-information-outline"
variant="tonal"
>
<v-card-text>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-information</v-icon>
File Type
</span>
<span>{{ fileInfo.mimeType }} ({{ fileType }})</span>
</div>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-chart-pie</v-icon>
File Size
</span>
<span>{{ formatBytes(fileInfo.size) }}</span>
</div>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-upload</v-icon>
Uploaded At
</span>
<span>{{
new Date(fileInfo.createdAt).toLocaleString()
}}</span>
</div>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-details</v-icon>
Technical Info
</span>
<v-btn
text
size="x-small"
@click="showTechDetails = !showTechDetails"
>
{{ showTechDetails ? "Hide" : "Show" }}
</v-btn>
</div>
<v-expand-transition>
<div
v-if="showTechDetails"
class="mt-2 d-flex flex-column gap-1"
>
<p class="text-caption opacity-75">#{{ fileInfo.id }}</p>
<v-card class="pa-2" variant="outlined">
<pre
class="overflow-x-auto px-2 py-1"
><code>{{ JSON.stringify(fileInfo.fileMeta, null, 4) }}</code></pre>
</v-card>
</div>
</v-expand-transition>
</v-card-text>
</v-card>
</div>
<div class="d-flex flex-column gap-3">
<v-text-field
v-if="fileInfo.isEncrypted"
label="Password"
v-model="filePass"
type="password"
/>
<v-btn class="flex-grow-1" @click="downloadFile">Download</v-btn>
</div>
<v-expand-transition>
<v-progress-linear
v-if="!!progress"
:model-value="progress"
:indeterminate="progress < 100"
class="mt-4"
/>
</v-expand-transition>
</v-col>
</v-row>
</div>
</v-card>
</div>
</template>
<script setup lang="ts">
import { useRoute } from "vue-router"
import { computed, onMounted, ref } from "vue"
import { downloadAndDecryptFile } from "./secure"
import { formatBytes } from "./format"
const route = useRoute()
const error = ref<string | null>(null)
const filePass = ref<string>("")
const fileId = route.params.id
const passcode = route.query.passcode as string | undefined
const progress = ref<number | undefined>(0)
const showTechDetails = ref<boolean>(false)
const api = useSolarNetwork()
const fileInfo = ref<any>(null)
async function fetchFileInfo() {
try {
let url = "/drive/files/" + fileId + "/info"
if (passcode) {
url += `?passcode=${passcode}`
}
const resp = await api(url)
fileInfo.value = resp
} catch (err) {
error.value = (err as Error).message
}
}
onMounted(() => fetchFileInfo())
const apiBase = useSolarNetworkUrl(false)
const fileType = computed(() => {
if (!fileInfo.value) return "unknown"
return fileInfo.value.mimeType?.split("/")[0] || "unknown"
})
const fileSource = computed(() => {
let url = `${apiBase}/drive/files/${fileId}`
if (passcode) {
url += `?passcode=${passcode}`
}
return url
})
async function downloadFile() {
if (fileInfo.value.isEncrypted && !filePass.value) {
alert("Please enter the password to download the file.")
return
}
if (fileInfo.value.isEncrypted) {
downloadAndDecryptFile(
fileSource.value,
filePass.value,
fileInfo.value.name,
(p: number) => {
progress.value = p * 100
}
).catch((err: any) => {
alert("Download failed: " + err.message)
progress.value = undefined
})
} else {
const res = await fetch(fileSource.value)
if (!res.ok) {
throw new Error(
`Failed to download ${fileInfo.value.name}: ${res.statusText}`
)
}
const contentLength = res.headers.get("content-length")
if (!contentLength) {
throw new Error("Content-Length response header is missing.")
}
const total = parseInt(contentLength, 10)
const reader = res.body!.getReader()
const chunks: Uint8Array[] = []
let received = 0
while (true) {
const { done, value } = await reader.read()
if (done) break
if (value) {
chunks.push(value)
received += value.length
progress.value = (received / total) * 100
}
}
const blob = new Blob(chunks as BlobPart[])
const blobUrl = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = blobUrl
a.download =
fileInfo.value.fileName ||
"download." + fileInfo.value.mimeType.split("/")[1]
document.body.appendChild(a)
a.click()
a.remove()
window.URL.revokeObjectURL(blobUrl)
}
}
</script>

View File

@@ -0,0 +1,8 @@
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

94
app/pages/files/secure.ts Normal file
View File

@@ -0,0 +1,94 @@
export async function downloadAndDecryptFile(
url: string,
password: string,
fileName: string,
onProgress?: (progress: number) => void,
): Promise<void> {
const response = await fetch(url)
if (!response.ok) throw new Error(`Failed to fetch: ${response.status}`)
const contentLength = +(response.headers.get('Content-Length') || 0)
const reader = response.body!.getReader()
const chunks: Uint8Array[] = []
let received = 0
while (true) {
const { done, value } = await reader.read()
if (done) break
if (value) {
chunks.push(value)
received += value.length
if (contentLength && onProgress) {
onProgress(received / contentLength)
}
}
}
const fullBuffer = new Uint8Array(received)
let offset = 0
for (const chunk of chunks) {
fullBuffer.set(chunk, offset)
offset += chunk.length
}
const decryptedBytes = await decryptFile(fullBuffer, password)
// Create a blob and trigger a download
const blob = new Blob([decryptedBytes])
const downloadUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = downloadUrl
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(downloadUrl)
}
export async function decryptFile(fileBuffer: Uint8Array, password: string): Promise<Uint8Array> {
const salt = fileBuffer.slice(0, 16)
const nonce = fileBuffer.slice(16, 28)
const tag = fileBuffer.slice(28, 44)
const ciphertext = fileBuffer.slice(44)
const enc = new TextEncoder()
const keyMaterial = await crypto.subtle.importKey(
'raw',
enc.encode(password),
{ name: 'PBKDF2' },
false,
['deriveKey'],
)
const key = await crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['decrypt'],
)
const fullCiphertext = new Uint8Array(ciphertext.length + tag.length)
fullCiphertext.set(ciphertext)
fullCiphertext.set(tag, ciphertext.length)
let decrypted: ArrayBuffer
try {
decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: nonce, tagLength: 128 },
key,
fullCiphertext,
)
} catch {
throw new Error('Incorrect password or corrupted file.')
}
const magic = new TextEncoder().encode('DYSON1')
const decryptedBytes = new Uint8Array(decrypted)
for (let i = 0; i < magic.length; i++) {
if (decryptedBytes[i] !== magic[i]) {
throw new Error('Incorrect password or corrupted file.')
}
}
return decryptedBytes.slice(magic.length)
}

View File

@@ -31,7 +31,7 @@
<post-editor @posted="refreshActivities" /> <post-editor @posted="refreshActivities" />
</v-card-text> </v-card-text>
</v-card> </v-card>
<sidebar-footer /> <sidebar-footer class="max-lg:hidden" />
</div> </div>
</div> </div>
</v-container> </v-container>
@@ -47,20 +47,23 @@ import type { SnVersion, SnActivity } from "~/types/api"
import PostEditor from "~/components/PostEditor.vue" import PostEditor from "~/components/PostEditor.vue"
import PostItem from "~/components/PostItem.vue" import PostItem from "~/components/PostItem.vue"
import IconLight from '~/assets/images/cloudy-lamb.png' import IconLight from "~/assets/images/cloudy-lamb.png"
const router = useRouter() const router = useRouter()
useHead({ useHead({
title: "Explore", title: "Explore",
meta: [ meta: [
{ name: 'description', content: 'The open social network. Friendly to everyone.' }, {
name: "description",
content: "The open social network. Friendly to everyone."
}
] ]
}) })
defineOgImage({ defineOgImage({
title: 'Explore', title: "Explore",
description: 'The open social network. Friendly to everyone.', description: "The open social network. Friendly to everyone."
}) })
const userStore = useUserStore() const userStore = useUserStore()
@@ -102,7 +105,7 @@ onMounted(() => fetchActivites())
useInfiniteScroll(window, fetchActivites, { useInfiniteScroll(window, fetchActivites, {
canLoadMore: () => !loading.value && activitesHasMore.value, canLoadMore: () => !loading.value && activitesHasMore.value,
distance: 10, distance: 10
}) })
async function refreshActivities() { async function refreshActivities() {

View File

@@ -91,7 +91,7 @@
<!-- Other Types: Merged Header, Content, and Attachments --> <!-- Other Types: Merged Header, Content, and Attachments -->
<template v-else> <template v-else>
<!-- Merged Header, Content, and Attachments Section --> <!-- Merged Header, Content, and Attachments Section -->
<v-card class="mb-4 elevation-1" rounded="lg"> <v-card class="px-4 py-3 mb-4 elevation-1" rounded="lg">
<v-card-text class="pa-6"> <v-card-text class="pa-6">
<post-header :item="post" class="mb-4" /> <post-header :item="post" class="mb-4" />
@@ -206,7 +206,14 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from "vue" import { computed } from "vue"
import { Marked } from "marked" import { unified } from "unified"
import remarkParse from "remark-parse"
import remarkMath from "remark-math"
import remarkRehype from "remark-rehype"
import rehypeKatex from "rehype-katex"
import rehypeStringify from "rehype-stringify"
import remarkBreaks from "remark-breaks"
import remarkGfm from "remark-gfm"
import type { SnPost } from "~/types/api" import type { SnPost } from "~/types/api"
import PostHeader from "~/components/PostHeader.vue" import PostHeader from "~/components/PostHeader.vue"
@@ -216,17 +223,28 @@ import PostReactionList from "~/components/PostReactionList.vue"
const route = useRoute() const route = useRoute()
const id = route.params.id as string const id = route.params.id as string
const marked = new Marked() const processor = unified()
.use(remarkParse)
.use(remarkMath)
.use(remarkBreaks)
.use(remarkGfm)
.use(remarkRehype)
.use(rehypeKatex)
.use(rehypeStringify)
const apiServer = useSolarNetwork(true); const apiServer = useSolarNetwork(true)
const { data: postData, error, pending } = await useAsyncData(`post-${id}`, async () => { const {
data: postData,
error,
pending
} = await useAsyncData(`post-${id}`, async () => {
try { try {
const resp = await apiServer(`/sphere/posts/${id}`) const resp = await apiServer(`/sphere/posts/${id}`)
const post = resp as SnPost const post = resp as SnPost
let html = "" let html = ""
if (post.content) { if (post.content) {
html = await marked.parse(post.content, { breaks: true }) html = String(processor.processSync(post.content))
} }
return { post, html } return { post, html }
} catch (e) { } catch (e) {
@@ -245,7 +263,7 @@ useHead({
if (pending.value) return "Loading post..." if (pending.value) return "Loading post..."
if (error.value) return "Error" if (error.value) return "Error"
if (!post.value) return "Post not found" if (!post.value) return "Post not found"
return post.value.title || "Post" return `${post.value?.title || "Post"} from ${post.value?.publisher.nick}`
}), }),
meta: computed(() => { meta: computed(() => {
if (post.value) { if (post.value) {
@@ -265,8 +283,8 @@ const userPicture = computed(() => {
: undefined : undefined
}) })
const userBackground = computed(() => { const userBackground = computed(() => {
const firstImageAttachment = post.value?.attachments?.find(att => const firstImageAttachment = post.value?.attachments?.find((att) =>
att.mimeType?.startsWith('image/') att.mimeType?.startsWith("image/")
) )
return firstImageAttachment return firstImageAttachment
? `${apiBase}/drive/files/${firstImageAttachment.id}` ? `${apiBase}/drive/files/${firstImageAttachment.id}`
@@ -274,11 +292,14 @@ const userBackground = computed(() => {
}) })
defineOgImage({ defineOgImage({
component: 'ImageCard', component: "ImageCard",
title: computed(() => post.value?.title || 'Post'), title: computed(() => post.value?.title || "Post"),
description: computed(() => post.value?.description || post.value?.content?.substring(0, 150) || ''), description: computed(
() =>
post.value?.description || post.value?.content?.substring(0, 150) || ""
),
avatarUrl: computed(() => userPicture.value), avatarUrl: computed(() => userPicture.value),
backgroundImage: computed(() => userBackground.value), backgroundImage: computed(() => userBackground.value)
}) })
function formatDate(dateString: string): string { function formatDate(dateString: string): string {

View File

@@ -0,0 +1,115 @@
<template>
<div class="d-flex align-center justify-center fill-height">
<v-card max-width="400" title="Magic Spell" prepend-icon="mdi-magic-staff" class="pa-2">
<v-card-text>
<v-alert type="success" v-if="done" class="mb-4">
The magic spell has been applied successfully. Now you can close this
tab and back to the Solar Network!
</v-alert>
<v-alert
type="error"
v-else-if="!!error"
title="Something went wrong"
class="mb-4"
>{{ error }}</v-alert
>
<div v-else-if="!!spell">
<p class="mb-2">
Magic spell for {{ spellTypes[spell.type] ?? "unknown" }}
</p>
<div class="d-flex align-center gap-2 mb-2">
<v-icon size="18">mdi-account-circle</v-icon>
<strong>@{{ spell.account.name }}</strong>
</div>
<div class="d-flex align-center gap-2 mb-2">
<v-icon size="18">mdi-play</v-icon>
<span>Available at</span>
<strong>{{
new Date(spell.createdAt ?? spell.affectedAt).toLocaleString()
}}</strong>
</div>
<div class="d-flex align-center gap-2 mb-4" v-if="spell.expiredAt">
<v-icon size="18">mdi-calendar</v-icon>
<span>Until</span>
<strong>{{ spell.expiredAt.toString() }}</strong>
</div>
<div class="mt-4">
<v-text-field
v-if="spell.type == 3"
v-model="newPassword"
label="New password"
type="password"
density="comfortable"
></v-text-field>
<v-btn color="primary" :loading="submitting" @click="applySpell">
<v-icon left>mdi-check</v-icon>
Apply
</v-btn>
</div>
</div>
<v-progress-circular
v-else
indeterminate
size="32"
class="mt-4"
></v-progress-circular>
</v-card-text>
</v-card>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue"
import { useRoute } from "vue-router"
const route = useRoute()
const spellWord: string =
typeof route.params.word === "string"
? route.params.word
: route.params.word?.join("/") || ""
const spell = ref<any>(null)
const error = ref<string | null>(null)
const newPassword = ref<string>()
const submitting = ref(false)
const done = ref(false)
const spellTypes = [
"Account Activation",
"Account Deactivation",
"Account Deletion",
"Reset Password",
"Contact Method Verification"
]
const api = useSolarNetwork()
async function fetchSpell() {
try {
const resp = await api(`/id/spells/${encodeURIComponent(spellWord)}`)
spell.value = resp
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : String(err)
}
}
async function applySpell() {
submitting.value = true
try {
await api(`/id/spells/${encodeURIComponent(spellWord)}/apply`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: newPassword.value
? JSON.stringify({ new_password: newPassword.value })
: null
})
done.value = true
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : String(err)
}
}
onMounted(() => fetchSpell())
</script>

View File

@@ -0,0 +1,93 @@
<template>
<div id="swagger-ui"></div>
</template>
<script lang="ts" setup>
// @ts-ignore
import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist"
import "swagger-ui-dist/swagger-ui.css"
const colorMode = useColorMode()
onMounted(() => {
// Load theme once on page load
loadTheme(colorMode.value)
// Reactively switch if user toggles mode
watch(colorMode, (newVal) => {
loadTheme(newVal.value)
})
})
function loadTheme(mode: string) {
if (mode === "dark") {
import("swagger-themes/themes/one-dark.css")
} else {
import("swagger-themes/themes/material.css")
}
}
const apiBase = useSolarNetworkUrl(true)
onMounted(() => {
const ui = SwaggerUIBundle({
urls: [
{
url: `${apiBase}/swagger/ring/v1/swagger.json`,
name: "DysonNetwork.Ring"
},
{
url: `${apiBase}/swagger/pass/v1/swagger.json`,
name: "DysonNetwork.Pass"
},
{
url: `${apiBase}/swagger/sphere/v1/swagger.json`,
name: "DysonNetwork.Sphere"
},
{
url: `${apiBase}/swagger/drive/v1/swagger.json`,
name: "DysonNetwork.Drive"
},
{
url: `${apiBase}/swagger/develop/v1/swagger.json`,
name: "DysonNetwork.Develop"
}
],
dom_id: "#swagger-ui",
deepLinking: true,
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
layout: "StandaloneLayout"
})
// @ts-ignore
window.ui = ui
})
definePageMeta({
layout: "minimal"
})
useHead({
title: "Solar Network API"
})
</script>
<style>
@import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap");
.swagger-ui *:not(:is(pre, pre *, textarea, textarea *)) {
font-family: var(--font-family) !important;
}
.swagger-ui pre,
.swagger-ui pre *,
.swagger-ui textarea,
.swagger-ui textarea * {
font-family: "IBM Plex Mono", monospace !important;
}
@media (prefers-color-scheme: dark) {
.swagger-ui {
--secondary-text-color: #ffffff !important;
}
}
</style>

24
app/plugins/01.auth.ts Normal file
View File

@@ -0,0 +1,24 @@
import { useUserStore } from '~/stores/user'
export default defineNuxtPlugin(() => {
const side = process.server ? 'SERVER' : 'CLIENT'
console.log(`[AUTH PLUGIN] Running on ${side}`)
const userStore = useUserStore()
// Prevent fetching if it's already in progress
if (userStore.isLoading) {
console.log(`[AUTH PLUGIN] User fetch already in progress on ${side}. Skipping.`)
return
}
// On initial app load, fetch the user if a token exists but the user object isn't populated.
if (userStore.token && !userStore.user) {
console.log(`[AUTH PLUGIN] Token found, user not loaded. Fetching user on ${side}.`)
userStore.fetchUser()
} else {
console.log(`[AUTH PLUGIN] Conditions not met for fetching user on ${side}.`, {
hasToken: !!userStore.token,
hasUser: !!userStore.user
})
}
})

View File

@@ -11,7 +11,7 @@ export const useUserStore = defineStore("user", () => {
const error = ref<string | null>(null) const error = ref<string | null>(null)
// The name is match with the remote one (set by server Set-Cookie) // The name is match with the remote one (set by server Set-Cookie)
const token = useCookie<string | null>("AuthToken", { const token = useCookie<string | null>("fl_AuthToken", {
default: () => null, default: () => null,
path: "/", path: "/",
maxAge: 60 * 60 * 24 * 365 * 10 maxAge: 60 * 60 * 24 * 365 * 10
@@ -20,9 +20,6 @@ export const useUserStore = defineStore("user", () => {
// Getters // Getters
const isAuthenticated = computed(() => !!user.value && !!token.value) const isAuthenticated = computed(() => !!user.value && !!token.value)
// Call fetchUser immediately
fetchUser()
// Actions // Actions
async function fetchUser(reload = true) { async function fetchUser(reload = true) {
if (!reload && user.value) return // Skip fetching if already loaded and not forced to if (!reload && user.value) return // Skip fetching if already loaded and not forced to

View File

@@ -60,7 +60,7 @@ export interface SnPost {
awardedScore: number; awardedScore: number;
reactionsCount: Record<string, number>; reactionsCount: Record<string, number>;
repliesCount: number; repliesCount: number;
reactionsMade: Record<string, unknown>; reactionsMade: Record<string, boolean>;
repliedGone: boolean; repliedGone: boolean;
forwardedGone: boolean; forwardedGone: boolean;
repliedPostId: string | null; repliedPostId: string | null;

18
app/types/marked-katex.d.ts vendored Normal file
View File

@@ -0,0 +1,18 @@
declare module 'marked-katex' {
interface Options {
throwOnError?: boolean
errorColor?: string
displayMode?: boolean
leqno?: boolean
fleqn?: boolean
macros?: Record<string, string>
colorIsTextColor?: boolean
strict?: boolean | 'ignore' | 'warn' | 'error'
trust?: boolean | ((context: { command: string; url: string; protocol: string }) => boolean)
output?: 'html' | 'mathml' | 'htmlAndMathml'
}
function markedKatex(options?: Options): any
export default markedKatex
}

2629
bun.lock

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,9 @@
// @ts-check // @ts-check
import withNuxt from "./.nuxt/eslint.config.mjs" import withNuxt from "./.nuxt/eslint.config.mjs"
import tailwind from "eslint-plugin-tailwindcss"
export default withNuxt( export default withNuxt(
// Your custom configs here // Your custom configs here
{ {
...tailwind.configs["flat/recommended"],
rules: { rules: {
"vue/multi-word-component-names": "off", "vue/multi-word-component-names": "off",
"vue/no-v-html": "off", "vue/no-v-html": "off",

View File

@@ -13,11 +13,12 @@ export default defineNuxtConfig({
"@nuxtjs/color-mode", "@nuxtjs/color-mode",
"nuxt-og-image" "nuxt-og-image"
], ],
css: ["~/assets/css/main.css"], css: ["~/assets/css/main.css", "katex/dist/katex.min.css"],
app: { app: {
pageTransition: { name: "page", mode: "out-in" }, pageTransition: { name: "page", mode: "out-in" },
head: { head: {
titleTemplate: "%s - Solar Network" titleTemplate: "%s - Solar Network",
link: [{ rel: "icon", type: "image/png", href: "/favicon.png" }]
} }
}, },
site: { site: {
@@ -59,11 +60,6 @@ export default defineNuxtConfig({
plugins: [tailwindcss()] plugins: [tailwindcss()]
}, },
nitro: { nitro: {
routeRules: {
"/.well-known/**": {
proxy: process.env.NUXT_PUBLIC_API_BASE || "https://api.solian.app"
}
},
devProxy: { devProxy: {
"/api": { "/api": {
target: process.env.NUXT_PUBLIC_API_BASE || "https://api.solian.app", target: process.env.NUXT_PUBLIC_API_BASE || "https://api.solian.app",

12606
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -24,15 +24,27 @@
"@vueuse/core": "^13.9.0", "@vueuse/core": "^13.9.0",
"blurhash": "^2.0.5", "blurhash": "^2.0.5",
"cfturnstile-vue3": "^2.0.0", "cfturnstile-vue3": "^2.0.0",
"eslint": "^9.0.0", "eslint": "^9.36.0",
"katex": "^0.16.22",
"luxon": "^3.7.2", "luxon": "^3.7.2",
"marked": "^16.3.0",
"nuxt": "^4.1.2", "nuxt": "^4.1.2",
"nuxt-og-image": "^5.1.11", "nuxt-og-image": "^5.1.11",
"pinia": "^3.0.3", "pinia": "^3.0.3",
"rehype-katex": "^7.0.1",
"rehype-stringify": "^10.0.1",
"remark": "^15.0.1",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
"remark-html": "^16.0.1",
"remark-math": "^6.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"sharp": "^0.34.4", "sharp": "^0.34.4",
"swagger-themes": "^1.4.3",
"swagger-ui-dist": "^5.29.0",
"tailwindcss": "^4.1.13", "tailwindcss": "^4.1.13",
"tus-js-client": "^4.3.1", "tus-js-client": "^4.3.1",
"unified": "^11.0.5",
"vue": "^3.5.21", "vue": "^3.5.21",
"vue-router": "^4.5.1", "vue-router": "^4.5.1",
"vuetify-nuxt-module": "0.18.7" "vuetify-nuxt-module": "0.18.7"
@@ -40,7 +52,6 @@
"devDependencies": { "devDependencies": {
"@mdi/font": "^7.4.47", "@mdi/font": "^7.4.47",
"@types/luxon": "^3.7.1", "@types/luxon": "^3.7.1",
"@types/node": "^24.5.2", "@types/node": "^24.5.2"
"eslint-plugin-tailwindcss": "^4.0.0-beta.0"
} }
} }

BIN
public/favicon.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB