add cropper for vrc plus management

This commit is contained in:
pa
2026-02-28 22:04:54 +09:00
parent cc696701b5
commit 7a8e8e4a73
11 changed files with 727 additions and 1075 deletions

View File

@@ -529,9 +529,19 @@
<template v-if="avatarDialog.visible">
<SetAvatarTagsDialog v-model:setAvatarTagsDialog="setAvatarTagsDialog" />
<SetAvatarStylesDialog v-model:setAvatarStylesDialog="setAvatarStylesDialog" />
<ChangeAvatarImageDialog
v-model:changeAvatarImageDialogVisible="changeAvatarImageDialogVisible"
v-model:previousImageUrl="previousImageUrl" />
<input
id="AvatarImageUploadButton"
type="file"
accept="image/*"
style="display: none"
@change="onFileChangeAvatarImage" />
<ImageCropDialog
:open="cropDialogOpen"
:title="t('dialog.change_content_image.avatar')"
:aspect-ratio="4 / 3"
:file="cropDialogFile"
@update:open="cropDialogOpen = $event"
@confirm="onCropConfirmAvatar" />
</template>
</div>
</div>
@@ -597,14 +607,20 @@
DropdownMenuSeparator,
DropdownMenuTrigger
} from '../../ui/dropdown-menu';
import {
handleImageUploadInput,
readFileAsBase64,
resizeImageToFitLimits,
uploadImageLegacy,
withUploadTimeout
} from '../../../shared/utils/imageUpload';
import { avatarModerationRequest, avatarRequest, favoriteRequest } from '../../../api';
import { AppDebug } from '../../../service/appConfig.js';
import { Badge } from '../../ui/badge';
import { database } from '../../../service/database';
import { formatJsonVars } from '../../../shared/utils/base/ui';
import { handleImageUploadInput } from '../../../shared/utils/imageUpload';
const ChangeAvatarImageDialog = defineAsyncComponent(() => import('./ChangeAvatarImageDialog.vue'));
import ImageCropDialog from '../ImageCropDialog.vue';
const SetAvatarStylesDialog = defineAsyncComponent(() => import('./SetAvatarStylesDialog.vue'));
const SetAvatarTagsDialog = defineAsyncComponent(() => import('./SetAvatarTagsDialog.vue'));
@@ -628,8 +644,9 @@
{ value: 'JSON', label: t('dialog.avatar.json.header') }
]);
const changeAvatarImageDialogVisible = ref(false);
const previousImageUrl = ref('');
const cropDialogOpen = ref(false);
const cropDialogFile = ref(null);
const changeAvatarImageLoading = ref(false);
const treeData = ref({});
const memo = ref('');
@@ -971,9 +988,63 @@
}
function showChangeAvatarImageDialog() {
const { imageUrl } = avatarDialog.value.ref;
previousImageUrl.value = imageUrl;
changeAvatarImageDialogVisible.value = true;
document.getElementById('AvatarImageUploadButton').click();
}
function onFileChangeAvatarImage(e) {
const { file, clearInput } = handleImageUploadInput(e, {
inputSelector: '#AvatarImageUploadButton',
tooLargeMessage: () => t('message.file.too_large'),
invalidTypeMessage: () => t('message.file.not_image')
});
if (!file) {
return;
}
if (!avatarDialog.value.visible || avatarDialog.value.loading) {
clearInput();
return;
}
clearInput();
cropDialogFile.value = file;
cropDialogOpen.value = true;
}
async function onCropConfirmAvatar(blob) {
changeAvatarImageLoading.value = true;
try {
await withUploadTimeout(
(async () => {
const base64Body = await readFileAsBase64(blob);
const base64File = await resizeImageToFitLimits(base64Body);
if (LINUX) {
const args = await avatarRequest.uploadAvatarImage(base64File);
const fileUrl = args.json.versions[args.json.versions.length - 1].file.url;
await avatarRequest.saveAvatar({
id: avatarDialog.value.id,
imageUrl: fileUrl
});
} else {
await uploadImageLegacy('avatar', {
entityId: avatarDialog.value.id,
imageUrl: avatarDialog.value.ref.imageUrl,
base64File,
blob
});
}
})()
);
toast.success(t('message.upload.success'));
// force refresh cover image
const avatarId = avatarDialog.value.id;
avatarDialog.value.id = '';
showAvatarDialog(avatarId);
} catch (error) {
console.error('avatar image upload process failed:', error);
toast.error(t('message.upload.error'));
} finally {
changeAvatarImageLoading.value = false;
cropDialogOpen.value = false;
}
}
function promptChangeAvatarDescription(avatar) {

View File

@@ -1,428 +0,0 @@
<template>
<Dialog
:open="changeAvatarImageDialogVisible"
@update:open="
(open) => {
if (!open) closeDialog();
}
">
<DialogContent class="x-dialog sm:max-w-212.5">
<DialogHeader>
<DialogTitle>{{ t('dialog.change_content_image.avatar') }}</DialogTitle>
</DialogHeader>
<div>
<input
id="AvatarImageUploadButton"
type="file"
accept="image/*"
style="display: none"
@change="onFileChangeAvatarImage" />
<Button
variant="outline"
size="sm"
:disabled="changeAvatarImageDialogLoading"
@click="uploadAvatarImage">
<Upload />
{{ t('dialog.change_content_image.upload') }}
</Button>
<div class="text-xs text-muted-foreground mb-4 mt-1 flex items-center gap-1">
<Info /> {{ t('dialog.change_content_image.description') }}
</div>
<div v-if="cropperImageSrc" class="mt-4">
<Cropper
ref="cropperRef"
class="h-100 max-h-full"
:src="cropperImageSrc"
:stencil-props="{ aspectRatio: 4 / 3 }"
image-restriction="stencil" />
</div>
<div v-else class="flex justify-center items-center">
<img :src="previousImageUrl" class="img-size" loading="lazy" />
</div>
</div>
<DialogFooter>
<template v-if="cropperImageSrc">
<Button
variant="secondary"
size="sm"
:disabled="changeAvatarImageDialogLoading"
@click="cancelCrop">
{{ t('dialog.change_content_image.cancel') }}
</Button>
<Button size="sm" :disabled="changeAvatarImageDialogLoading" @click="onConfirmCrop">
{{ t('dialog.change_content_image.confirm') }}
</Button>
</template>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
<script setup>
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Info, Upload } from 'lucide-vue-next';
import { Button } from '@/components/ui/button';
import { Cropper } from 'vue-advanced-cropper';
import { ref } from 'vue';
import { storeToRefs } from 'pinia';
import { toast } from 'vue-sonner';
import { useI18n } from 'vue-i18n';
import { avatarRequest, imageRequest } from '../../../api';
import { $throw } from '../../../service/request';
import { AppDebug } from '../../../service/appConfig';
import { extractFileId } from '../../../shared/utils';
import { handleImageUploadInput } from '../../../shared/utils/imageUpload';
import { useAvatarStore } from '../../../stores';
import 'vue-advanced-cropper/dist/style.css';
const { t } = useI18n();
const { avatarDialog } = storeToRefs(useAvatarStore());
const { applyAvatar } = useAvatarStore();
defineProps({
changeAvatarImageDialogVisible: {
type: Boolean,
required: true
},
previousImageUrl: {
type: String,
default: ''
}
});
const MAX_PREVIEW_SIZE = 800;
const changeAvatarImageDialogLoading = ref(false);
const cropperRef = ref(null);
const cropperImageSrc = ref('');
const selectedFile = ref(null);
const originalImage = ref(null);
const previewScale = ref(1);
const avatarImage = ref({
base64File: '',
fileMd5: '',
base64SignatureFile: '',
signatureMd5: '',
fileId: '',
avatarId: ''
});
const emit = defineEmits(['update:changeAvatarImageDialogVisible', 'update:previousImageUrl']);
function resetCropState() {
cropperImageSrc.value = '';
selectedFile.value = null;
originalImage.value = null;
previewScale.value = 1;
}
function closeDialog() {
resetCropState();
emit('update:changeAvatarImageDialogVisible', false);
}
async function resizeImageToFitLimits(file) {
const response = await AppApi.ResizeImageToFitLimits(file);
return response;
}
function onFileChangeAvatarImage(e) {
const { file, clearInput } = handleImageUploadInput(e, {
inputSelector: '#AvatarImageUploadButton',
tooLargeMessage: () => t('message.file.too_large'),
invalidTypeMessage: () => t('message.file.not_image')
});
if (!file) {
return;
}
if (!avatarDialog.value.visible || avatarDialog.value.loading) {
clearInput();
return;
}
selectedFile.value = file;
const r = new FileReader();
r.onload = () => {
const img = new Image();
img.onload = () => {
originalImage.value = img;
if (img.width > MAX_PREVIEW_SIZE || img.height > MAX_PREVIEW_SIZE) {
const scale = Math.min(MAX_PREVIEW_SIZE / img.width, MAX_PREVIEW_SIZE / img.height);
previewScale.value = scale;
const cvs = document.createElement('canvas');
cvs.width = Math.round(img.width * scale);
cvs.height = Math.round(img.height * scale);
const ctx = cvs.getContext('2d');
ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
cropperImageSrc.value = cvs.toDataURL('image/jpeg', 0.9);
} else {
previewScale.value = 1;
cropperImageSrc.value = r.result;
}
};
img.onerror = () => {
resetCropState();
};
img.src = r.result;
};
r.onerror = () => {
resetCropState();
toast.error(t('message.file.not_image'));
};
r.readAsDataURL(file);
clearInput();
}
function cancelCrop() {
resetCropState();
}
function onConfirmCrop() {
const { coordinates } = cropperRef.value.getResult();
if (!coordinates || !originalImage.value) {
return;
}
// Scale coordinates back
const scale = previewScale.value;
const srcX = Math.round(coordinates.left / scale);
const srcY = Math.round(coordinates.top / scale);
const srcW = Math.round(coordinates.width / scale);
const srcH = Math.round(coordinates.height / scale);
const cropCanvas = document.createElement('canvas');
cropCanvas.width = srcW;
cropCanvas.height = srcH;
const ctx = cropCanvas.getContext('2d');
ctx.drawImage(originalImage.value, srcX, srcY, srcW, srcH, 0, 0, srcW, srcH);
cropCanvas.toBlob((blob) => {
const r = new FileReader();
const finalize = () => {
changeAvatarImageDialogLoading.value = false;
resetCropState();
};
r.onerror = finalize;
r.onabort = finalize;
r.onload = async function () {
const uploadPromise = (async () => {
const bytes = new Uint8Array(r.result);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64File = await resizeImageToFitLimits(btoa(binary));
// 10MB
if (LINUX) {
// use new website upload process on Linux, we're missing the needed libraries for Unity method
// website method clears avatar name and is missing world image uploading
await initiateUpload(base64File);
return;
}
await initiateUploadLegacy(base64File, blob);
})();
toast.promise(uploadPromise, {
loading: t('message.upload.loading'),
success: t('message.upload.success'),
error: t('message.upload.error')
});
try {
await uploadPromise;
} catch (error) {
console.error('avatar image upload process failed:', error);
} finally {
finalize();
}
};
changeAvatarImageDialogLoading.value = true;
try {
r.readAsArrayBuffer(blob);
} catch (error) {
console.error('Failed to read cropped image', error);
finalize();
}
}, 'image/png');
}
async function initiateUploadLegacy(base64File, file) {
const fileMd5 = await AppApi.MD5File(base64File);
const fileSizeInBytes = parseInt(file.size, 10);
const base64SignatureFile = await AppApi.SignFile(base64File);
const signatureMd5 = await AppApi.MD5File(base64SignatureFile);
const signatureSizeInBytes = parseInt(await AppApi.FileLength(base64SignatureFile), 10);
const avatarId = avatarDialog.value.id;
const { imageUrl } = avatarDialog.value.ref;
const fileId = extractFileId(imageUrl);
avatarImage.value = {
base64File,
fileMd5,
base64SignatureFile,
signatureMd5,
fileId,
avatarId
};
const params = {
fileMd5,
fileSizeInBytes,
signatureMd5,
signatureSizeInBytes
};
const res = await imageRequest.uploadAvatarImage(params, fileId);
return avatarImageInit(res);
}
async function avatarImageInit(args) {
const fileId = args.json.id;
const fileVersion = args.json.versions[args.json.versions.length - 1].version;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadAvatarImageFileStart(params);
return avatarImageFileStart(res);
}
async function avatarImageFileStart(args) {
const { url } = args.json;
const { fileId, fileVersion } = args.params;
const params = {
url,
fileId,
fileVersion
};
return uploadAvatarImageFileAWS(params);
}
async function uploadAvatarImageFileAWS(params) {
const json = await webApiService.execute({
url: params.url,
uploadFilePUT: true,
fileData: avatarImage.value.base64File,
fileMIME: 'image/png',
fileMD5: avatarImage.value.fileMd5
});
if (json.status !== 200) {
changeAvatarImageDialogLoading.value = false;
$throw(json.status, 'avatar image upload failed', params.url);
}
const args = {
json,
params
};
return avatarImageFileAWS(args);
}
async function avatarImageFileAWS(args) {
const { fileId, fileVersion } = args.params;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadAvatarImageFileFinish(params);
return avatarImageFileFinish(res);
}
async function avatarImageFileFinish(args) {
const { fileId, fileVersion } = args.params;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadAvatarImageSigStart(params);
return avatarImageSigStart(res);
}
async function avatarImageSigStart(args) {
const { url } = args.json;
const { fileId, fileVersion } = args.params;
const params = {
url,
fileId,
fileVersion
};
return uploadAvatarImageSigAWS(params);
}
async function uploadAvatarImageSigAWS(params) {
const json = await webApiService.execute({
url: params.url,
uploadFilePUT: true,
fileData: avatarImage.value.base64SignatureFile,
fileMIME: 'application/x-rsync-signature',
fileMD5: avatarImage.value.signatureMd5
});
if (json.status !== 200) {
changeAvatarImageDialogLoading.value = false;
$throw(json.status, 'avatar image upload failed', params.url);
}
const args = {
json,
params
};
return avatarImageSigAWS(args);
}
async function avatarImageSigAWS(args) {
const { fileId, fileVersion } = args.params;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadAvatarImageSigFinish(params);
return avatarImageSigFinish(res);
}
async function avatarImageSigFinish(args) {
const { fileId, fileVersion } = args.params;
const params = {
id: avatarImage.value.avatarId,
imageUrl: `${AppDebug.endpointDomain}/file/${fileId}/${fileVersion}/file`
};
const res = await imageRequest.setAvatarImage(params);
return avatarImageSet(res);
}
function avatarImageSet(args) {
changeAvatarImageDialogLoading.value = false;
if (args.json.imageUrl === args.params.imageUrl) {
emit('update:previousImageUrl', args.json.imageUrl);
} else {
$throw(0, 'avatar image change failed', args.params.imageUrl);
}
}
// ------------ Upload Process End ------------
async function initiateUpload(base64File) {
const args = await avatarRequest.uploadAvatarImage(base64File);
const fileUrl = args.json.versions[args.json.versions.length - 1].file.url;
const avatarArgs = await avatarRequest.saveAvatar({
id: avatarDialog.value.id,
imageUrl: fileUrl
});
const ref = applyAvatar(avatarArgs.json);
changeAvatarImageDialogLoading.value = false;
emit('update:previousImageUrl', ref.imageUrl);
// closeDialog();
}
function uploadAvatarImage() {
document.getElementById('AvatarImageUploadButton').click();
}
</script>
<style scoped>
.img-size {
width: 500px;
height: 375px;
}
</style>

