upload images to games

This commit is contained in:
DecDuck
2024-10-12 12:09:14 +11:00
parent 27070b6a4c
commit 9b7ee4e746
11 changed files with 348 additions and 12 deletions

19
components/GamePanel.vue Normal file
View File

@ -0,0 +1,19 @@
<template>
<NuxtLink v-if="game" :href="`/store/${game.id}`" class="rounded overflow-hidden w-48 h-64 group relative transition-all duration-300 hover:scale-105 hover:shadow-xl">
<img :src="useObject(game.mCoverId)" class="w-full h-full object-cover" />
<div class="absolute inset-0 bg-gradient-to-b from-transparent to-90% to-zinc-800"/>
<div class="absolute bottom-0 left-0 px-2 py-1.5">
<h1 class="text-zinc-100 text-sm font-bold font-display">{{ game.mName }}</h1>
<p class="text-zinc-400 text-xs">{{ game.mShortDescription.split(" ").slice(0, 10).join(" ") }}...</p>
</div>
</NuxtLink>
<div v-else class="rounded w-48 h-64 bg-zinc-800 flex items-center justify-center">
<p class="text-zinc-700 text-sm font-semibold font-display uppercase">no game</p>
</div>
</template>
<script setup lang="ts">
import type { SerializeObject } from "nitropack";
const props = defineProps<{ game?: SerializeObject<{ id: string, mCoverId: string, mName: string, mShortDescription: string }> }>();
</script>

View File

@ -0,0 +1,169 @@
<template>
<TransitionRoot as="template" :show="open">
<Dialog class="relative z-50" @close="open = false">
<TransitionChild
as="template"
enter="ease-out duration-300"
enter-from="opacity-0"
enter-to="opacity-100"
leave="ease-in duration-200"
leave-from="opacity-100"
leave-to="opacity-0"
>
<div
class="fixed inset-0 bg-zinc-950 bg-opacity-75 transition-opacity"
/>
</TransitionChild>
<div class="fixed inset-0 z-10 w-screen overflow-y-auto">
<div
class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0"
>
<TransitionChild
as="template"
enter="ease-out duration-300"
enter-from="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enter-to="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leave-from="opacity-100 translate-y-0 sm:scale-100"
leave-to="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
<DialogPanel
class="relative transform overflow-hidden rounded-lg bg-zinc-900 px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6"
>
<div class="sm:flex sm:items-start">
<div
class="mt-3 w-full text-center sm:ml-4 sm:mt-0 sm:text-left"
>
<div class="mt-2">
<label
for="file-upload"
class="cursor-pointer transition relative block w-full rounded-lg border-2 border-dashed border-zinc-800 p-12 text-center hover:border-zinc-700 focus:outline-none focus:ring-2 focus:ring-blue-600 focus:ring-offset-2"
>
<ArrowUpTrayIcon
class="mx-auto h-6 w-6 text-zinc-700"
stroke="currentColor"
fill="none"
viewBox="0 0 48 48"
aria-hidden="true"
/>
<span
class="mt-2 block text-sm font-semibold text-zinc-100"
>Upload file</span
>
<p class="mt-1 text-xs text-zinc-400" v-if="currentFile">
{{ currentFile.name }}
</p>
</label>
<input
:accept="props.accept"
@change="(e) => file = (e.target as any)?.files"
class="hidden"
type="file"
id="file-upload"
/>
</div>
</div>
</div>
<div class="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
<LoadingButton
:disabled="currentFile == undefined"
type="button"
:loading="uploadLoading"
@click="() => uploadFile_wrapper()"
:class="[
'inline-flex w-full shadow-sm sm:ml-3 sm:w-auto',
currentFile === undefined
? 'text-zinc-400 bg-blue-600/10 hover:bg-blue-600/10'
: 'text-white bg-blue-600 hover:bg-blue-500',
]"
>
Upload
</LoadingButton>
<button
type="button"
class="mt-3 inline-flex w-full justify-center rounded-md bg-zinc-800 px-3 py-2 text-sm font-semibold text-zinc-100 shadow-sm ring-1 ring-inset ring-zinc-800 hover:bg-zinc-900 sm:mt-0 sm:w-auto"
@click="open = false"
ref="cancelButtonRef"
>
Cancel
</button>
</div>
<div v-if="uploadError" class="mt-3 rounded-md bg-red-600/10 p-4">
<div class="flex">
<div class="flex-shrink-0">
<XCircleIcon
class="h-5 w-5 text-red-600"
aria-hidden="true"
/>
</div>
<div class="ml-3">
<h3 class="text-sm font-medium text-red-600">
{{ uploadError }}
</h3>
</div>
</div>
</div>
</DialogPanel>
</TransitionChild>
</div>
</div>
</Dialog>
</TransitionRoot>
</template>
<script setup lang="ts">
import { ref } from "vue";
import {
Dialog,
DialogPanel,
DialogTitle,
TransitionChild,
TransitionRoot,
} from "@headlessui/vue";
import { ExclamationTriangleIcon } from "@heroicons/vue/24/outline";
import { ArrowUpTrayIcon } from "@heroicons/vue/20/solid";
const open = defineModel<boolean>();
const file = ref<FileList | undefined>();
const currentFile = computed(() => file.value?.item(0));
const props = defineProps<{
endpoint: string;
accept: string;
options?: { [key: string]: string };
}>();
const emit = defineEmits(["upload"]);
const uploadLoading = ref(false);
const uploadError = ref<string | undefined>();
async function uploadFile() {
if (!currentFile.value) return;
const form = new FormData();
form.append("file", currentFile.value);
if (props.options) {
for (const [key, value] of Object.entries(props.options)) {
form.append(key, value);
}
}
console.log(props.endpoint);
const result = await $fetch(props.endpoint, { method: "POST", body: form });
open.value = false;
file.value = undefined;
emit("upload", result);
}
function uploadFile_wrapper() {
uploadLoading.value = true;
uploadFile()
.catch((error) => {
uploadError.value = error.statusMessage ?? "An unknown error occurred.";
})
.finally(() => {
uploadLoading.value = false;
});
}
</script>

