feat: migrate to vue 3 (#2689)

---------

Co-authored-by: Joep <jcbuhre@gmail.com>
Co-authored-by: Omar Hussein <omarmohammad1951@gmail.com>
Co-authored-by: Oleg Lobanov <oleg@lobanov.me>
This commit is contained in:
kloon15
2024-04-01 17:18:22 +02:00
committed by GitHub
parent 0e3b35b30e
commit 5100e587d7
164 changed files with 12202 additions and 8047 deletions

View File

@@ -1,25 +1,25 @@
<template>
<errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading">
<div class="row" v-else-if="!layoutStore.loading && settings !== null">
<div class="column">
<form class="card" @submit.prevent="save">
<div class="card-title">
<h2>{{ $t("settings.globalSettings") }}</h2>
<h2>{{ t("settings.globalSettings") }}</h2>
</div>
<div class="card-content">
<p>
<input type="checkbox" v-model="settings.signup" />
{{ $t("settings.allowSignup") }}
{{ t("settings.allowSignup") }}
</p>
<p>
<input type="checkbox" v-model="settings.createUserDir" />
{{ $t("settings.createUserDir") }}
{{ t("settings.createUserDir") }}
</p>
<div>
<p class="small">{{ $t("settings.userHomeBasePath") }}</p>
<p class="small">{{ t("settings.userHomeBasePath") }}</p>
<input
class="input input--block"
type="text"
@@ -27,31 +27,36 @@
/>
</div>
<h3>{{ $t("settings.rules") }}</h3>
<p class="small">{{ $t("settings.globalRules") }}</p>
<rules :rules.sync="settings.rules" />
<h3>{{ t("settings.rules") }}</h3>
<p class="small">{{ t("settings.globalRules") }}</p>
<rules v-model:rules="settings.rules" />
<div v-if="isExecEnabled">
<h3>{{ $t("settings.executeOnShell") }}</h3>
<p class="small">{{ $t("settings.executeOnShellDescription") }}</p>
<div v-if="enableExec">
<h3>{{ t("settings.executeOnShell") }}</h3>
<p class="small">{{ t("settings.executeOnShellDescription") }}</p>
<input
class="input input--block"
type="text"
placeholder="bash -c, cmd /c, ..."
v-model="settings.shell"
v-model="shellValue"
/>
</div>
<h3>{{ $t("settings.branding") }}</h3>
<h3>{{ t("settings.branding") }}</h3>
<i18n path="settings.brandingHelp" tag="p" class="small">
<i18n-t
keypath="settings.brandingHelp"
tag="p"
class="small"
scope="global"
>
<a
class="link"
target="_blank"
href="https://filebrowser.org/configuration/custom-branding"
>{{ $t("settings.documentation") }}</a
>{{ t("settings.documentation") }}</a
>
</i18n>
</i18n-t>
<p>
<input
@@ -59,7 +64,7 @@
v-model="settings.branding.disableExternal"
id="branding-links"
/>
{{ $t("settings.disableExternalLinks") }}
{{ t("settings.disableExternalLinks") }}
</p>
<p>
@@ -68,20 +73,20 @@
v-model="settings.branding.disableUsedPercentage"
id="branding-links"
/>
{{ $t("settings.disableUsedDiskPercentage") }}
{{ t("settings.disableUsedDiskPercentage") }}
</p>
<p>
<label for="theme">{{ $t("settings.themes.title") }}</label>
<label for="theme">{{ t("settings.themes.title") }}</label>
<themes
class="input input--block"
:theme.sync="settings.branding.theme"
v-model:theme="settings.branding.theme"
id="theme"
></themes>
</p>
<p>
<label for="branding-name">{{ $t("settings.instanceName") }}</label>
<label for="branding-name">{{ t("settings.instanceName") }}</label>
<input
class="input input--block"
type="text"
@@ -92,7 +97,7 @@
<p>
<label for="branding-files">{{
$t("settings.brandingDirectoryPath")
t("settings.brandingDirectoryPath")
}}</label>
<input
class="input input--block"
@@ -102,14 +107,14 @@
/>
</p>
<h3>{{ $t("settings.tusUploads") }}</h3>
<h3>{{ t("settings.tusUploads") }}</h3>
<p class="small">{{ $t("settings.tusUploadsHelp") }}</p>
<p class="small">{{ t("settings.tusUploadsHelp") }}</p>
<div class="tusConditionalSettings">
<p>
<label for="tus-chunkSize">{{
$t("settings.tusUploadsChunkSize")
t("settings.tusUploadsChunkSize")
}}</label>
<input
class="input input--block"
@@ -121,14 +126,13 @@
<p>
<label for="tus-retryCount">{{
$t("settings.tusUploadsRetryCount")
t("settings.tusUploadsRetryCount")
}}</label>
<input
class="input input--block"
type="number"
<vue-number-input
controls
v-model.number="settings.tus.retryCount"
id="tus-retryCount"
min="0"
:min="0"
/>
</p>
</div>
@@ -138,7 +142,7 @@
<input
class="button button--flat"
type="submit"
:value="$t('buttons.update')"
:value="t('buttons.update')"
/>
</div>
</form>
@@ -147,16 +151,16 @@
<div class="column">
<form class="card" @submit.prevent="save">
<div class="card-title">
<h2>{{ $t("settings.userDefaults") }}</h2>
<h2>{{ t("settings.userDefaults") }}</h2>
</div>
<div class="card-content">
<p class="small">{{ $t("settings.defaultUserDescription") }}</p>
<p class="small">{{ t("settings.defaultUserDescription") }}</p>
<user-form
:isNew="false"
:isDefault="true"
:user.sync="settings.defaults"
v-model:user="settings.defaults"
/>
</div>
@@ -164,44 +168,49 @@
<input
class="button button--flat"
type="submit"
:value="$t('buttons.update')"
:value="t('buttons.update')"
/>
</div>
</form>
</div>
<div class="column">
<form v-if="isExecEnabled" class="card" @submit.prevent="save">
<form v-if="enableExec" class="card" @submit.prevent="save">
<div class="card-title">
<h2>{{ $t("settings.commandRunner") }}</h2>
<h2>{{ t("settings.commandRunner") }}</h2>
</div>
<div class="card-content">
<i18n path="settings.commandRunnerHelp" tag="p" class="small">
<i18n-t
keypath="settings.commandRunnerHelp"
tag="p"
class="small"
scope="global"
>
<code>FILE</code>
<code>SCOPE</code>
<a
class="link"
target="_blank"
href="https://filebrowser.org/configuration/command-runner"
>{{ $t("settings.documentation") }}</a
>{{ t("settings.documentation") }}</a
>
</i18n>
</i18n-t>
<div
v-for="command in settings.commands"
:key="command.name"
v-for="(command, key) in settings.commands"
:key="key"
class="collapsible"
>
<input :id="command.name" type="checkbox" />
<label :for="command.name">
<p>{{ capitalize(command.name) }}</p>
<input :id="key" type="checkbox" />
<label :for="key">
<p>{{ capitalize(key) }}</p>
<i class="material-icons">arrow_drop_down</i>
</label>
<div class="collapse">
<textarea
class="input input--block input--textarea"
v-model.trim="command.value"
v-model.trim="commandObject[key]"
></textarea>
</div>
</div>
@@ -211,7 +220,7 @@
<input
class="button button--flat"
type="submit"
:value="$t('buttons.update')"
:value="t('buttons.update')"
/>
</div>
</form>
@@ -219,150 +228,178 @@
</div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
<script setup lang="ts">
import { useLayoutStore } from "@/stores/layout";
import { settings as api } from "@/api";
import { enableExec } from "@/utils/constants";
import UserForm from "@/components/settings/UserForm.vue";
import Rules from "@/components/settings/Rules.vue";
import Themes from "@/components/settings/Themes.vue";
import Errors from "@/views/Errors.vue";
import { computed, inject, onBeforeUnmount, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { StatusError } from "@/api/utils";
import { getTheme, setTheme } from "@/utils/theme";
export default {
name: "settings",
components: {
Themes,
UserForm,
Rules,
Errors,
const error = ref<StatusError | null>(null);
const originalSettings = ref<ISettings | null>(null);
const settings = ref<ISettings | null>(null);
const debounceTimeout = ref<number | null>(null);
const commandObject = ref<{
[key: string]: string[] | string;
}>({});
const shellValue = ref<string>("");
const $showError = inject<IToastError>("$showError")!;
const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
const { t } = useI18n();
const layoutStore = useLayoutStore();
const formattedChunkSize = computed({
get() {
return settings?.value?.tus?.chunkSize
? formatBytes(settings?.value?.tus?.chunkSize)
: "";
},
data: function () {
return {
error: null,
originalSettings: null,
settings: null,
debounceTimeout: null,
};
},
computed: {
...mapState(["user", "loading"]),
isExecEnabled: () => enableExec,
formattedChunkSize: {
get() {
return this.formatBytes(this.settings.tus.chunkSize);
},
set(value) {
// Use debouncing to allow the user to type freely without
// interruption by the formatter
// Clear the previous timeout if it exists
if (this.debounceTimeout) {
clearTimeout(this.debounceTimeout);
}
// Set a new timeout to apply the format after a short delay
this.debounceTimeout = setTimeout(() => {
this.settings.tus.chunkSize = this.parseBytes(value);
}, 1500);
},
},
},
async created() {
try {
this.setLoading(true);
const original = await api.get();
let settings = { ...original, commands: [] };
for (const key in original.commands) {
settings.commands.push({
name: key,
value: original.commands[key].join("\n"),
});
}
settings.shell = settings.shell.join(" ");
this.originalSettings = original;
this.settings = settings;
} catch (e) {
this.error = e;
} finally {
this.setLoading(false);
set(value: string) {
// Use debouncing to allow the user to type freely without
// interruption by the formatter
// Clear the previous timeout if it exists
if (debounceTimeout.value) {
clearTimeout(debounceTimeout.value);
}
// Set a new timeout to apply the format after a short delay
debounceTimeout.value = setTimeout(() => {
if (settings.value) settings.value.tus.chunkSize = parseBytes(value);
}, 1500);
},
methods: {
...mapMutations(["setLoading"]),
capitalize(name, where = "_") {
if (where === "caps") where = /(?=[A-Z])/;
let splitted = name.split(where);
name = "";
});
for (let i = 0; i < splitted.length; i++) {
name +=
splitted[i].charAt(0).toUpperCase() + splitted[i].slice(1) + " ";
}
// Define funcs
const capitalize = (name: string, where: string | RegExp = "_") => {
if (where === "caps") where = /(?=[A-Z])/;
let splitted = name.split(where);
name = "";
return name.slice(0, -1);
},
async save() {
let settings = {
...this.settings,
shell: this.settings.shell
.trim()
.split(" ")
.filter((s) => s !== ""),
commands: {},
};
for (let i = 0; i < splitted.length; i++) {
name += splitted[i].charAt(0).toUpperCase() + splitted[i].slice(1) + " ";
}
for (const { name, value } of this.settings.commands) {
settings.commands[name] = value.split("\n").filter((cmd) => cmd !== "");
}
try {
await api.update(settings);
this.$showSuccess(this.$t("settings.settingsUpdated"));
} catch (e) {
this.$showError(e);
}
},
// Parse the user-friendly input (e.g., "20M" or "1T") to bytes
parseBytes(input) {
const regex = /^(\d+)(\.\d+)?(B|K|KB|M|MB|G|GB|T|TB)?$/i;
const matches = input.match(regex);
if (matches) {
const size = parseFloat(matches[1].concat(matches[2] || ""));
let unit = matches[3].toUpperCase();
if (!unit.endsWith("B")) {
unit += "B";
}
const units = {
KB: 1024,
MB: 1024 ** 2,
GB: 1024 ** 3,
TB: 1024 ** 4,
};
return size * (units[unit] || 1);
} else {
return 1024 ** 2;
}
},
// Format the chunk size in bytes to user-friendly format
formatBytes(bytes) {
const units = ["B", "KB", "MB", "GB", "TB"];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size}${units[unitIndex]}`;
},
// Clear the debounce timeout when the component is destroyed
beforeDestroy() {
if (this.debounceTimeout) {
clearTimeout(this.debounceTimeout);
}
},
},
return name.slice(0, -1);
};
const save = async () => {
if (settings.value === null) return false;
let newSettings: ISettings = {
...settings.value,
shell:
settings.value?.shell
.join(" ")
.trim()
.split(" ")
.filter((s: string) => s !== "") ?? [],
commands: {},
};
const keys = Object.keys(settings.value.commands) as Array<
keyof SettingsCommand
>;
for (const key of keys) {
// not sure if we can safely assume non-null
const newValue = commandObject.value[key];
if (!newValue) continue;
if (Array.isArray(newValue)) {
newSettings.commands[key] = newValue;
} else if (key in commandObject.value) {
newSettings.commands[key] = newValue
.split("\n")
.filter((cmd: string) => cmd !== "");
}
}
newSettings.shell = shellValue.value.split("\n");
if (newSettings.branding.theme !== getTheme()) {
setTheme(newSettings.branding.theme);
}
try {
await api.update(newSettings);
$showSuccess(t("settings.settingsUpdated"));
} catch (e: any) {
$showError(e);
}
return true;
};
// Parse the user-friendly input (e.g., "20M" or "1T") to bytes
const parseBytes = (input: string) => {
const regex = /^(\d+)(\.\d+)?(B|K|KB|M|MB|G|GB|T|TB)?$/i;
const matches = input.match(regex);
if (matches) {
const size = parseFloat(matches[1].concat(matches[2] || ""));
let unit: keyof SettingsUnit =
matches[3].toUpperCase() as keyof SettingsUnit;
if (!unit.endsWith("B")) {
unit += "B";
}
const units: SettingsUnit = {
KB: 1024,
MB: 1024 ** 2,
GB: 1024 ** 3,
TB: 1024 ** 4,
};
return size * (units[unit as keyof SettingsUnit] || 1);
} else {
return 1024 ** 2;
}
};
// Format the chunk size in bytes to user-friendly format
const formatBytes = (bytes: number) => {
const units = ["B", "KB", "MB", "GB", "TB"];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size}${units[unitIndex]}`;
};
// Define Hooks
onMounted(async () => {
try {
layoutStore.loading = true;
const original: ISettings = await api.get();
let newSettings: ISettings = { ...original, commands: {} };
const keys = Object.keys(original.commands) as Array<keyof SettingsCommand>;
for (const key of keys) {
newSettings.commands[key] = original.commands[key];
commandObject.value[key] = original.commands[key]!.join("\n");
}
originalSettings.value = original;
settings.value = newSettings;
shellValue.value = newSettings.shell.join("\n");
} catch (err) {
if (err instanceof Error) {
error.value = err;
}
} finally {
layoutStore.loading = false;
}
});
// Clear the debounce timeout when the component is destroyed
onBeforeUnmount(() => {
if (debounceTimeout.value) {
clearTimeout(debounceTimeout.value);
}
});
</script>

View File

@@ -3,26 +3,26 @@
<div class="column">
<form class="card" @submit="updateSettings">
<div class="card-title">
<h2>{{ $t("settings.profileSettings") }}</h2>
<h2>{{ t("settings.profileSettings") }}</h2>
</div>
<div class="card-content">
<p>
<input type="checkbox" v-model="hideDotfiles" />
{{ $t("settings.hideDotfiles") }}
<input type="checkbox" name="hideDotfiles" v-model="hideDotfiles" />
{{ t("settings.hideDotfiles") }}
</p>
<p>
<input type="checkbox" v-model="singleClick" />
{{ $t("settings.singleClick") }}
<input type="checkbox" name="singleClick" v-model="singleClick" />
{{ t("settings.singleClick") }}
</p>
<p>
<input type="checkbox" v-model="dateFormat" />
{{ $t("settings.setDateFormat") }}
<input type="checkbox" name="dateFormat" v-model="dateFormat" />
{{ t("settings.setDateFormat") }}
</p>
<h3>{{ $t("settings.language") }}</h3>
<h3>{{ t("settings.language") }}</h3>
<languages
class="input input--block"
:locale.sync="locale"
v-model:locale="locale"
></languages>
</div>
@@ -30,32 +30,37 @@
<input
class="button button--flat"
type="submit"
:value="$t('buttons.update')"
name="submitProfile"
:value="t('buttons.update')"
/>
</div>
</form>
</div>
<div class="column">
<form class="card" v-if="!user.lockPassword" @submit="updatePassword">
<form
class="card"
v-if="!authStore.user?.lockPassword"
@submit="updatePassword"
>
<div class="card-title">
<h2>{{ $t("settings.changePassword") }}</h2>
<h2>{{ t("settings.changePassword") }}</h2>
</div>
<div class="card-content">
<input
:class="passwordClass"
type="password"
:placeholder="$t('settings.newPassword')"
:placeholder="t('settings.newPassword')"
v-model="password"
name="password"
/>
<input
:class="passwordClass"
type="password"
:placeholder="$t('settings.newPasswordConfirm')"
:placeholder="t('settings.newPasswordConfirm')"
v-model="passwordConf"
name="password"
name="passwordConf"
/>
</div>
@@ -63,7 +68,8 @@
<input
class="button button--flat"
type="submit"
:value="$t('buttons.update')"
name="submitPassword"
:value="t('buttons.update')"
/>
</div>
</form>
@@ -71,97 +77,106 @@
</div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
<script setup lang="ts">
import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout";
import { users as api } from "@/api";
import Languages from "@/components/settings/Languages.vue";
import i18n, { rtlLanguages } from "@/i18n";
import { computed, inject, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
export default {
name: "settings",
components: {
Languages,
},
data: function () {
return {
password: "",
passwordConf: "",
hideDotfiles: false,
singleClick: false,
dateFormat: false,
locale: "",
const layoutStore = useLayoutStore();
const authStore = useAuthStore();
const { t } = useI18n();
const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
const $showError = inject<IToastError>("$showError")!;
const password = ref<string>("");
const passwordConf = ref<string>("");
const hideDotfiles = ref<boolean>(false);
const singleClick = ref<boolean>(false);
const dateFormat = ref<boolean>(false);
const locale = ref<string>("");
const passwordClass = computed(() => {
const baseClass = "input input--block";
if (password.value === "" && passwordConf.value === "") {
return baseClass;
}
if (password.value === passwordConf.value) {
return `${baseClass} input--green`;
}
return `${baseClass} input--red`;
});
onMounted(() => {
layoutStore.loading = true;
if (authStore.user === null) return false;
locale.value = authStore.user.locale;
hideDotfiles.value = authStore.user.hideDotfiles;
singleClick.value = authStore.user.singleClick;
dateFormat.value = authStore.user.dateFormat;
layoutStore.loading = false;
return true;
});
const updatePassword = async (event: Event) => {
event.preventDefault();
if (
password.value !== passwordConf.value ||
password.value === "" ||
authStore.user === null
) {
return;
}
try {
const data = {
...authStore.user,
id: authStore.user.id,
password: password.value,
};
},
computed: {
...mapState(["user"]),
passwordClass() {
const baseClass = "input input--block";
await api.update(data, ["password"]);
authStore.updateUser(data);
$showSuccess(t("settings.passwordUpdated"));
} catch (e: any) {
$showError(e);
} finally {
password.value = passwordConf.value = "";
}
};
const updateSettings = async (event: Event) => {
event.preventDefault();
if (this.password === "" && this.passwordConf === "") {
return baseClass;
}
try {
if (authStore.user === null) throw new Error("User is not set!");
if (this.password === this.passwordConf) {
return `${baseClass} input--green`;
}
const data = {
...authStore.user,
id: authStore.user.id,
locale: locale.value,
hideDotfiles: hideDotfiles.value,
singleClick: singleClick.value,
dateFormat: dateFormat.value,
};
return `${baseClass} input--red`;
},
},
created() {
this.setLoading(false);
this.locale = this.user.locale;
this.hideDotfiles = this.user.hideDotfiles;
this.singleClick = this.user.singleClick;
this.dateFormat = this.user.dateFormat;
},
methods: {
...mapMutations(["updateUser", "setLoading"]),
async updatePassword(event) {
event.preventDefault();
if (this.password !== this.passwordConf || this.password === "") {
return;
}
try {
const data = { id: this.user.id, password: this.password };
await api.update(data, ["password"]);
this.updateUser(data);
this.$showSuccess(this.$t("settings.passwordUpdated"));
} catch (e) {
this.$showError(e);
}
},
async updateSettings(event) {
event.preventDefault();
try {
const data = {
id: this.user.id,
locale: this.locale,
hideDotfiles: this.hideDotfiles,
singleClick: this.singleClick,
dateFormat: this.dateFormat,
};
const shouldReload =
rtlLanguages.includes(data.locale) !==
rtlLanguages.includes(i18n.locale);
await api.update(data, [
"locale",
"hideDotfiles",
"singleClick",
"dateFormat",
]);
this.updateUser(data);
if (shouldReload) {
location.reload();
}
this.$showSuccess(this.$t("settings.settingsUpdated"));
} catch (e) {
this.$showError(e);
}
},
},
await api.update(data, [
"locale",
"hideDotfiles",
"singleClick",
"dateFormat",
]);
authStore.updateUser(data);
$showSuccess(t("settings.settingsUpdated"));
} catch (err) {
if (err instanceof Error) {
$showError(err);
}
}
};
</script>

View File

@@ -1,18 +1,20 @@
<template>
<errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading">
<div class="row" v-else-if="!layoutStore.loading">
<div class="column">
<div class="card">
<div class="card-title">
<h2>{{ $t("settings.shareManagement") }}</h2>
<h2>{{ t("settings.shareManagement") }}</h2>
</div>
<div class="card-content full" v-if="links.length > 0">
<table>
<tr>
<th>{{ $t("settings.path") }}</th>
<th>{{ $t("settings.shareDuration") }}</th>
<th v-if="user.perm.admin">{{ $t("settings.username") }}</th>
<th>{{ t("settings.path") }}</th>
<th>{{ t("settings.shareDuration") }}</th>
<th v-if="authStore.user?.perm.admin">
{{ t("settings.username") }}
</th>
<th></th>
<th></th>
</tr>
@@ -25,15 +27,15 @@
<template v-if="link.expire !== 0">{{
humanTime(link.expire)
}}</template>
<template v-else>{{ $t("permanent") }}</template>
<template v-else>{{ t("permanent") }}</template>
</td>
<td v-if="user.perm.admin">{{ link.username }}</td>
<td v-if="authStore.user?.perm.admin">{{ link.username }}</td>
<td class="small">
<button
class="action"
@click="deleteLink($event, link)"
:aria-label="$t('buttons.delete')"
:title="$t('buttons.delete')"
:aria-label="t('buttons.delete')"
:title="t('buttons.delete')"
>
<i class="material-icons">delete</i>
</button>
@@ -41,9 +43,9 @@
<td class="small">
<button
class="action copy-clipboard"
:data-clipboard-text="buildLink(link)"
:aria-label="$t('buttons.copyToClipboard')"
:title="$t('buttons.copyToClipboard')"
:aria-label="t('buttons.copyToClipboard')"
:title="t('buttons.copyToClipboard')"
@click="copyToClipboard(buildLink(link))"
>
<i class="material-icons">content_paste</i>
</button>
@@ -53,89 +55,95 @@
</div>
<h2 class="message" v-else>
<i class="material-icons">sentiment_dissatisfied</i>
<span>{{ $t("files.lonely") }}</span>
<span>{{ t("files.lonely") }}</span>
</h2>
</div>
</div>
</div>
</template>
<script>
<script setup lang="ts">
import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout";
import { share as api, users } from "@/api";
import { mapState, mapMutations } from "vuex";
import moment from "moment/min/moment-with-locales";
import Clipboard from "clipboard";
import dayjs from "dayjs";
import Errors from "@/views/Errors.vue";
import { inject, ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { StatusError } from "@/api/utils";
import { copy } from "@/utils/clipboard";
export default {
name: "shares",
components: {
Errors,
},
computed: mapState(["user", "loading"]),
data: function () {
return {
error: null,
links: [],
clip: null,
};
},
async created() {
this.setLoading(true);
const $showError = inject<IToastError>("$showError")!;
const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
const { t } = useI18n();
try {
let links = await api.list();
if (this.user.perm.admin) {
let userMap = new Map();
for (let user of await users.getAll())
userMap.set(user.id, user.username);
for (let link of links)
link.username = userMap.has(link.userID)
? userMap.get(link.userID)
: "";
const layoutStore = useLayoutStore();
const authStore = useAuthStore();
const error = ref<StatusError | null>(null);
const links = ref<Share[]>([]);
onMounted(async () => {
layoutStore.loading = true;
try {
let newLinks = await api.list();
if (authStore.user?.perm.admin) {
let userMap = new Map<number, string>();
for (let user of await users.getAll())
userMap.set(user.id, user.username);
for (let link of newLinks) {
if (link.userID && userMap.has(link.userID))
link.username = userMap.get(link.userID);
}
this.links = links;
} catch (e) {
this.error = e;
} finally {
this.setLoading(false);
}
},
mounted() {
this.clip = new Clipboard(".copy-clipboard");
this.clip.on("success", () => {
this.$showSuccess(this.$t("success.linkCopied"));
});
},
beforeDestroy() {
this.clip.destroy();
},
methods: {
...mapMutations(["setLoading"]),
deleteLink: async function (event, link) {
event.preventDefault();
links.value = newLinks;
} catch (err) {
if (err instanceof Error) {
error.value = err;
}
} finally {
layoutStore.loading = false;
}
});
this.$store.commit("showHover", {
prompt: "share-delete",
confirm: () => {
this.$store.commit("closeHovers");
const copyToClipboard = (text: string) => {
copy(text).then(
() => {
// clipboard successfully set
$showSuccess(t("success.linkCopied"));
},
() => {
// clipboard write failed
}
);
};
try {
api.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash);
this.$showSuccess(this.$t("settings.shareDeleted"));
} catch (e) {
this.$showError(e);
}
},
});
const deleteLink = async (event: Event, link: any) => {
event.preventDefault();
layoutStore.showHover({
prompt: "share-delete",
confirm: () => {
layoutStore.closeHovers();
try {
api.remove(link.hash);
links.value = links.value.filter((item) => item.hash !== link.hash);
$showSuccess(t("settings.shareDeleted"));
} catch (err) {
if (err instanceof Error) {
$showError(err);
}
}
},
humanTime(time) {
return moment(time * 1000).fromNow();
},
buildLink(share) {
return api.getShareURL(share);
},
},
});
};
const humanTime = (time: number) => {
return dayjs(time * 1000).fromNow();
};
const buildLink = (share: Share) => {
return api.getShareURL(share);
};
</script>

View File

@@ -1,17 +1,17 @@
<template>
<errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading">
<div class="row" v-else-if="!layoutStore.loading">
<div class="column">
<form @submit="save" class="card">
<div class="card-title">
<h2 v-if="user.id === 0">{{ $t("settings.newUser") }}</h2>
<h2 v-else>{{ $t("settings.user") }} {{ user.username }}</h2>
<h2 v-if="user?.id === 0">{{ $t("settings.newUser") }}</h2>
<h2 v-else>{{ $t("settings.user") }} {{ user?.username }}</h2>
</div>
<div class="card-content">
<div class="card-content" v-if="user">
<user-form
:user.sync="user"
:createUserDir.sync="createUserDir"
v-model:user="user"
v-model:createUserDir="createUserDir"
:isDefault="false"
:isNew="isNew"
/>
@@ -28,6 +28,15 @@
>
{{ $t("buttons.delete") }}
</button>
<router-link to="/settings/users">
<button
class="button button--flat button--grey"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
{{ $t("buttons.cancel") }}
</button>
</router-link>
<input
class="button button--flat"
type="submit"
@@ -36,136 +45,128 @@
</div>
</form>
</div>
<div v-if="this.currentPromptName === 'deleteUser'" class="card floating">
<div class="card-content">
<p>Are you sure you want to delete this user?</p>
</div>
<div class="card-action">
<button
class="button button--flat button--grey"
@click="closeHovers"
v-focus
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
{{ $t("buttons.cancel") }}
</button>
<button class="button button--flat" @click="deleteUser">
{{ $t("buttons.delete") }}
</button>
</div>
</div>
</div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from "vuex";
<script setup lang="ts">
import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout";
import { users as api, settings } from "@/api";
import UserForm from "@/components/settings/UserForm.vue";
import Errors from "@/views/Errors.vue";
import deepClone from "lodash.clonedeep";
import { computed, inject, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { StatusError } from "@/api/utils";
export default {
name: "user",
components: {
UserForm,
Errors,
},
data: () => {
return {
error: null,
originalUser: null,
user: {},
createUserDir: false,
};
},
created() {
this.fetchData();
},
computed: {
isNew() {
return this.$route.path === "/settings/users/new";
},
...mapState(["loading"]),
...mapGetters(["currentPrompt", "currentPromptName"]),
},
watch: {
$route: "fetchData",
"user.perm.admin": function () {
if (!this.user.perm.admin) return;
this.user.lockPassword = false;
},
},
methods: {
...mapMutations(["closeHovers", "showHover", "setUser", "setLoading"]),
async fetchData() {
this.setLoading(true);
const error = ref<StatusError>();
const originalUser = ref<IUser>();
const user = ref<IUser>();
const createUserDir = ref<boolean>(false);
try {
if (this.isNew) {
let { defaults, createUserDir } = await settings.get();
this.createUserDir = createUserDir;
this.user = {
...defaults,
username: "",
password: "",
rules: [],
lockPassword: false,
id: 0,
};
} else {
const id = this.$route.params.pathMatch;
this.user = { ...(await api.get(id)) };
}
} catch (e) {
this.error = e;
} finally {
this.setLoading(false);
}
},
deletePrompt() {
this.showHover("deleteUser");
},
async deleteUser(event) {
event.preventDefault();
const $showError = inject<IToastError>("$showError")!;
const $showSuccess = inject<IToastSuccess>("$showSuccess")!;
try {
await api.remove(this.user.id);
this.$router.push({ path: "/settings/users" });
this.$showSuccess(this.$t("settings.userDeleted"));
} catch (e) {
e.message === "403"
? this.$showError(this.$t("errors.forbidden"), false)
: this.$showError(e);
}
},
async save(event) {
event.preventDefault();
let user = {
...this.originalUser,
...this.user,
const authStore = useAuthStore();
const layoutStore = useLayoutStore();
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
onMounted(() => {
fetchData();
});
const isNew = computed(() => route.path === "/settings/users/new");
watch(route, () => fetchData());
watch(user, () => {
if (!user.value?.perm.admin) return;
user.value.lockPassword = false;
});
const fetchData = async () => {
layoutStore.loading = true;
try {
if (isNew.value) {
let { defaults, createUserDir: _createUserDir } = await settings.get();
createUserDir.value = _createUserDir;
user.value = {
...defaults,
username: "",
password: "",
rules: [],
lockPassword: false,
id: 0,
};
} else {
const id = Array.isArray(route.params.id)
? route.params.id.join("")
: route.params.id;
user.value = { ...(await api.get(parseInt(id))) };
}
} catch (err) {
if (err instanceof Error) {
error.value = err;
}
} finally {
layoutStore.loading = false;
}
};
const deletePrompt = () =>
layoutStore.showHover({ prompt: "deleteUser", confirm: deleteUser });
const deleteUser = async (e: Event) => {
e.preventDefault();
if (!user.value) {
return false;
}
try {
await api.remove(user.value.id);
router.push({ path: "/settings/users" });
$showSuccess(t("settings.userDeleted"));
} catch (err) {
if (err instanceof StatusError) {
err.status === 403 ? $showError(t("errors.forbidden")) : $showError(err);
} else if (err instanceof Error) {
$showError(err);
}
}
return true;
};
const save = async (event: Event) => {
event.preventDefault();
if (!user.value) {
return false;
}
try {
if (isNew.value) {
const newUser: IUser = {
...originalUser?.value,
...user.value,
};
try {
if (this.isNew) {
const loc = await api.create(user);
this.$router.push({ path: loc });
this.$showSuccess(this.$t("settings.userCreated"));
} else {
await api.update(user);
const loc = await api.create(newUser);
router.push({ path: loc || "/settings/users" });
$showSuccess(t("settings.userCreated"));
} else {
await api.update(user.value);
if (user.id === this.$store.state.user.id) {
this.setUser({ ...deepClone(user) });
}
this.$showSuccess(this.$t("settings.userUpdated"));
}
} catch (e) {
this.$showError(e);
if (user.value.id === authStore.user?.id) {
authStore.updateUser(user.value);
}
},
},
$showSuccess(t("settings.userUpdated"));
}
} catch (e: any) {
$showError(e);
}
return true;
};
</script>

View File

@@ -1,13 +1,13 @@
<template>
<errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading">
<div class="row" v-else-if="!layoutStore.loading">
<div class="column">
<div class="card">
<div class="card-title">
<h2>{{ $t("settings.users") }}</h2>
<h2>{{ t("settings.users") }}</h2>
<router-link to="/settings/users/new"
><button class="button">
{{ $t("buttons.new") }}
{{ t("buttons.new") }}
</button></router-link
>
</div>
@@ -15,9 +15,9 @@
<div class="card-content full">
<table>
<tr>
<th>{{ $t("settings.username") }}</th>
<th>{{ $t("settings.admin") }}</th>
<th>{{ $t("settings.scope") }}</th>
<th>{{ t("settings.username") }}</th>
<th>{{ t("settings.admin") }}</th>
<th>{{ t("settings.scope") }}</th>
<th></th>
</tr>
@@ -41,38 +41,31 @@
</div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
<script setup lang="ts">
import { useLayoutStore } from "@/stores/layout";
import { users as api } from "@/api";
import Errors from "@/views/Errors.vue";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { StatusError } from "@/api/utils";
export default {
name: "users",
components: {
Errors,
},
data: function () {
return {
error: null,
users: [],
};
},
async created() {
this.setLoading(true);
const error = ref<StatusError | null>(null);
const users = ref<IUser[]>([]);
try {
this.users = await api.getAll();
} catch (e) {
this.error = e;
} finally {
this.setLoading(false);
const layoutStore = useLayoutStore();
const { t } = useI18n();
onMounted(async () => {
layoutStore.loading = true;
try {
users.value = await api.getAll();
} catch (err) {
if (err instanceof Error) {
error.value = err;
}
},
computed: {
...mapState(["loading"]),
},
methods: {
...mapMutations(["setLoading"]),
},
};
} finally {
layoutStore.loading = false;
}
});
</script>