View File

@@ -0,0 +1,116 @@
<template>
<Dialog
:open="open"
@update:open="
(v) => {
if (!v) cancelCrop();
}
">
<DialogContent class="x-dialog sm:max-w-212.5">
<DialogHeader>
<DialogTitle>{{ title }}</DialogTitle>
</DialogHeader>
<div v-if="cropperImageSrc" class="mt-4">
<Cropper
ref="cropperRef"
class="h-100 max-h-full"
:src="cropperImageSrc"
:stencil-props="{ aspectRatio, movable: !loading, resizable: !loading }"
:move-image="!loading"
:resize-image="!loading"
image-restriction="stencil" />
</div>
<DialogFooter>
<template v-if="cropperImageSrc">
<Button variant="secondary" size="sm" :disabled="loading" @click="cancelCrop">
{{ t('dialog.change_content_image.cancel') }}
</Button>
<Button size="sm" :disabled="loading" @click="onConfirmCrop">
<Spinner v-if="loading" />
{{ loading ? t('message.upload.loading') : t('dialog.gallery_icons.crop_image') }}
</Button>
</template>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
<script setup>
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { ref, watch } from 'vue';
import { Button } from '@/components/ui/button';
import { Cropper } from 'vue-advanced-cropper';
import { Spinner } from '@/components/ui/spinner';
import { useI18n } from 'vue-i18n';
import { useImageCropper } from '../../composables/useImageCropper';
import 'vue-advanced-cropper/dist/style.css';
const { t } = useI18n();
const props = defineProps({
open: {
type: Boolean,
required: true
},
title: {
type: String,
default: ''
},
aspectRatio: {
type: Number,
default: 4 / 3
},
file: {
type: [File, null],
default: null
}
});
const emit = defineEmits(['update:open', 'confirm']);
const loading = ref(false);
// Attention: cropperRef is used
const { cropperRef, cropperImageSrc, resetCropState, loadImageForCrop, getCroppedBlob } = useImageCropper();
watch(
() => props.file,
(file) => {
if (file) {
loadImageForCrop(file);
}
}
);
watch(
() => props.open,
(open) => {
if (!open) {
loading.value = false;
resetCropState();
}
}
);
function cancelCrop() {
resetCropState();
emit('update:open', false);
}
async function onConfirmCrop() {
loading.value = true;
try {
const blob = await getCroppedBlob(props.file);
if (!blob) {
loading.value = false;
return;
}
emit('confirm', blob);
} catch {
loading.value = false;
}
}
</script>