View File

@ -39,6 +39,7 @@
"@types/turndown": "^5.0.5",
"@types/uuid": "^10.0.0",
"autoprefixer": "^10.4.20",
"h3": "^1.13.0",
"nitropack": "^2.9.7",
"postcss": "^8.4.47",
"sass": "^1.79.4",

View File

@ -26,6 +26,7 @@
</div>
<div class="ml-4 mt-2 flex-shrink-0">
<button
@click="() => (showUploadModal = true)"
type="button"
class="relative inline-flex items-center rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600"
>
@ -91,16 +92,26 @@
</div>
</div>
</div>
<UploadFileDialog
v-model="showUploadModal"
:options="{ id: game.id }"
accept="image/*"
endpoint="/api/v1/admin/game/image"
@upload="(result) => uploadAfterImageUpload(result)"
/>
</template>
<script setup lang="ts">
import type { Game } from "@prisma/client";
import markdownit from "markdown-it";
import UploadFileDialog from "~/components/UploadFileDialog.vue";
definePageMeta({
layout: "admin",
});
const showUploadModal = ref(false);
const route = useRoute();
const gameId = route.params.id.toString();
const headers = useRequestHeaders(["cookie"]);
@ -151,4 +162,9 @@ async function deleteImage(id: string) {
game.value.mImageLibrary = mImageLibrary;
game.value.mBannerId = mBannerId;
}
async function uploadAfterImageUpload(result: Game) {
if (!game.value) return;
game.value.mImageLibrary = result.mImageLibrary;
}
</script>

View File

@ -1,5 +1,13 @@
<template>
{{ games }}
<div class="px-12 py-4">
<h1 class="text-zinc-100 text-2xl font-bold font-display">
Newly added
</h1>
<NuxtLink class="text-blue-600 font-semibold">Explore more &rarr;</NuxtLink>
<div class="mt-4 grid grid-cols-8 gap-8">
<GamePanel v-for="i in 8" :game="games[i - 1]" />
</div>
</div>
</template>
<script setup lang="ts">

View File

