mirror of
https://github.com/MrUnknownDE/VRCX.git
synced 2026-04-21 07:43:50 +02:00
refactor untils
This commit is contained in:
153
src/shared/utils/__tests__/appActions.test.js
Normal file
153
src/shared/utils/__tests__/appActions.test.js
Normal file
@@ -0,0 +1,153 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn()
|
||||
},
|
||||
searchStore: {
|
||||
directAccessParse: vi.fn()
|
||||
},
|
||||
modalStore: {
|
||||
confirm: vi.fn()
|
||||
},
|
||||
i18n: {
|
||||
global: {
|
||||
t: vi.fn(() => 'copy failed')
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
vi.mock('vue-sonner', () => ({
|
||||
toast: mocks.toast
|
||||
}));
|
||||
|
||||
vi.mock('../../../stores', () => ({
|
||||
useSearchStore: () => mocks.searchStore,
|
||||
useModalStore: () => mocks.modalStore
|
||||
}));
|
||||
|
||||
vi.mock('../../../plugins/i18n', () => ({
|
||||
i18n: mocks.i18n
|
||||
}));
|
||||
|
||||
import {
|
||||
copyToClipboard,
|
||||
downloadAndSaveJson,
|
||||
openDiscordProfile,
|
||||
openExternalLink,
|
||||
openFolderGeneric
|
||||
} from '../appActions';
|
||||
|
||||
function flushPromises() {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
describe('appActions utils', () => {
|
||||
let consoleErrorSpy;
|
||||
|
||||
beforeEach(() => {
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
vi.clearAllMocks();
|
||||
mocks.searchStore.directAccessParse.mockReturnValue(false);
|
||||
mocks.modalStore.confirm.mockResolvedValue({ ok: false });
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: {
|
||||
writeText: vi.fn().mockResolvedValue(undefined)
|
||||
}
|
||||
});
|
||||
globalThis.AppApi = {
|
||||
OpenLink: vi.fn(),
|
||||
OpenDiscordProfile: vi.fn().mockResolvedValue(undefined),
|
||||
OpenFolderAndSelectItem: vi.fn()
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
test('downloadAndSaveJson returns early for invalid params', () => {
|
||||
downloadAndSaveJson('', { a: 1 });
|
||||
downloadAndSaveJson('name', null);
|
||||
expect(document.querySelectorAll('a[download]').length).toBe(0);
|
||||
});
|
||||
|
||||
test('downloadAndSaveJson creates and clicks download link', () => {
|
||||
const appendSpy = vi.spyOn(document.body, 'appendChild');
|
||||
const removeSpy = vi.spyOn(document.body, 'removeChild');
|
||||
|
||||
downloadAndSaveJson('profile', { id: 1 });
|
||||
|
||||
expect(appendSpy).toHaveBeenCalledTimes(1);
|
||||
expect(removeSpy).toHaveBeenCalledTimes(1);
|
||||
appendSpy.mockRestore();
|
||||
removeSpy.mockRestore();
|
||||
});
|
||||
|
||||
test('copyToClipboard shows success toast', async () => {
|
||||
copyToClipboard('hello', 'copied');
|
||||
await flushPromises();
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('hello');
|
||||
expect(mocks.toast.success).toHaveBeenCalledWith('copied');
|
||||
});
|
||||
|
||||
test('copyToClipboard shows translated error toast on failure', async () => {
|
||||
navigator.clipboard.writeText.mockRejectedValue(new Error('denied'));
|
||||
copyToClipboard('hello');
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(mocks.toast.error).toHaveBeenCalledWith('copy failed');
|
||||
});
|
||||
|
||||
test('openExternalLink returns early when direct access parse succeeds', async () => {
|
||||
mocks.searchStore.directAccessParse.mockReturnValue(true);
|
||||
openExternalLink('vrcx://user/usr_1');
|
||||
await flushPromises();
|
||||
expect(mocks.modalStore.confirm).not.toHaveBeenCalled();
|
||||
expect(AppApi.OpenLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('openExternalLink copies link when confirm is canceled', async () => {
|
||||
mocks.modalStore.confirm.mockResolvedValue({
|
||||
ok: false,
|
||||
reason: 'cancel'
|
||||
});
|
||||
openExternalLink('https://example.com');
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
|
||||
'https://example.com'
|
||||
);
|
||||
});
|
||||
|
||||
test('openExternalLink opens link when confirmed', async () => {
|
||||
mocks.modalStore.confirm.mockResolvedValue({ ok: true });
|
||||
openExternalLink('https://example.com');
|
||||
await flushPromises();
|
||||
expect(AppApi.OpenLink).toHaveBeenCalledWith('https://example.com');
|
||||
});
|
||||
|
||||
test('openDiscordProfile validates empty discord id', () => {
|
||||
openDiscordProfile('');
|
||||
expect(mocks.toast.error).toHaveBeenCalledWith('No Discord ID provided!');
|
||||
});
|
||||
|
||||
test('openDiscordProfile shows error toast when api fails', async () => {
|
||||
AppApi.OpenDiscordProfile.mockRejectedValue(new Error('fail'));
|
||||
openDiscordProfile('123');
|
||||
await flushPromises();
|
||||
expect(mocks.toast.error).toHaveBeenCalledWith(
|
||||
'Failed to open Discord profile!'
|
||||
);
|
||||
});
|
||||
|
||||
test('openFolderGeneric delegates to AppApi', () => {
|
||||
openFolderGeneric('/tmp/a.txt');
|
||||
expect(AppApi.OpenFolderAndSelectItem).toHaveBeenCalledWith(
|
||||
'/tmp/a.txt',
|
||||
true
|
||||
);
|
||||
});
|
||||
});
|
||||
40
src/shared/utils/__tests__/chart.test.js
Normal file
40
src/shared/utils/__tests__/chart.test.js
Normal file
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
|
||||
describe('loadEcharts', () => {
|
||||
test('loads echarts module', async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock('echarts', () => ({
|
||||
__esModule: true,
|
||||
marker: 'mock-echarts'
|
||||
}));
|
||||
const { loadEcharts } = await import('../chart.js');
|
||||
|
||||
const module = await loadEcharts();
|
||||
|
||||
expect(module).toMatchObject({ marker: 'mock-echarts' });
|
||||
});
|
||||
|
||||
test('returns cached module reference on subsequent calls', async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock('echarts', () => ({
|
||||
__esModule: true,
|
||||
marker: 'mock-echarts'
|
||||
}));
|
||||
const { loadEcharts } = await import('../chart.js');
|
||||
|
||||
const first = await loadEcharts();
|
||||
const second = await loadEcharts();
|
||||
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
|
||||
test('rejects when echarts import fails', async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock('echarts', () => {
|
||||
throw new Error('import failed');
|
||||
});
|
||||
const { loadEcharts } = await import('../chart.js');
|
||||
|
||||
await expect(loadEcharts()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ vi.mock('../../../services/appConfig', () => ({
|
||||
AppDebug: { endpointDomain: 'https://api.vrchat.cloud/api/1' }
|
||||
}));
|
||||
|
||||
vi.mock('../../utils/index.js', () => ({
|
||||
vi.mock('../../../shared/utils', () => ({
|
||||
extractFileId: vi.fn()
|
||||
}));
|
||||
|
||||
@@ -22,7 +22,8 @@ vi.mock('../../../api', () => ({
|
||||
}));
|
||||
|
||||
import { toast } from 'vue-sonner';
|
||||
import { handleImageUploadInput, withUploadTimeout } from '../imageUpload';
|
||||
import { withUploadTimeout } from '../imageUpload';
|
||||
import { handleImageUploadInput } from '../../../coordinators/imageUploadCoordinator';
|
||||
|
||||
// ─── withUploadTimeout ───────────────────────────────────────────────
|
||||
|
||||
|
||||
162
src/shared/utils/__tests__/memos.test.js
Normal file
162
src/shared/utils/__tests__/memos.test.js
Normal file
@@ -0,0 +1,162 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
friends: new Map(),
|
||||
setUserDialogMemo: vi.fn(),
|
||||
database: {
|
||||
getUserMemo: vi.fn(),
|
||||
setUserMemo: vi.fn(),
|
||||
deleteUserMemo: vi.fn(),
|
||||
getAllUserMemos: vi.fn(),
|
||||
getWorldMemo: vi.fn()
|
||||
},
|
||||
storage: {
|
||||
GetAll: vi.fn(),
|
||||
Remove: vi.fn()
|
||||
}
|
||||
}));
|
||||
|
||||
vi.mock('../../../stores', () => ({
|
||||
useFriendStore: () => ({
|
||||
friends: mocks.friends
|
||||
}),
|
||||
useUserStore: () => ({
|
||||
setUserDialogMemo: (...args) => mocks.setUserDialogMemo(...args)
|
||||
})
|
||||
}));
|
||||
|
||||
vi.mock('../../../services/database', () => ({
|
||||
database: mocks.database
|
||||
}));
|
||||
|
||||
import {
|
||||
getAllUserMemos,
|
||||
getUserMemo,
|
||||
getWorldMemo,
|
||||
migrateMemos,
|
||||
saveUserMemo
|
||||
} from '../../../coordinators/memoCoordinator.js';
|
||||
|
||||
describe('memos utils', () => {
|
||||
let consoleErrorSpy;
|
||||
|
||||
beforeEach(() => {
|
||||
consoleErrorSpy = vi
|
||||
.spyOn(console, 'error')
|
||||
.mockImplementation(() => {});
|
||||
mocks.friends = new Map();
|
||||
mocks.setUserDialogMemo.mockReset();
|
||||
mocks.database.getUserMemo.mockReset();
|
||||
mocks.database.setUserMemo.mockReset();
|
||||
mocks.database.deleteUserMemo.mockReset();
|
||||
mocks.database.getAllUserMemos.mockReset();
|
||||
mocks.database.getWorldMemo.mockReset();
|
||||
mocks.storage.GetAll.mockReset();
|
||||
mocks.storage.Remove.mockReset();
|
||||
globalThis.VRCXStorage = mocks.storage;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
test('getUserMemo returns fallback when database throws', async () => {
|
||||
mocks.database.getUserMemo.mockRejectedValue(new Error('boom'));
|
||||
|
||||
const result = await getUserMemo('usr_1');
|
||||
|
||||
expect(result).toEqual({
|
||||
userId: '',
|
||||
editedAt: '',
|
||||
memo: ''
|
||||
});
|
||||
});
|
||||
|
||||
test('getWorldMemo returns fallback when database throws', async () => {
|
||||
mocks.database.getWorldMemo.mockRejectedValue(new Error('boom'));
|
||||
|
||||
const result = await getWorldMemo('wrld_1');
|
||||
|
||||
expect(result).toEqual({
|
||||
worldId: '',
|
||||
editedAt: '',
|
||||
memo: ''
|
||||
});
|
||||
});
|
||||
|
||||
test('saveUserMemo persists memo and syncs friend fields', async () => {
|
||||
const friend = { memo: '', $nickName: '' };
|
||||
mocks.friends.set('usr_1', friend);
|
||||
|
||||
await saveUserMemo('usr_1', 'Nick\nmore');
|
||||
|
||||
expect(mocks.database.setUserMemo).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.database.deleteUserMemo).not.toHaveBeenCalled();
|
||||
expect(friend.memo).toBe('Nick\nmore');
|
||||
expect(friend.$nickName).toBe('Nick');
|
||||
expect(mocks.setUserDialogMemo).toHaveBeenCalledWith('Nick\nmore');
|
||||
});
|
||||
|
||||
test('saveUserMemo deletes memo and clears nickname on empty input', async () => {
|
||||
const friend = { memo: 'old', $nickName: 'old' };
|
||||
mocks.friends.set('usr_1', friend);
|
||||
|
||||
await saveUserMemo('usr_1', '');
|
||||
|
||||
expect(mocks.database.deleteUserMemo).toHaveBeenCalledWith('usr_1');
|
||||
expect(friend.memo).toBe('');
|
||||
expect(friend.$nickName).toBe('');
|
||||
expect(mocks.setUserDialogMemo).toHaveBeenCalledWith('');
|
||||
});
|
||||
|
||||
test('getAllUserMemos applies memo data to existing cached friends', async () => {
|
||||
const friend1 = { memo: '', $nickName: '' };
|
||||
const friend2 = { memo: '', $nickName: '' };
|
||||
mocks.friends.set('usr_1', friend1);
|
||||
mocks.friends.set('usr_2', friend2);
|
||||
mocks.database.getAllUserMemos.mockResolvedValue([
|
||||
{ userId: 'usr_1', memo: 'Alpha\nline2' },
|
||||
{ userId: 'usr_2', memo: '' },
|
||||
{ userId: 'usr_missing', memo: 'ignored' }
|
||||
]);
|
||||
|
||||
await getAllUserMemos();
|
||||
|
||||
expect(friend1.memo).toBe('Alpha\nline2');
|
||||
expect(friend1.$nickName).toBe('Alpha');
|
||||
expect(friend2.memo).toBe('');
|
||||
expect(friend2.$nickName).toBe('');
|
||||
});
|
||||
|
||||
test('migrateMemos moves memo_usr entries to database and storage cleanup', async () => {
|
||||
const friend = { memo: '', $nickName: '' };
|
||||
mocks.friends.set('usr_1', friend);
|
||||
mocks.storage.GetAll.mockResolvedValue(
|
||||
JSON.stringify({
|
||||
memo_usr_1: 'hello',
|
||||
other_key: 'x',
|
||||
memo_usr_2: ''
|
||||
})
|
||||
);
|
||||
|
||||
await migrateMemos();
|
||||
|
||||
expect(mocks.database.setUserMemo).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.database.setUserMemo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 'usr_1',
|
||||
memo: 'hello'
|
||||
})
|
||||
);
|
||||
expect(mocks.storage.Remove).toHaveBeenCalledWith('memo_usr_1');
|
||||
expect(mocks.storage.Remove).not.toHaveBeenCalledWith('memo_usr_2');
|
||||
});
|
||||
|
||||
test('migrateMemos rejects for invalid JSON payload', async () => {
|
||||
mocks.storage.GetAll.mockResolvedValue('{bad json');
|
||||
|
||||
await expect(migrateMemos()).rejects.toThrow();
|
||||
expect(mocks.database.setUserMemo).not.toHaveBeenCalled();
|
||||
expect(mocks.storage.Remove).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
102
src/shared/utils/appActions.js
Normal file
102
src/shared/utils/appActions.js
Normal file
@@ -0,0 +1,102 @@
|
||||
import { toast } from 'vue-sonner';
|
||||
|
||||
import { useModalStore, useSearchStore } from '../../stores';
|
||||
import { escapeTag } from './base/string';
|
||||
import { i18n } from '../../plugins/i18n';
|
||||
|
||||
/**
|
||||
* @param {string} fileName
|
||||
* @param {*} data
|
||||
*/
|
||||
function downloadAndSaveJson(fileName, data) {
|
||||
if (!fileName || !data) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const link = document.createElement('a');
|
||||
link.setAttribute(
|
||||
'href',
|
||||
`data:application/json;charset=utf-8,${encodeURIComponent(
|
||||
JSON.stringify(data, null, 2)
|
||||
)}`
|
||||
);
|
||||
link.setAttribute('download', `${fileName}.json`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
} catch {
|
||||
toast.error(escapeTag('Failed to download JSON.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {string} message
|
||||
*/
|
||||
function copyToClipboard(text, message = 'Copied successfully!') {
|
||||
navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => {
|
||||
toast.success(message);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Copy failed:', err);
|
||||
toast.error(i18n.global.t('message.copy_failed'));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} link
|
||||
*/
|
||||
function openExternalLink(link) {
|
||||
const searchStore = useSearchStore();
|
||||
if (searchStore.directAccessParse(link)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const modalStore = useModalStore();
|
||||
modalStore
|
||||
.confirm({
|
||||
description: `${link}`,
|
||||
title: 'Open External Link',
|
||||
confirmText: 'Open',
|
||||
cancelText: 'Copy'
|
||||
})
|
||||
.then(({ ok, reason }) => {
|
||||
if (reason === 'cancel') {
|
||||
copyToClipboard(link, 'Link copied to clipboard!');
|
||||
return;
|
||||
}
|
||||
if (ok) {
|
||||
AppApi.OpenLink(link);
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function openDiscordProfile(discordId) {
|
||||
if (!discordId) {
|
||||
toast.error('No Discord ID provided!');
|
||||
return;
|
||||
}
|
||||
AppApi.OpenDiscordProfile(discordId).catch((err) => {
|
||||
console.error('Failed to open Discord profile:', err);
|
||||
toast.error('Failed to open Discord profile!');
|
||||
});
|
||||
}
|
||||
|
||||
// #region | App: Random unsorted app methods, data structs, API functions, and an API feedback/file analysis event
|
||||
|
||||
function openFolderGeneric(path) {
|
||||
AppApi.OpenFolderAndSelectItem(path, true);
|
||||
}
|
||||
|
||||
export {
|
||||
downloadAndSaveJson,
|
||||
copyToClipboard,
|
||||
openExternalLink,
|
||||
openDiscordProfile,
|
||||
openFolderGeneric
|
||||
};
|
||||
@@ -15,7 +15,7 @@ vi.mock('../../../../plugins/router', () => ({
|
||||
}));
|
||||
|
||||
import { useAppearanceSettingsStore } from '../../../../stores';
|
||||
import { formatDateFilter } from '../date';
|
||||
import { formatDateFilter } from '../../../../coordinators/dateCoordinator';
|
||||
|
||||
describe('formatDateFilter', () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import { useAppearanceSettingsStore } from '../../../stores';
|
||||
|
||||
function padZero(num) {
|
||||
return String(num).padStart(2, '0');
|
||||
}
|
||||
|
||||
function toIsoLong(date) {
|
||||
const y = date.getFullYear();
|
||||
const m = padZero(date.getMonth() + 1);
|
||||
const d = padZero(date.getDate());
|
||||
const hh = padZero(date.getHours());
|
||||
const mm = padZero(date.getMinutes());
|
||||
const ss = padZero(date.getSeconds());
|
||||
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function toLocalShort(date, dateFormat, hour12) {
|
||||
return date
|
||||
.toLocaleDateString(dateFormat, {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: 'numeric',
|
||||
minute: 'numeric',
|
||||
hourCycle: hour12 ? 'h12' : 'h23'
|
||||
})
|
||||
.replace(' AM', 'am')
|
||||
.replace(' PM', 'pm')
|
||||
.replace(',', '');
|
||||
}
|
||||
|
||||
function toLocalLong(date, dateFormat, hour12) {
|
||||
return date.toLocaleDateString(dateFormat, {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: 'numeric',
|
||||
second: 'numeric',
|
||||
hourCycle: hour12 ? 'h12' : 'h23'
|
||||
});
|
||||
}
|
||||
|
||||
function toLocalTime(date, dateFormat, hour12) {
|
||||
return date.toLocaleTimeString(dateFormat, {
|
||||
hour: 'numeric',
|
||||
minute: 'numeric',
|
||||
hourCycle: hour12 ? 'h12' : 'h23'
|
||||
});
|
||||
}
|
||||
|
||||
function toLocalDate(date, dateFormat) {
|
||||
return date.toLocaleDateString(dateFormat, {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
year: 'numeric'
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} dateStr
|
||||
* @param {'long'|'short'|'time'|'date'} format
|
||||
* @returns {string}
|
||||
*/
|
||||
function formatDateFilter(dateStr, format) {
|
||||
const appearance = useAppearanceSettingsStore();
|
||||
const {
|
||||
dtIsoFormat: isoFormat,
|
||||
dtHour12: hour12,
|
||||
currentCulture
|
||||
} = appearance;
|
||||
|
||||
if (!dateStr) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
const dt = new Date(dateStr);
|
||||
if (isNaN(dt.getTime())) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
let dateFormat = 'en-gb';
|
||||
if (!isoFormat && currentCulture) {
|
||||
dateFormat = currentCulture;
|
||||
}
|
||||
if (dateFormat.length > 4 && dateFormat[4] === '_') {
|
||||
dateFormat = dateFormat.slice(0, 4);
|
||||
}
|
||||
|
||||
if (isoFormat && format === 'long') {
|
||||
return toIsoLong(dt);
|
||||
} else if (format === 'long') {
|
||||
return toLocalLong(dt, dateFormat, hour12);
|
||||
} else if (format === 'short') {
|
||||
return toLocalShort(dt, dateFormat, hour12);
|
||||
} else if (format === 'time') {
|
||||
return toLocalTime(dt, dateFormat, hour12);
|
||||
} else if (format === 'date') {
|
||||
return toLocalDate(dt, dateFormat);
|
||||
} else {
|
||||
console.warn(`Unknown date format: ${format}`);
|
||||
}
|
||||
|
||||
return '-';
|
||||
}
|
||||
|
||||
export { formatDateFilter };
|
||||
@@ -1,14 +1,3 @@
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { toast } from 'vue-sonner';
|
||||
|
||||
import {
|
||||
useAuthStore,
|
||||
useAvatarStore,
|
||||
useInstanceStore,
|
||||
useModalStore,
|
||||
useSearchStore,
|
||||
useWorldStore
|
||||
} from '../../stores';
|
||||
import {
|
||||
extractFileId,
|
||||
extractFileVersion,
|
||||
@@ -17,148 +6,20 @@ import {
|
||||
import { escapeTag, replaceBioSymbols } from './base/string';
|
||||
import { getFaviconUrl, replaceVrcPackageUrl } from './urlUtils';
|
||||
import { AppDebug } from '../../services/appConfig.js';
|
||||
import { compareUnityVersion } from './avatar';
|
||||
import { getAvailablePlatforms } from './platformUtils';
|
||||
import { i18n } from '../../plugins/i18n';
|
||||
import { queryRequest } from '../../api';
|
||||
|
||||
/**
|
||||
* @param {string} fileName
|
||||
* @param {*} data
|
||||
*/
|
||||
function downloadAndSaveJson(fileName, data) {
|
||||
if (!fileName || !data) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const link = document.createElement('a');
|
||||
link.setAttribute(
|
||||
'href',
|
||||
`data:application/json;charset=utf-8,${encodeURIComponent(
|
||||
JSON.stringify(data, null, 2)
|
||||
)}`
|
||||
);
|
||||
link.setAttribute('download', `${fileName}.json`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
} catch {
|
||||
toast.error(escapeTag('Failed to download JSON.'));
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteVRChatCache(ref) {
|
||||
const authStore = useAuthStore();
|
||||
const sdkUnityVersion = authStore.cachedConfig.sdkUnityVersion;
|
||||
let assetUrl = '';
|
||||
let variant = '';
|
||||
for (let i = ref.unityPackages.length - 1; i > -1; i--) {
|
||||
const unityPackage = ref.unityPackages[i];
|
||||
if (
|
||||
unityPackage.variant &&
|
||||
unityPackage.variant !== 'standard' &&
|
||||
unityPackage.variant !== 'security'
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
unityPackage.platform === 'standalonewindows' &&
|
||||
compareUnityVersion(unityPackage.unitySortNumber, sdkUnityVersion)
|
||||
) {
|
||||
assetUrl = unityPackage.assetUrl;
|
||||
if (!unityPackage.variant || unityPackage.variant === 'standard') {
|
||||
variant = 'security';
|
||||
} else {
|
||||
variant = unityPackage.variant;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
const id = extractFileId(assetUrl);
|
||||
const version = parseInt(extractFileVersion(assetUrl), 10);
|
||||
const variantVersion = parseInt(extractVariantVersion(assetUrl), 10);
|
||||
await AssetBundleManager.DeleteCache(id, version, variant, variantVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} ref
|
||||
* @returns
|
||||
*/
|
||||
async function checkVRChatCache(ref) {
|
||||
if (!ref.unityPackages) {
|
||||
return { Item1: -1, Item2: false, Item3: '' };
|
||||
}
|
||||
const authStore = useAuthStore();
|
||||
const sdkUnityVersion = authStore.cachedConfig.sdkUnityVersion;
|
||||
let assetUrl = '';
|
||||
let variant = '';
|
||||
for (let i = ref.unityPackages.length - 1; i > -1; i--) {
|
||||
const unityPackage = ref.unityPackages[i];
|
||||
if (unityPackage.variant && unityPackage.variant !== 'security') {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
unityPackage.platform === 'standalonewindows' &&
|
||||
compareUnityVersion(unityPackage.unitySortNumber, sdkUnityVersion)
|
||||
) {
|
||||
assetUrl = unityPackage.assetUrl;
|
||||
if (!unityPackage.variant || unityPackage.variant === 'standard') {
|
||||
variant = 'security';
|
||||
} else {
|
||||
variant = unityPackage.variant;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!assetUrl) {
|
||||
assetUrl = ref.assetUrl;
|
||||
}
|
||||
const id = extractFileId(assetUrl);
|
||||
const version = parseInt(extractFileVersion(assetUrl), 10);
|
||||
const variantVersion = parseInt(extractVariantVersion(assetUrl), 10);
|
||||
if (!id || !version) {
|
||||
return { Item1: -1, Item2: false, Item3: '' };
|
||||
}
|
||||
|
||||
try {
|
||||
return AssetBundleManager.CheckVRChatCache(
|
||||
id,
|
||||
version,
|
||||
variant,
|
||||
variantVersion
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed reading VRChat cache size:', err);
|
||||
toast.error(`Failed reading VRChat cache size: ${err}`);
|
||||
return { Item1: -1, Item2: false, Item3: '' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {string} message
|
||||
*/
|
||||
function copyToClipboard(text, message = 'Copied successfully!') {
|
||||
navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => {
|
||||
toast.success(message);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Copy failed:', err);
|
||||
toast.error(i18n.global.t('message.copy_failed'));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} url
|
||||
* @param {number} resolution
|
||||
* @param endpointDomain
|
||||
* @returns {string}
|
||||
*/
|
||||
function convertFileUrlToImageUrl(url, resolution = 128, endpointDomain = AppDebug.endpointDomain) {
|
||||
function convertFileUrlToImageUrl(
|
||||
url,
|
||||
resolution = 128,
|
||||
endpointDomain = AppDebug.endpointDomain
|
||||
) {
|
||||
if (!url) {
|
||||
return '';
|
||||
}
|
||||
@@ -183,137 +44,9 @@ function convertFileUrlToImageUrl(url, resolution = 128, endpointDomain = AppDeb
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} link
|
||||
* @param func
|
||||
* @param delay
|
||||
*/
|
||||
function openExternalLink(link) {
|
||||
const searchStore = useSearchStore();
|
||||
if (searchStore.directAccessParse(link)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const modalStore = useModalStore();
|
||||
modalStore
|
||||
.confirm({
|
||||
description: `${link}`,
|
||||
title: 'Open External Link',
|
||||
confirmText: 'Open',
|
||||
cancelText: 'Copy'
|
||||
})
|
||||
.then(({ ok, reason }) => {
|
||||
if (reason === 'cancel') {
|
||||
copyToClipboard(link, 'Link copied to clipboard!');
|
||||
return;
|
||||
}
|
||||
if (ok) {
|
||||
AppApi.OpenLink(link);
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function openDiscordProfile(discordId) {
|
||||
if (!discordId) {
|
||||
toast.error('No Discord ID provided!');
|
||||
return;
|
||||
}
|
||||
AppApi.OpenDiscordProfile(discordId).catch((err) => {
|
||||
console.error('Failed to open Discord profile:', err);
|
||||
toast.error('Failed to open Discord profile!');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} ref
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async function getBundleDateSize(ref) {
|
||||
const authStore = useAuthStore();
|
||||
const sdkUnityVersion = authStore.cachedConfig.sdkUnityVersion;
|
||||
const avatarStore = useAvatarStore();
|
||||
const { avatarDialog } = storeToRefs(avatarStore);
|
||||
const worldStore = useWorldStore();
|
||||
const { worldDialog } = storeToRefs(worldStore);
|
||||
const instanceStore = useInstanceStore();
|
||||
const { currentInstanceWorld, currentInstanceLocation } =
|
||||
storeToRefs(instanceStore);
|
||||
const bundleJson = {};
|
||||
for (let i = ref.unityPackages.length - 1; i > -1; i--) {
|
||||
const unityPackage = ref.unityPackages[i];
|
||||
if (!unityPackage) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
unityPackage.variant &&
|
||||
unityPackage.variant !== 'standard' &&
|
||||
unityPackage.variant !== 'security'
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (!compareUnityVersion(unityPackage.unitySortNumber, sdkUnityVersion)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const platform = unityPackage.platform;
|
||||
if (bundleJson[platform]) {
|
||||
continue;
|
||||
}
|
||||
const assetUrl = unityPackage.assetUrl;
|
||||
const fileId = extractFileId(assetUrl);
|
||||
const version = parseInt(extractFileVersion(assetUrl), 10);
|
||||
let variant = '';
|
||||
if (!unityPackage.variant || unityPackage.variant === 'standard') {
|
||||
variant = 'security';
|
||||
} else {
|
||||
variant = unityPackage.variant;
|
||||
}
|
||||
if (!fileId || !version) {
|
||||
continue;
|
||||
}
|
||||
const args = await queryRequest.fetch('fileAnalysis', {
|
||||
fileId,
|
||||
version,
|
||||
variant
|
||||
});
|
||||
if (!args?.json?.success) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const json = args.json;
|
||||
if (typeof json.fileSize !== 'undefined') {
|
||||
json._fileSize = `${(json.fileSize / 1048576).toFixed(2)} MB`;
|
||||
}
|
||||
if (typeof json.uncompressedSize !== 'undefined') {
|
||||
json._uncompressedSize = `${(json.uncompressedSize / 1048576).toFixed(2)} MB`;
|
||||
}
|
||||
if (typeof json.avatarStats?.totalTextureUsage !== 'undefined') {
|
||||
json._totalTextureUsage = `${(json.avatarStats.totalTextureUsage / 1048576).toFixed(2)} MB`;
|
||||
}
|
||||
bundleJson[platform] = json;
|
||||
|
||||
if (avatarDialog.value.id === ref.id) {
|
||||
// update avatar dialog
|
||||
avatarDialog.value.fileAnalysis[platform] = json;
|
||||
}
|
||||
// update world dialog
|
||||
if (worldDialog.value.id === ref.id) {
|
||||
worldDialog.value.fileAnalysis[platform] = json;
|
||||
}
|
||||
// update player list
|
||||
if (currentInstanceLocation.value.worldId === ref.id) {
|
||||
currentInstanceWorld.value.fileAnalysis[platform] = json;
|
||||
}
|
||||
}
|
||||
|
||||
return bundleJson;
|
||||
}
|
||||
|
||||
// #region | App: Random unsorted app methods, data structs, API functions, and an API feedback/file analysis event
|
||||
|
||||
function openFolderGeneric(path) {
|
||||
AppApi.OpenFolderAndSelectItem(path, true);
|
||||
}
|
||||
|
||||
function debounce(func, delay) {
|
||||
let timer = null;
|
||||
return function (...args) {
|
||||
@@ -325,12 +58,23 @@ function debounce(func, delay) {
|
||||
};
|
||||
}
|
||||
|
||||
// Re-export from appActions and cacheCoordinator for backward compatibility
|
||||
export {
|
||||
getAvailablePlatforms,
|
||||
downloadAndSaveJson,
|
||||
copyToClipboard,
|
||||
openExternalLink,
|
||||
openDiscordProfile,
|
||||
openFolderGeneric
|
||||
} from './appActions';
|
||||
|
||||
export {
|
||||
deleteVRChatCache,
|
||||
checkVRChatCache,
|
||||
copyToClipboard,
|
||||
getBundleDateSize
|
||||
} from '../../coordinators/cacheCoordinator';
|
||||
|
||||
export {
|
||||
getAvailablePlatforms,
|
||||
getFaviconUrl,
|
||||
convertFileUrlToImageUrl,
|
||||
replaceVrcPackageUrl,
|
||||
@@ -338,9 +82,5 @@ export {
|
||||
extractFileVersion,
|
||||
extractVariantVersion,
|
||||
replaceBioSymbols,
|
||||
openExternalLink,
|
||||
openDiscordProfile,
|
||||
getBundleDateSize,
|
||||
openFolderGeneric,
|
||||
debounce
|
||||
};
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { toast } from 'vue-sonner';
|
||||
|
||||
import { $throw } from '../../services/request';
|
||||
import { AppDebug } from '../../services/appConfig.js';
|
||||
import { extractFileId } from './index.js';
|
||||
import { imageRequest } from '../../api';
|
||||
|
||||
const UPLOAD_TIMEOUT_MS = 30_000;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param promise
|
||||
*/
|
||||
export function withUploadTimeout(promise) {
|
||||
return Promise.race([
|
||||
promise,
|
||||
@@ -19,79 +16,6 @@ export function withUploadTimeout(promise) {
|
||||
]);
|
||||
}
|
||||
|
||||
function resolveMessage(message) {
|
||||
if (typeof message === 'function') {
|
||||
return message();
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
function getInputElement(selector) {
|
||||
if (!selector) {
|
||||
return null;
|
||||
}
|
||||
if (typeof selector === 'function') {
|
||||
return selector();
|
||||
}
|
||||
if (typeof selector === 'string') {
|
||||
return document.querySelector(selector);
|
||||
}
|
||||
return selector;
|
||||
}
|
||||
|
||||
export function handleImageUploadInput(event, options = {}) {
|
||||
const {
|
||||
inputSelector,
|
||||
// 20MB
|
||||
maxSize = 20000000,
|
||||
acceptPattern = /image.*/,
|
||||
tooLargeMessage,
|
||||
invalidTypeMessage,
|
||||
onClear
|
||||
} = options;
|
||||
|
||||
const clearInput = () => {
|
||||
onClear?.();
|
||||
const input = getInputElement(inputSelector);
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const files = event?.target?.files || event?.dataTransfer?.files;
|
||||
if (!files || files.length === 0) {
|
||||
clearInput();
|
||||
return { file: null, clearInput };
|
||||
}
|
||||
|
||||
const file = files[0];
|
||||
if (file.size >= maxSize) {
|
||||
if (tooLargeMessage) {
|
||||
toast.error(resolveMessage(tooLargeMessage));
|
||||
}
|
||||
clearInput();
|
||||
return { file: null, clearInput };
|
||||
}
|
||||
|
||||
let acceptRegex = null;
|
||||
if (acceptPattern) {
|
||||
acceptRegex =
|
||||
acceptPattern instanceof RegExp
|
||||
? acceptPattern
|
||||
: new RegExp(acceptPattern);
|
||||
}
|
||||
|
||||
if (acceptRegex && !acceptRegex.test(file.type)) {
|
||||
if (invalidTypeMessage) {
|
||||
toast.error(resolveMessage(invalidTypeMessage));
|
||||
}
|
||||
clearInput();
|
||||
return { file: null, clearInput };
|
||||
}
|
||||
|
||||
return { file, clearInput };
|
||||
}
|
||||
|
||||
/**
|
||||
* File -> base64
|
||||
* @param {Blob|File} blob
|
||||
@@ -113,122 +37,3 @@ export function readFileAsBase64(blob) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export * from './base/array';
|
||||
export * from './base/devtool';
|
||||
export * from './base/format';
|
||||
export * from './base/date';
|
||||
export { formatDateFilter } from '../../coordinators/dateCoordinator';
|
||||
export * from './base/string';
|
||||
export * from './avatar';
|
||||
export * from './chart';
|
||||
@@ -20,7 +20,6 @@ export * from './gallery';
|
||||
export * from './location';
|
||||
export * from './invite';
|
||||
export * from './world';
|
||||
export * from './memos';
|
||||
export * from './throttle';
|
||||
export * from './retry';
|
||||
export * from './gameLog';
|
||||
|
||||
@@ -1,20 +1,3 @@
|
||||
import { instanceRequest } from '../../api';
|
||||
import { parseLocation } from './locationParser';
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} instance
|
||||
*/
|
||||
function refreshInstancePlayerCount(instance) {
|
||||
const L = parseLocation(instance);
|
||||
if (L.isRealInstance) {
|
||||
instanceRequest.getInstance({
|
||||
worldId: L.worldId,
|
||||
instanceId: L.instanceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} instanceId
|
||||
@@ -131,9 +114,4 @@ function buildLegacyInstanceTag({
|
||||
return tags.join('');
|
||||
}
|
||||
|
||||
export {
|
||||
refreshInstancePlayerCount,
|
||||
isRealInstance,
|
||||
getLaunchURL,
|
||||
buildLegacyInstanceTag
|
||||
};
|
||||
export { isRealInstance, getLaunchURL, buildLegacyInstanceTag };
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
import { useFriendStore, useUserStore } from '../../stores';
|
||||
import { database } from '../../services/database';
|
||||
|
||||
/**
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function migrateMemos() {
|
||||
const json = JSON.parse(await VRCXStorage.GetAll());
|
||||
for (const line in json) {
|
||||
if (line.substring(0, 8) === 'memo_usr') {
|
||||
const userId = line.substring(5);
|
||||
const memo = json[line];
|
||||
if (memo) {
|
||||
await saveUserMemo(userId, memo);
|
||||
VRCXStorage.Remove(`memo_${userId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} userId
|
||||
* @returns
|
||||
*/
|
||||
async function getUserMemo(userId) {
|
||||
try {
|
||||
return await database.getUserMemo(userId);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return {
|
||||
userId: '',
|
||||
editedAt: '',
|
||||
memo: ''
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @param {string} memo
|
||||
*/
|
||||
async function saveUserMemo(id, memo) {
|
||||
const friendStore = useFriendStore();
|
||||
const userStore = useUserStore();
|
||||
if (memo) {
|
||||
await database.setUserMemo({
|
||||
userId: id,
|
||||
editedAt: new Date().toJSON(),
|
||||
memo
|
||||
});
|
||||
} else {
|
||||
await database.deleteUserMemo(id);
|
||||
}
|
||||
const ref = friendStore.friends.get(id);
|
||||
if (ref) {
|
||||
ref.memo = String(memo || '');
|
||||
if (memo) {
|
||||
const array = memo.split('\n');
|
||||
ref.$nickName = array[0];
|
||||
} else {
|
||||
ref.$nickName = '';
|
||||
}
|
||||
userStore.setUserDialogMemo(memo);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function getAllUserMemos() {
|
||||
const friendStore = useFriendStore();
|
||||
const memos = await database.getAllUserMemos();
|
||||
memos.forEach((memo) => {
|
||||
const ref = friendStore.friends.get(memo.userId);
|
||||
if (typeof ref !== 'undefined') {
|
||||
ref.memo = memo.memo;
|
||||
ref.$nickName = '';
|
||||
if (memo.memo) {
|
||||
const array = memo.memo.split('\n');
|
||||
ref.$nickName = array[0];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} worldId
|
||||
* @returns
|
||||
*/
|
||||
async function getWorldMemo(worldId) {
|
||||
try {
|
||||
return await database.getWorldMemo(worldId);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return {
|
||||
worldId: '',
|
||||
editedAt: '',
|
||||
memo: ''
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// async function getAvatarMemo(avatarId) {
|
||||
// try {
|
||||
// return await database.getAvatarMemoDB(avatarId);
|
||||
// } catch (err) {
|
||||
// console.error(err);
|
||||
// return {
|
||||
// avatarId: '',
|
||||
// editedAt: '',
|
||||
// memo: ''
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
export {
|
||||
migrateMemos,
|
||||
getUserMemo,
|
||||
saveUserMemo,
|
||||
getAllUserMemos,
|
||||
getWorldMemo
|
||||
// getAvatarMemo
|
||||
};
|
||||
Reference in New Issue
Block a user