View File

@@ -1,415 +0,0 @@
<template>
<Dialog
:open="changeWorldImageDialogVisible"
@update:open="
(open) => {
if (!open) closeDialog();
}
">
<DialogContent class="x-dialog sm:max-w-212.5">
<DialogHeader>
<DialogTitle>{{ t('dialog.change_content_image.world') }}</DialogTitle>
</DialogHeader>
<div>
<input
id="WorldImageUploadButton"
type="file"
accept="image/*"
style="display: none"
@change="onFileChangeWorldImage" />
<Button variant="outline" size="sm" :disabled="changeWorldImageDialogLoading" @click="uploadWorldImage">
<Upload />
{{ t('dialog.change_content_image.upload') }}
</Button>
<div class="text-xs text-muted-foreground mb-4 mt-1 flex items-center gap-1">
<Info /> {{ t('dialog.change_content_image.description') }}
</div>
<div v-if="cropperImageSrc" class="mt-4">
<Cropper
ref="cropperRef"
class="h-100 max-h-full"
:src="cropperImageSrc"
:stencil-props="{ aspectRatio: 4 / 3 }"
image-restriction="stencil" />
</div>
<div v-else class="flex justify-center items-center">
<img :src="previousImageUrl" class="img-size" loading="lazy" />
</div>
</div>
<DialogFooter>
<template v-if="cropperImageSrc">
<Button variant="secondary" size="sm" :disabled="changeWorldImageDialogLoading" @click="cancelCrop">
{{ t('dialog.change_content_image.cancel') }}
</Button>
<Button size="sm" :disabled="changeWorldImageDialogLoading" @click="onConfirmCrop">
{{ t('dialog.change_content_image.confirm') }}
</Button>
</template>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
<script setup>
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Info, Upload } from 'lucide-vue-next';
import { Button } from '@/components/ui/button';
import { Cropper } from 'vue-advanced-cropper';
import { ref } from 'vue';
import { storeToRefs } from 'pinia';
import { toast } from 'vue-sonner';
import { useI18n } from 'vue-i18n';
import { imageRequest, worldRequest } from '../../../api';
import { $throw } from '../../../service/request';
import { AppDebug } from '../../../service/appConfig';
import { extractFileId } from '../../../shared/utils';
import { handleImageUploadInput } from '../../../shared/utils/imageUpload';
import { useWorldStore } from '../../../stores';
import 'vue-advanced-cropper/dist/style.css';
const { t } = useI18n();
const { worldDialog } = storeToRefs(useWorldStore());
const { applyWorld } = useWorldStore();
defineProps({
changeWorldImageDialogVisible: {
type: Boolean,
required: true
},
previousImageUrl: {
type: String,
default: ''
}
});
const MAX_PREVIEW_SIZE = 800;
const changeWorldImageDialogLoading = ref(false);
const cropperRef = ref(null);
const cropperImageSrc = ref('');
const selectedFile = ref(null);
const originalImage = ref(null);
const previewScale = ref(1);
const worldImage = ref({
base64File: '',
fileMd5: '',
base64SignatureFile: '',
signatureMd5: '',
fileId: '',
worldId: ''
});
const emit = defineEmits(['update:changeWorldImageDialogVisible', 'update:previousImageUrl']);
function resetCropState() {
cropperImageSrc.value = '';
selectedFile.value = null;
originalImage.value = null;
previewScale.value = 1;
}
function closeDialog() {
resetCropState();
emit('update:changeWorldImageDialogVisible', false);
}
async function resizeImageToFitLimits(file) {
const response = await AppApi.ResizeImageToFitLimits(file);
return response;
}
function onFileChangeWorldImage(e) {
const { file, clearInput } = handleImageUploadInput(e, {
inputSelector: '#WorldImageUploadButton',
tooLargeMessage: () => t('message.file.too_large'),
invalidTypeMessage: () => t('message.file.not_image')
});
if (!file) {
return;
}
if (!worldDialog.value.visible || worldDialog.value.loading) {
clearInput();
return;
}
selectedFile.value = file;
const r = new FileReader();
r.onload = () => {
const img = new Image();
img.onload = () => {
originalImage.value = img;
if (img.width > MAX_PREVIEW_SIZE || img.height > MAX_PREVIEW_SIZE) {
const scale = Math.min(MAX_PREVIEW_SIZE / img.width, MAX_PREVIEW_SIZE / img.height);
previewScale.value = scale;
const cvs = document.createElement('canvas');
cvs.width = Math.round(img.width * scale);
cvs.height = Math.round(img.height * scale);
const ctx = cvs.getContext('2d');
ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
cropperImageSrc.value = cvs.toDataURL('image/jpeg', 0.9);
} else {
previewScale.value = 1;
cropperImageSrc.value = r.result;
}
};
img.onerror = () => {
resetCropState();
};
img.src = r.result;
};
r.onerror = () => {
resetCropState();
toast.error(t('message.file.not_image'));
};
r.readAsDataURL(file);
clearInput();
}
function cancelCrop() {
resetCropState();
}
function onConfirmCrop() {
const { coordinates } = cropperRef.value.getResult();
if (!coordinates || !originalImage.value) {
return;
}
// scale back
const scale = previewScale.value;
const srcX = Math.round(coordinates.left / scale);
const srcY = Math.round(coordinates.top / scale);
const srcW = Math.round(coordinates.width / scale);
const srcH = Math.round(coordinates.height / scale);
const cropCanvas = document.createElement('canvas');
cropCanvas.width = srcW;
cropCanvas.height = srcH;
const ctx = cropCanvas.getContext('2d');
ctx.drawImage(originalImage.value, srcX, srcY, srcW, srcH, 0, 0, srcW, srcH);
cropCanvas.toBlob((blob) => {
const r = new FileReader();
const finalize = () => {
changeWorldImageDialogLoading.value = false;
resetCropState();
};
r.onerror = finalize;
r.onabort = finalize;
r.onload = async function () {
const uploadPromise = (async () => {
const bytes = new Uint8Array(r.result);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64File = await resizeImageToFitLimits(btoa(binary));
// 10MB
await initiateUploadLegacy(base64File, blob);
// await initiateUpload(base64File);
})();
toast.promise(uploadPromise, {
loading: t('message.upload.loading'),
success: t('message.upload.success'),
error: t('message.upload.error')
});
try {
await uploadPromise;
} catch (error) {
console.error('World image upload process failed:', error);
} finally {
finalize();
}
};
changeWorldImageDialogLoading.value = true;
try {
r.readAsArrayBuffer(blob);
} catch (error) {
console.error('Failed to read cropped image', error);
finalize();
}
}, 'image/png');
}
async function initiateUploadLegacy(base64File, file) {
const fileMd5 = await AppApi.MD5File(base64File);
const fileSizeInBytes = parseInt(file.size, 10);
const base64SignatureFile = await AppApi.SignFile(base64File);
const signatureMd5 = await AppApi.MD5File(base64SignatureFile);
const signatureSizeInBytes = parseInt(await AppApi.FileLength(base64SignatureFile), 10);
const worldId = worldDialog.value.id;
const { imageUrl } = worldDialog.value.ref;
const fileId = extractFileId(imageUrl);
worldImage.value = {
base64File,
fileMd5,
base64SignatureFile,
signatureMd5,
fileId,
worldId
};
const params = {
fileMd5,
fileSizeInBytes,
signatureMd5,
signatureSizeInBytes
};
const res = await imageRequest.uploadWorldImage(params, fileId);
return worldImageInit(res);
}
async function worldImageInit(args) {
const fileId = args.json.id;
const fileVersion = args.json.versions[args.json.versions.length - 1].version;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadWorldImageFileStart(params);
return worldImageFileStart(res);
}
async function worldImageFileStart(args) {
const { url } = args.json;
const { fileId, fileVersion } = args.params;
const params = {
url,
fileId,
fileVersion
};
return uploadWorldImageFileAWS(params);
}
async function uploadWorldImageFileAWS(params) {
const json = await webApiService.execute({
url: params.url,
uploadFilePUT: true,
fileData: worldImage.value.base64File,
fileMIME: 'image/png',
fileMD5: worldImage.value.fileMd5
});
if (json.status !== 200) {
changeWorldImageDialogLoading.value = false;
$throw(json.status, 'World image upload failed', params.url);
}
const args = {
json,
params
};
return worldImageFileAWS(args);
}
async function worldImageFileAWS(args) {
const { fileId, fileVersion } = args.params;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadWorldImageFileFinish(params);
return worldImageFileFinish(res);
}
async function worldImageFileFinish(args) {
const { fileId, fileVersion } = args.params;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadWorldImageSigStart(params);
return worldImageSigStart(res);
}
async function worldImageSigStart(args) {
const { url } = args.json;
const { fileId, fileVersion } = args.params;
const params = {
url,
fileId,
fileVersion
};
return uploadWorldImageSigAWS(params);
}
async function uploadWorldImageSigAWS(params) {
const json = await webApiService.execute({
url: params.url,
uploadFilePUT: true,
fileData: worldImage.value.base64SignatureFile,
fileMIME: 'application/x-rsync-signature',
fileMD5: worldImage.value.signatureMd5
});
if (json.status !== 200) {
changeWorldImageDialogLoading.value = false;
$throw(json.status, 'World image upload failed', params.url);
}
const args = {
json,
params
};
return worldImageSigAWS(args);
}
async function worldImageSigAWS(args) {
const { fileId, fileVersion } = args.params;
const params = {
fileId,
fileVersion
};
const res = await imageRequest.uploadWorldImageSigFinish(params);
return worldImageSigFinish(res);
}
async function worldImageSigFinish(args) {
const { fileId, fileVersion } = args.params;
const params = {
id: worldImage.value.worldId,
imageUrl: `${AppDebug.endpointDomain}/file/${fileId}/${fileVersion}/file`
};
const res = await imageRequest.setWorldImage(params);
return worldImageSet(res);
}
function worldImageSet(args) {
changeWorldImageDialogLoading.value = false;
if (args.json.imageUrl === args.params.imageUrl) {
emit('update:previousImageUrl', args.json.imageUrl);
} else {
$throw(0, 'World image change failed', args.params.imageUrl);
}
}
// ------------ Upload Process End ------------
async function initiateUpload(base64File) {
const args = await worldRequest.uploadWorldImage(base64File);
const fileUrl = args.json.versions[args.json.versions.length - 1].file.url;
const worldArgs = await worldRequest.saveWorld({
id: worldDialog.value.id,
imageUrl: fileUrl
});
const ref = applyWorld(worldArgs.json);
changeWorldImageDialogLoading.value = false;
emit('update:previousImageUrl', ref.imageUrl);
// closeDialog();
}
function uploadWorldImage() {
document.getElementById('WorldImageUploadButton').click();
}
</script>
<style scoped>
.img-size {
width: 500px;
height: 375px;
}
</style>