@ -28,7 +28,13 @@ export default defineEventHandler(async (h3) => {
if (!game)
throw createError({ statusCode: 400, statusMessage: "Invalid game ID" });
game.mImageLibrary = game.mImageLibrary.filter((e) => e != imageId);
const imageIndex = game.mImageLibrary.findIndex((e) => e == imageId);
if (imageIndex == -1)
throw createError({ statusCode: 400, statusMessage: "Image not found" });
game.mImageLibrary.splice(imageIndex, 1);
await h3.context.objects.delete(imageId);
if (game.mBannerId === imageId) {
game.mBannerId = game.mImageLibrary[0];
}

View File

@ -0,0 +1,57 @@
import prisma from "~/server/internal/db/database";
import { handleFileUpload } from "~/server/internal/utils/handlefileupload";
export default defineEventHandler(async (h3) => {
const user = await h3.context.session.getAdminUser(h3);
if (!user) throw createError({ statusCode: 403 });
const form = await readMultipartFormData(h3);
if (!form)
throw createError({
statusCode: 400,
statusMessage: "This endpoint requires multipart form data.",
});
const uploadResult = await handleFileUpload(h3, {}, ["internal:read"]);
if (!uploadResult)
throw createError({
statusCode: 400,
statusMessage: "Failed to upload file",
});
const [id, options, pull, dump] = uploadResult;
if (!id) {
dump();
throw createError({
statusCode: 400,
statusMessage: "Did not upload a file",
});
}
const gameId = options.id;
if (!gameId)
throw createError({
statusCode: 400,
statusMessage: "No game ID attached",
});
const hasGame = (await prisma.game.count({ where: { id: gameId } })) != 0;
if (!hasGame) {
dump();
throw createError({ statusCode: 400, statusMessage: "Invalid game ID" });
}
const result = await prisma.game.update({
where: {
id: gameId,
},
data: {
mImageLibrary: {
push: id,
},
},
});
await pull();
return result;
});

View File

@ -9,7 +9,7 @@ export default defineEventHandler(async (h3) => {
id: true,
mName: true,
mShortDescription: true,
mBannerId: true,
mCoverId:true,
mDevelopers: {
select: {
id: true,

View File

@ -6,12 +6,13 @@ import { Readable } from "stream";
import { v4 as uuidv4 } from "uuid";
import { GlobalObjectHandler } from "~/server/plugins/objects";
type TransactionTable = { [key: string]: string }; // ID to URL
type TransactionDataType = string | Readable | Buffer;
type TransactionTable = { [key: string]: TransactionDataType }; // ID to data
type GlobalTransactionRecord = { [key: string]: TransactionTable }; // Transaction ID to table
type Register = (url: string) => string;
type Pull = () => Promise<void>;
type Dump = () => void;
export type Register = (url: TransactionDataType) => string;
export type Pull = () => Promise<void>;
export type Dump = () => void;
export class ObjectTransactionalHandler {
private record: GlobalTransactionRecord = {};
@ -24,18 +25,23 @@ export class ObjectTransactionalHandler {
this.record[transactionId] ??= {};
const register = (url: string) => {
const register = (data: TransactionDataType) => {
const objectId = uuidv4();
this.record[transactionId][objectId] = url;
this.record[transactionId][objectId] = data;
return objectId;
};
const pull = async () => {
for (const [id, url] of Object.entries(this.record[transactionId])) {
for (const [id, data] of Object.entries(this.record[transactionId])) {
await GlobalObjectHandler.createFromSource(
id,
() => $fetch<Readable>(url, { responseType: "stream" }),
() => {
if (typeof data === "string") {
return $fetch<Readable>(data, { responseType: "stream" });
}
return (async () => data)();
},
metadata,
permissions
);

View File

@ -0,0 +1,31 @@
import { EventHandlerRequest, H3Event } from "h3";
import { Dump, ObjectTransactionalHandler, Pull } from "../objects/transactional";
export async function handleFileUpload(
h3: H3Event<EventHandlerRequest>,
metadata: { [key: string]: string },
permissions: Array<string>
): Promise<[string | undefined, {[key: string]: string}, Pull, Dump] | undefined> {
const formData = await readMultipartFormData(h3);
if (!formData) return undefined;
const transactionalHandler = new ObjectTransactionalHandler();
const [add, pull, dump] = transactionalHandler.new(metadata, permissions);
const options: { [key: string]: string } = {};
let id;
for (const entry of formData) {
if (entry.filename) {
// Only pick one file
if (id) continue;
// Add file to transaction handler so we can void it later if we error out
id = add(entry.data);
continue;
}
if (!entry.name) continue;
options[entry.name] = entry.data.toString("utf-8");
}
return [id, options, pull, dump];
}

View File

@ -2232,6 +2232,13 @@ cross-spawn@^7.0.0, cross-spawn@^7.0.3:
shebang-command "^2.0.0"
which "^2.0.1"
"crossws@>=0.2.0 <0.4.0":
version "0.3.1"
resolved "https://registry.yarnpkg.com/crossws/-/crossws-0.3.1.tgz#7980e0b6688fe23286661c3ab8deeccbaa05ca86"
integrity sha512-HsZgeVYaG+b5zA+9PbIPGq4+J/CJynJuearykPsXx4V/eMhyQ5EDVg3Ak2FBZtVXCiOLu/U7IiwDHTr9MA+IKw==
dependencies:
uncrypto "^0.1.3"
crossws@^0.2.4:
version "0.2.4"
resolved "https://registry.yarnpkg.com/crossws/-/crossws-0.2.4.tgz#82a8b518bff1018ab1d21ced9e35ffbe1681ad03"
@ -3049,6 +3056,22 @@ h3@^1.12.0:
uncrypto "^0.1.3"
unenv "^1.9.0"
h3@^1.13.0:
version "1.13.0"
resolved "https://registry.yarnpkg.com/h3/-/h3-1.13.0.tgz#b5347a8936529794b6754b440e26c0ab8a60dceb"
integrity sha512-vFEAu/yf8UMUcB4s43OaDaigcqpQd14yanmOsn+NcRX3/guSKncyE2rOYhq8RIchgJrPSs/QiIddnTTR1ddiAg==
dependencies:
cookie-es "^1.2.2"
crossws ">=0.2.0 <0.4.0"
defu "^6.1.4"
destr "^2.0.3"
iron-webcrypto "^1.2.1"
ohash "^1.1.4"
radix3 "^1.1.2"
ufo "^1.5.4"
uncrypto "^0.1.3"
unenv "^1.10.0"
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
@ -3194,7 +3217,7 @@ ioredis@^5.4.1:
redis-parser "^3.0.0"
standard-as-callback "^2.1.0"
iron-webcrypto@^1.1.1:
iron-webcrypto@^1.1.1, iron-webcrypto@^1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz#aa60ff2aa10550630f4c0b11fd2442becdb35a6f"
integrity sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==