View File

@@ -744,9 +744,19 @@
<NewInstanceDialog
:new-instance-dialog-location-tag="newInstanceDialogLocationTag"
:last-location="lastLocation" />
<ChangeWorldImageDialog
v-model:change-world-image-dialog-visible="changeWorldImageDialogVisible"
v-model:previousImageUrl="previousImageUrl" />
<input
id="WorldImageUploadButton"
type="file"
accept="image/*"
style="display: none"
@change="onFileChangeWorldImage" />
<ImageCropDialog
:open="cropDialogOpen"
:title="t('dialog.change_content_image.world')"
:aspect-ratio="4 / 3"
:file="cropDialogFile"
@update:open="cropDialogOpen = $event"
@confirm="onCropConfirmWorld" />
</template>
</div>
</template>
@@ -805,7 +815,6 @@
userStatusClass
} from '../../../shared/utils';
import {
useAdvancedSettingsStore,
useAppearanceSettingsStore,
useFavoriteStore,
useGalleryStore,
@@ -813,7 +822,6 @@
useInstanceStore,
useInviteStore,
useLocationStore,
useModalStore,
useUserStore,
useWorldStore
} from '../../../stores';
@@ -824,19 +832,21 @@
DropdownMenuSeparator,
DropdownMenuTrigger
} from '../../ui/dropdown-menu';
import {
handleImageUploadInput,
readFileAsBase64,
resizeImageToFitLimits,
uploadImageLegacy,
withUploadTimeout
} from '../../../shared/utils/imageUpload';
import { favoriteRequest, miscRequest, userRequest, worldRequest } from '../../../api';
import { Badge } from '../../ui/badge';
import { database } from '../../../service/database.js';
import { formatJsonVars } from '../../../shared/utils/base/ui';
import ImageCropDialog from '../ImageCropDialog.vue';
import InstanceActionBar from '../../InstanceActionBar.vue';
const modalStore = useModalStore();
const { translateText } = useAdvancedSettingsStore();
const { bioLanguage, translationApi } = storeToRefs(useAdvancedSettingsStore());
const NewInstanceDialog = defineAsyncComponent(() => import('../NewInstanceDialog.vue'));
const ChangeWorldImageDialog = defineAsyncComponent(() => import('./ChangeWorldImageDialog.vue'));
const SetWorldTagsDialog = defineAsyncComponent(() => import('./SetWorldTagsDialog.vue'));
const WorldAllowedDomainsDialog = defineAsyncComponent(() => import('./WorldAllowedDomainsDialog.vue'));
@@ -868,8 +878,9 @@
});
const isSetWorldTagsDialogVisible = ref(false);
const newInstanceDialogLocationTag = ref('');
const changeWorldImageDialogVisible = ref(false);
const previousImageUrl = ref('');
const cropDialogOpen = ref(false);
const cropDialogFile = ref(null);
const changeWorldImageLoading = ref(false);
const translatedDescription = ref('');
const isTranslating = ref(false);
@@ -1008,9 +1019,50 @@
}
function showChangeWorldImageDialog() {
const { imageUrl } = worldDialog.value.ref;
previousImageUrl.value = imageUrl;
changeWorldImageDialogVisible.value = true;
document.getElementById('WorldImageUploadButton').click();
}
function onFileChangeWorldImage(e) {
const { file, clearInput } = handleImageUploadInput(e, {
inputSelector: '#WorldImageUploadButton',
tooLargeMessage: () => t('message.file.too_large'),
invalidTypeMessage: () => t('message.file.not_image')
});
if (!file) {
return;
}
if (!worldDialog.value.visible || worldDialog.value.loading) {
clearInput();
return;
}
clearInput();
cropDialogFile.value = file;
cropDialogOpen.value = true;
}
async function onCropConfirmWorld(blob) {
changeWorldImageLoading.value = true;
try {
await withUploadTimeout(
(async () => {
const base64Body = await readFileAsBase64(blob);
const base64File = await resizeImageToFitLimits(base64Body);
await uploadImageLegacy('world', {
entityId: worldDialog.value.id,
imageUrl: worldDialog.value.ref.imageUrl,
base64File,
blob
});
})()
);
toast.success(t('message.upload.success'));
} catch (error) {
console.error('World image upload process failed:', error);
toast.error(t('message.upload.error'));
} finally {
changeWorldImageLoading.value = false;
cropDialogOpen.value = false;
}
}
function showNewInstanceDialog(tag) {

View File

@@ -0,0 +1,112 @@
import { ref } from 'vue';
import { toast } from 'vue-sonner';
import { useI18n } from 'vue-i18n';
const MAX_PREVIEW_SIZE = 800;
export function useImageCropper() {
const { t } = useI18n();
const cropperRef = ref(null);
const cropperImageSrc = ref('');
const originalImage = ref(null);
const previewScale = ref(1);
function resetCropState() {
cropperImageSrc.value = '';
originalImage.value = null;
previewScale.value = 1;
}
/**
* Downscaling for preview
* @param {File} file
*/
function loadImageForCrop(file) {
const r = new FileReader();
r.onload = () => {
const img = new Image();
img.onload = () => {
originalImage.value = img;
if (
img.width > MAX_PREVIEW_SIZE ||
img.height > MAX_PREVIEW_SIZE
) {
const scale = Math.min(
MAX_PREVIEW_SIZE / img.width,
MAX_PREVIEW_SIZE / img.height
);
previewScale.value = scale;
const cvs = document.createElement('canvas');
cvs.width = Math.round(img.width * scale);
cvs.height = Math.round(img.height * scale);
const ctx = cvs.getContext('2d');
ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
cropperImageSrc.value = cvs.toDataURL('image/jpeg', 0.9);
} else {
previewScale.value = 1;
// @ts-ignore
cropperImageSrc.value = r.result;
}
};
img.onerror = () => {
resetCropState();
};
// @ts-ignore
img.src = r.result;
};
r.onerror = () => {
resetCropState();
toast.error(t('message.file.not_image'));
};
r.readAsDataURL(file);
}
/**
* @param {File} [originalFile]
* @returns {Promise<Blob|null>}
*/
function getCroppedBlob(originalFile) {
const result = cropperRef.value?.getResult();
if (!result?.coordinates || !originalImage.value) {
return Promise.resolve(null);
}
const { coordinates } = result;
const scale = previewScale.value;
const srcX = Math.round(coordinates.left / scale);
const srcY = Math.round(coordinates.top / scale);
const srcW = Math.round(coordinates.width / scale);
const srcH = Math.round(coordinates.height / scale);
const img = originalImage.value;
const noCrop =
srcX <= 1 &&
srcY <= 1 &&
Math.abs(srcW - img.width) <= 1 &&
Math.abs(srcH - img.height) <= 1;
// pass no crop
if (noCrop && originalFile) {
return Promise.resolve(originalFile);
}
const cropCanvas = document.createElement('canvas');
cropCanvas.width = srcW;
cropCanvas.height = srcH;
const ctx = cropCanvas.getContext('2d');
ctx.drawImage(img, srcX, srcY, srcW, srcH, 0, 0, srcW, srcH);
return new Promise((resolve) => {
cropCanvas.toBlob(resolve, 'image/png');
});
}
return {
cropperRef,
cropperImageSrc,
resetCropState,
loadImageForCrop,
getCroppedBlob
};
}

View File

@@ -1694,7 +1694,8 @@
"drone_skin": "Drone Skin",
"emoji": "Emoji",
"redeem": "Redeem",
"create_animated_emoji": "Animated Emoji Generator"
"create_animated_emoji": "Animated Emoji Generator",
"crop_image": "Confirm Upload"
},
"gallery_select": {
"header": "Select Image",

View File

@@ -1,4 +1,24 @@
import { toast } from 'vue-sonner';
import { $throw } from '../../service/request';
import { AppDebug } from '../../service/appConfig.js';
import { extractFileId } from './index.js';
import { imageRequest } from '../../api';
const UPLOAD_TIMEOUT_MS = 20_000;
export function withUploadTimeout(promise) {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(
() => reject(new Error('Upload timed out')),
UPLOAD_TIMEOUT_MS
)
)
]);
}
function resolveMessage(message) {
if (typeof message === 'function') {
return message();
@@ -71,3 +91,144 @@ export function handleImageUploadInput(event, options = {}) {
return { file, clearInput };
}
/**
* File -> base64
* @param {Blob|File} blob
* @returns {Promise<string>} base64 encoded string
*/
export function readFileAsBase64(blob) {
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onerror = reject;
r.onabort = reject;
r.onload = () => {
const bytes = new Uint8Array(r.result);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
resolve(btoa(binary));
};
r.readAsArrayBuffer(blob);
});
}
/**
* @param {string} base64Data - base64 encoded image
* @returns {Promise<string>} resized base64 encoded image
*/
export async function resizeImageToFitLimits(base64Data) {
// frontend limit check = 20MB
return AppApi.ResizeImageToFitLimits(base64Data);
}
/**
* Upload image through AWS
* @param {'avatar'|'world'} type
* @param {object} opts
* @param {string} opts.entityId - avatar or world id
* @param {string} opts.imageUrl - current imageUrl on the entity
* @param {string} opts.base64File - base64 encoded image data
* @param {Blob} opts.blob - the original blob (used for file size)
*/
export async function uploadImageLegacy(
type,
{ entityId, imageUrl, base64File, blob }
) {
const apiMap = {
avatar: {
uploadImage: imageRequest.uploadAvatarImage,
fileStart: imageRequest.uploadAvatarImageFileStart,
fileFinish: imageRequest.uploadAvatarImageFileFinish,
sigStart: imageRequest.uploadAvatarImageSigStart,
sigFinish: imageRequest.uploadAvatarImageSigFinish,
setImage: imageRequest.setAvatarImage
},
world: {
uploadImage: imageRequest.uploadWorldImage,
fileStart: imageRequest.uploadWorldImageFileStart,
fileFinish: imageRequest.uploadWorldImageFileFinish,
sigStart: imageRequest.uploadWorldImageSigStart,
sigFinish: imageRequest.uploadWorldImageSigFinish,
setImage: imageRequest.setWorldImage
}
};
const api = apiMap[type];
const fileMd5 = await AppApi.MD5File(base64File);
const fileSizeInBytes = parseInt(blob.size, 10);
const base64SignatureFile = await AppApi.SignFile(base64File);
const signatureMd5 = await AppApi.MD5File(base64SignatureFile);
const signatureSizeInBytes = parseInt(
await AppApi.FileLength(base64SignatureFile),
10
);
const fileId = extractFileId(imageUrl);
// imageInit
const uploadRes = await api.uploadImage(
{ fileMd5, fileSizeInBytes, signatureMd5, signatureSizeInBytes },
fileId
);
const uploadedFileId = uploadRes.json.id;
const fileVersion =
uploadRes.json.versions[uploadRes.json.versions.length - 1].version;
// imageFileStart
const fileStartRes = await api.fileStart({
fileId: uploadedFileId,
fileVersion
});
// uploadImageFileAWS
const fileAwsRes = await webApiService.execute({
url: fileStartRes.json.url,
uploadFilePUT: true,
fileData: base64File,
fileMIME: 'image/png',
fileMD5: fileMd5
});
if (fileAwsRes.status !== 200) {
$throw(
fileAwsRes.status,
`${type} image upload failed`,
fileStartRes.json.url
);
}
// imageFileFinish
await api.fileFinish({ fileId: uploadedFileId, fileVersion });
// imageSigStart
const sigStartRes = await api.sigStart({
fileId: uploadedFileId,
fileVersion
});
// uploadImageSigAWS
const sigAwsRes = await webApiService.execute({
url: sigStartRes.json.url,
uploadFilePUT: true,
fileData: base64SignatureFile,
fileMIME: 'application/x-rsync-signature',
fileMD5: signatureMd5
});
if (sigAwsRes.status !== 200) {
$throw(
sigAwsRes.status,
`${type} image upload failed`,
sigStartRes.json.url
);
}
// imageSigFinish
await api.sigFinish({ fileId: uploadedFileId, fileVersion });
// imageSet
const newImageUrl = `${AppDebug.endpointDomain}/file/${uploadedFileId}/${fileVersion}/file`;
const setRes = await api.setImage({ id: entityId, imageUrl: newImageUrl });
if (setRes.json.imageUrl !== newImageUrl) {
$throw(0, `${type} image change failed`, newImageUrl);
}
}

View File

@@ -559,6 +559,14 @@
</div>
</template>
</TabsUnderline>
<ImageCropDialog
:open="cropDialogOpen"
:title="cropDialogTitle"
:aspect-ratio="cropDialogAspectRatio"
:file="cropDialogFile"
@update:open="cropDialogOpen = $event"
@confirm="onCropConfirm" />
</div>
</template>
@@ -592,11 +600,12 @@
} from '../../shared/utils';
import { inventoryRequest, miscRequest, userRequest, vrcPlusIconRequest, vrcPlusImageRequest } from '../../api';
import { useAdvancedSettingsStore, useAuthStore, useGalleryStore, useModalStore, useUserStore } from '../../stores';
import { handleImageUploadInput, readFileAsBase64, withUploadTimeout } from '../../shared/utils/imageUpload';
import { emojiAnimationStyleList, emojiAnimationStyleUrl } from '../../shared/constants';
import { AppDebug } from '../../service/appConfig';
import { handleImageUploadInput } from '../../shared/utils/imageUpload';
import Emoji from '../../components/Emoji.vue';
import ImageCropDialog from '../../components/dialogs/ImageCropDialog.vue';
const { t } = useI18n();
const router = useRouter();
@@ -663,6 +672,12 @@
const pendingUploads = ref(0);
const isUploading = computed(() => pendingUploads.value > 0);
const cropDialogOpen = ref(false);
const cropDialogTitle = ref('');
const cropDialogAspectRatio = ref(4 / 3);
const cropDialogFile = ref(null);
const cropDialogUploadHandler = ref(null);
onMounted(() => {
galleryDialogVisible.value = true;
loadGalleryData();
@@ -685,6 +700,28 @@
router.push({ name: 'tools' });
}
function openCropDialog(file, title, aspectRatio, handler) {
cropDialogTitle.value = title;
cropDialogAspectRatio.value = aspectRatio;
cropDialogFile.value = file;
cropDialogUploadHandler.value = handler;
cropDialogOpen.value = true;
}
async function onCropConfirm(blob) {
if (!cropDialogUploadHandler.value) {
return;
}
const handler = cropDialogUploadHandler.value;
cropDialogUploadHandler.value = null;
cropDialogFile.value = null;
try {
await handler(blob);
} finally {
cropDialogOpen.value = false;
}
}
function onFileChangeGallery(e) {
const { file, clearInput } = handleImageUploadInput(e, {
inputSelector: '#GalleryUploadButton',
@@ -694,41 +731,25 @@
if (!file) {
return;
}
startUpload();
const r = new FileReader();
const handleReaderError = () => finishUpload();
r.onerror = handleReaderError;
r.onabort = handleReaderError;
r.onload = function () {
try {
const base64Body = btoa(r.result.toString());
const uploadPromise = vrcPlusImageRequest.uploadGalleryImage(base64Body).then((args) => {
handleGalleryImageAdd(args);
return args;
});
toast.promise(uploadPromise, {
loading: t('message.upload.loading'),
success: t('message.upload.success'),
error: t('message.upload.error')
});
uploadPromise
.catch((error) => {
console.error('Failed to upload', error);
})
.finally(() => finishUpload());
} catch (error) {
finishUpload();
console.error('Failed to process image', error);
}
};
try {
r.readAsBinaryString(file);
} catch (error) {
clearInput();
finishUpload();
console.error('Failed to read file', error);
}
clearInput();
openCropDialog(file, t('dialog.change_content_image.upload'), 4 / 3, async (blob) => {
startUpload();
try {
await withUploadTimeout(
(async () => {
const base64Body = await readFileAsBase64(blob);
const args = await vrcPlusImageRequest.uploadGalleryImage(base64Body);
handleGalleryImageAdd(args);
})()
);
toast.success(t('message.upload.success'));
} catch (error) {
console.error('Failed to upload', error);
toast.error(t('message.upload.error'));
} finally {
finishUpload();
}
});
}
function displayGalleryUpload() {
@@ -789,43 +810,27 @@
if (!file) {
return;
}
startUpload();
const r = new FileReader();
const handleReaderError = () => finishUpload();
r.onerror = handleReaderError;
r.onabort = handleReaderError;
r.onload = function () {
try {
const base64Body = btoa(r.result.toString());
const uploadPromise = vrcPlusIconRequest.uploadVRCPlusIcon(base64Body).then((args) => {
if (Object.keys(VRCPlusIconsTable.value).length !== 0) {
VRCPlusIconsTable.value.unshift(args.json);
}
return args;
});
toast.promise(uploadPromise, {
loading: t('message.upload.loading'),
success: t('message.upload.success'),
error: t('message.upload.error')
});
uploadPromise
.catch((error) => {
console.error('Failed to upload VRC+ icon', error);
})
.finally(() => finishUpload());
} catch (error) {
finishUpload();
console.error('Failed to process upload', error);
}
};
try {
r.readAsBinaryString(file);
} catch (error) {
clearInput();
finishUpload();
console.error('Failed to read file', error);
}
clearInput();
openCropDialog(file, t('dialog.change_content_image.upload'), 1 / 1, async (blob) => {
startUpload();
try {
await withUploadTimeout(
(async () => {
const base64Body = await readFileAsBase64(blob);
const args = await vrcPlusIconRequest.uploadVRCPlusIcon(base64Body);
if (Object.keys(VRCPlusIconsTable.value).length !== 0) {
VRCPlusIconsTable.value.unshift(args.json);
}
})()
);
toast.success(t('message.upload.success'));
} catch (error) {
console.error('Failed to upload VRC+ icon', error);
toast.error(t('message.upload.error'));
} finally {
finishUpload();
}
});
}
function displayVRCPlusIconUpload() {
@@ -908,57 +913,41 @@
if (!file) {
return;
}
startUpload();
// set Emoji settings from fileName
parseEmojiFileName(file.name);
const r = new FileReader();
const handleReaderError = () => finishUpload();
r.onerror = handleReaderError;
r.onabort = handleReaderError;
r.onload = function () {
try {
const params = {
tag: emojiAnimType.value ? 'emojianimated' : 'emoji',
animationStyle: emojiAnimationStyle.value.toLowerCase(),
maskTag: 'square'
};
if (emojiAnimType.value) {
params.frames = emojiAnimFrameCount.value;
params.framesOverTime = emojiAnimFps.value;
}
if (emojiAnimLoopPingPong.value) {
params.loopStyle = 'pingpong';
}
const base64Body = btoa(r.result.toString());
const uploadPromise = vrcPlusImageRequest.uploadEmoji(base64Body, params).then((args) => {
if (Object.keys(emojiTable.value).length !== 0) {
emojiTable.value.unshift(args.json);
}
return args;
});
toast.promise(uploadPromise, {
loading: t('message.upload.loading'),
success: t('message.upload.success'),
error: t('message.upload.error')
});
uploadPromise
.catch((error) => {
console.error('Failed to upload', error);
})
.finally(() => finishUpload());
} catch (error) {
finishUpload();
console.error('Failed to process upload', error);
}
};
try {
r.readAsBinaryString(file);
} catch (error) {
clearInput();
finishUpload();
console.error('Failed to read file', error);
}
clearInput();
openCropDialog(file, t('dialog.change_content_image.upload'), 1 / 1, async (blob) => {
startUpload();
try {
await withUploadTimeout(
(async () => {
const params = {
tag: emojiAnimType.value ? 'emojianimated' : 'emoji',
animationStyle: emojiAnimationStyle.value.toLowerCase(),
maskTag: 'square'
};
if (emojiAnimType.value) {
params.frames = emojiAnimFrameCount.value;
params.framesOverTime = emojiAnimFps.value;
}
if (emojiAnimLoopPingPong.value) {
params.loopStyle = 'pingpong';
}
const base64Body = await readFileAsBase64(blob);
const args = await vrcPlusImageRequest.uploadEmoji(base64Body, params);
if (Object.keys(emojiTable.value).length !== 0) {
emojiTable.value.unshift(args.json);
}
})()
);
toast.success(t('message.upload.success'));
} catch (error) {
console.error('Failed to upload', error);
toast.error(t('message.upload.error'));
} finally {
finishUpload();
}
});
}
function displayEmojiUpload() {
@@ -988,45 +977,29 @@
if (!file) {
return;
}
startUpload();
const r = new FileReader();
const handleReaderError = () => finishUpload();
r.onerror = handleReaderError;
r.onabort = handleReaderError;
r.onload = function () {
try {
const params = {
tag: 'sticker',
maskTag: 'square'
};
const base64Body = btoa(r.result.toString());
const uploadPromise = vrcPlusImageRequest.uploadSticker(base64Body, params).then((args) => {
handleStickerAdd(args);
return args;
});
toast.promise(uploadPromise, {
loading: t('message.upload.loading'),
success: t('message.upload.success'),
error: t('message.upload.error')
});
uploadPromise
.catch((error) => {
console.error('Failed to upload', error);
})
.finally(() => finishUpload());
} catch (error) {
finishUpload();
console.error('Failed to process upload', error);
}
};
try {
r.readAsBinaryString(file);
} catch (error) {
clearInput();
finishUpload();
console.error('Failed to read file', error);
}
clearInput();
openCropDialog(file, t('dialog.change_content_image.upload'), 1 / 1, async (blob) => {
startUpload();
try {
await withUploadTimeout(
(async () => {
const params = {
tag: 'sticker',
maskTag: 'square'
};
const base64Body = await readFileAsBase64(blob);
const args = await vrcPlusImageRequest.uploadSticker(base64Body, params);
handleStickerAdd(args);
})()
);
toast.success(t('message.upload.success'));
} catch (error) {
console.error('Failed to upload', error);
toast.error(t('message.upload.error'));
} finally {
finishUpload();
}
});
}
function displayStickerUpload() {
@@ -1057,55 +1030,37 @@
if (!file) {
return;
}
startUpload();
const r = new FileReader();
const handleReaderError = () => finishUpload();
r.onerror = handleReaderError;
r.onabort = handleReaderError;
r.onload = function () {
clearInput();
openCropDialog(file, t('dialog.change_content_image.upload'), 16 / 9, async (blob) => {
startUpload();
try {
const date = new Date();
// why the fuck isn't this UTC
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
const timestamp = date.toISOString().slice(0, 19);
const params = {
note: printUploadNote.value,
// worldId: '',
timestamp
};
const base64Body = btoa(r.result.toString());
const cropWhiteBorder = printCropBorder.value;
const uploadPromise = vrcPlusImageRequest
.uploadPrint(base64Body, cropWhiteBorder, params)
.then((args) => {
await withUploadTimeout(
(async () => {
const date = new Date();
// why the fuck isn't this UTC
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
const timestamp = date.toISOString().slice(0, 19);
const params = {
note: printUploadNote.value,
// worldId: '',
timestamp
};
const base64Body = await readFileAsBase64(blob);
const cropWhiteBorder = printCropBorder.value;
const args = await vrcPlusImageRequest.uploadPrint(base64Body, cropWhiteBorder, params);
if (Object.keys(printTable.value).length !== 0) {
printTable.value.unshift(args.json);
}
return args;
});
toast.promise(uploadPromise, {
loading: t('message.upload.loading'),
success: t('message.upload.success'),
error: t('message.upload.error')
});
uploadPromise
.catch((error) => {
console.error('Failed to upload', error);
})
.finally(() => finishUpload());
})()
);
toast.success(t('message.upload.success'));
} catch (error) {
console.error('Failed to upload', error);
toast.error(t('message.upload.error'));
} finally {
finishUpload();
console.error('Failed to process upload', error);
}
};
try {
r.readAsBinaryString(file);
} catch (error) {
clearInput();
finishUpload();
console.error('Failed to read file', error);
}
clearInput();
});
}
function displayPrintUpload() {