Compare commits

..

6 Commits

Author SHA1 Message Date
Calum H.
cf309fd641 feat: basic CODEOWNERS template 2025-06-22 17:23:07 +01:00
Prospector
ced073d26c Add colors for new loaders, reduce utility redundancy (#3820)
* Add colors to some newer loaders

* Make loader formatting consistent everywhere, remove redundant utilities
2025-06-21 14:35:42 +00:00
Josiah Glosson
cc34e69524 Initial shared instances backend (#3800)
* Create base shared instance migration and initial routes

* Fix build

* Add version uploads

* Add permissions field for shared instance users

* Actually use permissions field

* Add "public" flag to shared instances that allow GETing them without authorization

* Add the ability to get and list shared instance versions

* Add the ability to delete shared instance versions

* Fix build after merge

* Secured file hosting (#3784)

* Remove Backblaze-specific file-hosting backend

* Added S3_USES_PATH_STYLE_BUCKETS

* Remove unused file_id parameter from delete_file_version

* Add support for separate public and private buckets in labrinth::file_hosting

* Rename delete_file_version to delete_file

* Add (untested) get_url_for_private_file

* Remove url field from shared instance routes

* Remove url field from shared instance routes

* Use private bucket for shared instance versions

* Make S3 environment variables fully separate between public and private buckets

* Change file host expiry for shared instances to 180 seconds

* Fix lint

* Merge shared instance migrations into a single migration

* Replace shared instance owners with Ghost instead of deleting the instance
2025-06-19 19:46:12 +00:00
IMB11
d4864deac5 fix: intercom bubble colliding with notifications (#3810) 2025-06-19 15:18:10 +00:00
IMB11
125207880d fix: state update race conditons (#3812) 2025-06-19 15:18:00 +00:00
IMB11
a8f17f40f5 fix: unclear file upload errors temp fix (#3811) 2025-06-19 15:17:50 +00:00
109 changed files with 2518 additions and 2421 deletions

25
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,25 @@
/apps/frontend/ @modrinth/frontend
/apps/app-frontend/ @modrinth/frontend
/apps/daedalus_client/ @modrinth/backend
/apps/docs/ @modrinth/support @modrinth/platform @modrinth/servers
/apps/labrinth @modrinth/backend
/apps/app @modrinth/backend
/packages/app-lib/ @modrinth/backend
/packages/ariadne/ @modrinth/backend
/packages/assets/ @modrinth/frontend
/packages/daedalus/ @modrinth/backend
/packages/eslint-config-custom/ @modrinth/frontend
/packages/tsconfig/ @modrinth/frontend
/packages/ui/ @modrinth/frontend
/packages/utils/ @modrinth/frontend
README.md @modrinth/support
LICENSE @Geometrically @Prospector
/COPYING.md @Geometrically @Prospector
/apps/frontend/src/pages/legal/ @Geometrically @Prospector
/.github/ @Geometrically @Prospector
/docker-compose.yml @modrinth/backend

View File

@@ -85,11 +85,10 @@ During development, you might notice that changes made directly to entities in t
#### CDN options
`STORAGE_BACKEND`: Controls what storage backend is used. This can be either `local`, `backblaze`, or `s3`, but defaults to `local`
`STORAGE_BACKEND`: Controls what storage backend is used. This can be either `local` or `s3`, but defaults to `local`
The Backblaze and S3 configuration options are fairly self-explanatory in name, so here's simply their names:
`BACKBLAZE_KEY_ID`, `BACKBLAZE_KEY`, `BACKBLAZE_BUCKET_ID`
`S3_ACCESS_TOKEN`, `S3_SECRET`, `S3_URL`, `S3_REGION`, `S3_BUCKET_NAME`
The S3 configuration options are fairly self-explanatory in name, so here's simply their names:
`S3_ACCESS_TOKEN`, `S3_SECRET`, `S3_URL`, `S3_REGION`, `S3_PUBLIC_BUCKET_NAME`, `S3_PRIVATE_BUCKET_NAME`, `S3_USES_PATH_STYLE_BUCKETS`
#### Search, OAuth, and miscellaneous options

View File

@@ -41,12 +41,10 @@
"@modrinth/ui": "workspace:*",
"@modrinth/utils": "workspace:*",
"@pinia/nuxt": "^0.5.1",
"@types/three": "^0.172.0",
"@vintl/vintl": "^4.4.1",
"@vueuse/core": "^11.1.0",
"ace-builds": "^1.36.2",
"ansi-to-html": "^0.7.2",
"cronstrue": "^2.61.0",
"dayjs": "^1.11.7",
"dompurify": "^3.1.7",
"floating-vue": "^5.2.2",
@@ -61,6 +59,7 @@
"qrcode.vue": "^3.4.0",
"semver": "^7.5.4",
"three": "^0.172.0",
"@types/three": "^0.172.0",
"vue-multiselect": "3.0.0-alpha.2",
"vue-typed-virtual-list": "^1.0.10",
"vue3-ace-editor": "^2.2.4",

View File

@@ -1,5 +1,8 @@
<template>
<div class="vue-notification-group experimental-styles-within">
<div
class="vue-notification-group experimental-styles-within"
:class="{ 'intercom-present': isIntercomPresent }"
>
<transition-group name="notifs">
<div
v-for="(item, index) in notifications"
@@ -80,6 +83,8 @@ import {
} from "@modrinth/assets";
const notifications = useNotifications();
const isIntercomPresent = ref(false);
function stopTimer(notif) {
clearTimeout(notif.timer);
}
@@ -106,6 +111,27 @@ const createNotifText = (notif) => {
return text;
};
function checkIntercomPresence() {
isIntercomPresent.value = !!document.querySelector(".intercom-lightweight-app");
}
onMounted(() => {
checkIntercomPresence();
const observer = new MutationObserver(() => {
checkIntercomPresence();
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
onBeforeUnmount(() => {
observer.disconnect();
});
});
function copyToClipboard(notif) {
const text = createNotifText(notif);
@@ -130,6 +156,10 @@ function copyToClipboard(notif) {
bottom: 0.75rem;
}
&.intercom-present {
bottom: 5rem;
}
.vue-notification-wrapper {
width: 100%;
overflow: hidden;

View File

@@ -57,7 +57,7 @@
<div class="table-cell">
<BoxIcon />
<span>{{
$formatProjectType(
formatProjectType(
$getProjectTypeForDisplay(
project.project_types?.[0] ?? "project",
project.loaders,
@@ -111,6 +111,7 @@
<script setup>
import { BoxIcon, SettingsIcon, TransferIcon, XIcon } from "@modrinth/assets";
import { Button, Modal, Checkbox, CopyCode, Avatar } from "@modrinth/ui";
import { formatProjectType } from "@modrinth/utils";
const modalOpen = ref(null);

View File

@@ -118,7 +118,7 @@ import {
ScaleIcon,
DropdownIcon,
} from "@modrinth/assets";
import { formatProjectType } from "~/plugins/shorthands.js";
import { formatProjectType } from "@modrinth/utils";
import { acceptTeamInvite, removeTeamMember } from "~/helpers/teams.js";
const props = defineProps({

View File

@@ -11,8 +11,8 @@
<div class="stacked">
<span class="title">{{ report.project.title }}</span>
<span>{{
$formatProjectType(
$getProjectTypeForUrl(report.project.project_type, report.project.loaders),
formatProjectType(
getProjectTypeForUrl(report.project.project_type, report.project.loaders),
)
}}</span>
</div>
@@ -53,8 +53,8 @@
<div class="stacked">
<span class="title">{{ report.project.title }}</span>
<span>{{
$formatProjectType(
$getProjectTypeForUrl(report.project.project_type, report.project.loaders),
formatProjectType(
getProjectTypeForUrl(report.project.project_type, report.project.loaders),
)
}}</span>
</div>
@@ -105,8 +105,10 @@
<script setup>
import { ReportIcon, UnknownIcon, VersionIcon } from "@modrinth/assets";
import { Avatar, Badge, CopyCode, useRelativeTime } from "@modrinth/ui";
import { formatProjectType } from "@modrinth/utils";
import { renderHighlightedString } from "~/helpers/highlight.js";
import ThreadSummary from "~/components/ui/thread/ThreadSummary.vue";
import { getProjectTypeForUrl } from "~/helpers/projects.js";
const formatRelativeTime = useRelativeTime();

View File

@@ -4,12 +4,14 @@
<span
v-for="category in categoriesFiltered"
:key="category.name"
v-html="category.icon + $formatCategory(category.name)"
v-html="category.icon + formatCategory(category.name)"
/>
</div>
</template>
<script>
import { formatCategory } from "@modrinth/utils";
export default {
props: {
categories: {
@@ -38,6 +40,7 @@ export default {
);
},
},
methods: { formatCategory },
};
</script>

View File

@@ -16,7 +16,7 @@ import {
} from "@modrinth/assets";
import { ButtonStyled, commonMessages, OverflowMenu, ProgressBar } from "@modrinth/ui";
import { defineMessages, useVIntl } from "@vintl/vintl";
import { ref } from "vue";
import { ref, computed } from "vue";
import type { Backup } from "@modrinth/utils";
const flags = useFeatureFlags();
@@ -52,9 +52,10 @@ const failedToCreate = computed(() => props.backup.interrupted);
const preparedDownloadStates = ["ready", "done"];
const inactiveStates = ["failed", "cancelled"];
const hasPreparedDownload = computed(() =>
preparedDownloadStates.includes(props.backup.task?.file?.state ?? ""),
);
const hasPreparedDownload = computed(() => {
const fileState = props.backup.task?.file?.state ?? "";
return preparedDownloadStates.includes(fileState);
});
const creating = computed(() => {
const task = props.backup.task?.create;
@@ -81,6 +82,10 @@ const restoring = computed(() => {
const initiatedPrepare = ref(false);
const preparingFile = computed(() => {
if (hasPreparedDownload.value) {
return false;
}
const task = props.backup.task?.file;
return (
(!task && initiatedPrepare.value) ||

View File

@@ -39,7 +39,7 @@
/>
<XCircleIcon
v-show="
item.status === 'error' ||
item.status.includes('error') ||
item.status === 'cancelled' ||
item.status === 'incorrect-type'
"
@@ -54,9 +54,14 @@
<template v-if="item.status === 'completed'">
<span>Done</span>
</template>
<template v-else-if="item.status === 'error'">
<template v-else-if="item.status === 'error-file-exists'">
<span class="text-red">Failed - File already exists</span>
</template>
<template v-else-if="item.status === 'error-generic'">
<span class="text-red"
>Failed - {{ item.error?.message || "An unexpected error occured." }}</span
>
</template>
<template v-else-if="item.status === 'incorrect-type'">
<span class="text-red">Failed - Incorrect file type</span>
</template>
@@ -104,9 +109,17 @@ import { FSModule } from "~/composables/servers/modules/fs.ts";
interface UploadItem {
file: File;
progress: number;
status: "pending" | "uploading" | "completed" | "error" | "cancelled" | "incorrect-type";
status:
| "pending"
| "uploading"
| "completed"
| "error-file-exists"
| "error-generic"
| "cancelled"
| "incorrect-type";
size: string;
uploader?: any;
error?: Error;
}
interface Props {
@@ -245,8 +258,18 @@ const uploadFile = async (file: File) => {
console.error("Error uploading file:", error);
const index = uploadQueue.value.findIndex((item) => item.file.name === file.name);
if (index !== -1 && uploadQueue.value[index].status !== "cancelled") {
uploadQueue.value[index].status =
error instanceof Error && error.message === badFileTypeMsg ? "incorrect-type" : "error";
const target = uploadQueue.value[index];
if (error instanceof Error) {
if (error.message === badFileTypeMsg) {
target.status = "incorrect-type";
} else if (target.progress === 100 && error.message.includes("401")) {
target.status = "error-file-exists";
} else {
target.status = "error-generic";
target.error = error;
}
}
}
setTimeout(async () => {

View File

@@ -6,7 +6,7 @@
<NuxtLink
:to="link.href"
class="flex items-center gap-2 rounded-xl p-2 hover:bg-button-bg"
:class="{ 'bg-button-bg text-contrast': isLinkActive(link) }"
:class="{ 'bg-button-bg text-contrast': route.path === link.href }"
>
<div class="flex items-center gap-2 font-bold">
<component :is="link.icon" class="size-6" />
@@ -39,33 +39,13 @@ import { ModrinthServer } from "~/composables/servers/modrinth-servers.ts";
const emit = defineEmits(["reinstall"]);
const props = defineProps<{
navLinks: {
label: string;
href: string;
icon: Component;
external?: boolean;
matches?: RegExp[];
}[];
defineProps<{
navLinks: { label: string; href: string; icon: Component; external?: boolean }[];
route: RouteLocationNormalized;
server: ModrinthServer;
backupInProgress?: BackupInProgressReason;
}>();
const isLinkActive = (link: (typeof props.navLinks)[0]) => {
if (props.route.path === link.href) {
return true;
}
if (link.matches && link.matches.length > 0) {
return link.matches.some((regex: RegExp) => {
return regex.test(props.route.path);
});
}
return false;
};
const onReinstall = (...args: any[]) => {
emit("reinstall", ...args);
};

View File

@@ -1,531 +0,0 @@
<template>
<NewModal
ref="modal"
:header="isNew ? 'New scheduled task' : 'Editing scheduled task'"
@hide="onModalHide"
>
<div class="modal-content flex flex-col gap-2">
<div v-if="error" class="text-sm text-brand-red">
{{ error }}
</div>
<div class="flex max-w-md flex-col gap-2">
<label for="title">
<span class="text-lg font-bold text-contrast">
Title <span class="text-brand-red">*</span>
</span>
</label>
<input
id="title"
v-model="task.title"
type="text"
maxlength="64"
placeholder="Enter task title..."
autocomplete="off"
class="input input-bordered"
required
/>
</div>
<div class="flex flex-col gap-2">
<label><span class="text-lg font-bold text-contrast">Schedule Type</span></label>
<RadioButtons v-model="scheduleType" :items="['daily', 'custom']" class="mb-2">
<template #default="{ item }">
<span class="flex items-center gap-2">
<ClockIcon v-if="item === 'daily'" class="size-5" />
<CodeIcon v-else class="size-5" />
<span>{{
item === "daily" ? "Every X day(s) at specific time" : "Custom cron expression"
}}</span>
</span>
</template>
</RadioButtons>
</div>
<div class="card flex h-[140px] items-center overflow-hidden rounded-lg !bg-bg">
<Transition
name="schedule-content"
mode="out-in"
enter-active-class="transition-all duration-300 ease-in-out"
leave-active-class="transition-all duration-300 ease-in-out"
enter-from-class="opacity-0"
enter-to-class="opacity-100"
leave-from-class="opacity-100"
leave-to-class="opacity-0"
>
<div v-if="scheduleType === 'daily'" key="daily" class="flex w-full flex-col gap-2">
<div class="flex w-full gap-8">
<div class="flex flex-col gap-2">
<label for="dayInterval" class="text-md font-medium">Every X day(s)</label>
<div class="flex items-center gap-2">
<input
id="dayInterval"
v-model="dayInterval"
type="text"
inputmode="numeric"
maxlength="3"
class="input input-bordered w-20"
placeholder="1"
@input="onDayIntervalInput"
/>
<span class="text-muted-foreground text-sm">day(s)</span>
</div>
</div>
<div class="flex flex-col gap-2">
<label class="text-md font-medium">At time</label>
<TimePicker v-model="selectedTime" use-utc-values placeholder="Select time" />
</div>
</div>
<div class="text-xs">
{{ humanReadableDescription }}
</div>
</div>
<div v-else key="custom" class="flex w-full flex-col gap-2">
<label for="customCron" class="text-md font-medium"
>Cron Expression
<nuxt-link
v-tooltip="
`Click to read more about what cron expressions are, and how to create them.`
"
class="align-middle text-link"
target="_blank"
to="https://www.geeksforgeeks.org/writing-cron-expressions-for-scheduling-tasks/"
><UnknownIcon class="size-4" />
</nuxt-link>
</label>
<input
id="customCron"
v-model="customCron"
type="text"
class="input input-bordered font-mono"
placeholder="0 0 9 * * *"
/>
<div v-if="!isValidCron" class="text-xs text-brand-red">
Invalid cron format. Please use 6 space-separated values (e.g.,
<code>second minute hour day month day-of-week</code>).
</div>
<div v-else class="text-xs">
{{ humanReadableDescription }}
</div>
</div>
</Transition>
</div>
<div class="flex max-w-md flex-col gap-2">
<label for="action_kind"><span class="text-lg font-bold text-contrast">Action</span></label>
<RadioButtons v-model="task.action_kind" :items="actionKinds" class="mb-2">
<template #default="{ item }">
<span>{{ item === "restart" ? "Restart server" : "Run game command" }}</span>
</template>
</RadioButtons>
</div>
<Transition
name="command-section"
enter-active-class="transition-all duration-300 ease-in-out"
leave-active-class="transition-all duration-300 ease-in-out"
enter-from-class="opacity-0 max-h-0 overflow-hidden"
enter-to-class="opacity-100 max-h-96 overflow-visible"
leave-from-class="opacity-100 max-h-96 overflow-visible"
leave-to-class="opacity-0 max-h-0 overflow-hidden"
>
<div v-if="task.action_kind === 'game-command'" class="flex max-w-lg flex-col gap-4">
<label for="command" class="flex flex-col gap-2"
><span class="text-lg font-bold text-contrast">
Command <span class="text-brand-red">*</span>
</span>
<span
>The command that will be ran when the task is executed. If the command is invalid
nothing will happen.</span
></label
>
<div class="max-w-md">
<input
id="command"
v-model="commandValue"
type="text"
maxlength="256"
placeholder="Enter command to run..."
class="input input-bordered"
required
/>
</div>
</div>
</Transition>
<div class="flex max-w-lg flex-col gap-4">
<label for="warn_msg" class="flex flex-col gap-2"
><span class="text-lg font-bold text-contrast">
Warning Command
<span
v-if="task.warn_intervals && task.warn_intervals.length > 0"
class="text-brand-red"
>*</span
>
</span>
<span
>You can use <code>{}</code> to insert the time until the task is executed. If the
command is invalid nothing will happen.</span
></label
>
<div class="max-w-md">
<input
id="warn_msg"
v-model="task.warn_msg"
type="text"
maxlength="128"
:placeholder="`/tellraw @a \u0022Restarting in {}!\u0022`"
class="input input-bordered max-w-md"
/>
</div>
</div>
<div class="flex max-w-lg flex-col gap-4">
<label for="warn_msg" class="flex flex-col gap-2"
><span class="text-lg font-bold text-contrast">Warning Intervals</span>
<span
>When, at the time before the scheduled task is executed, should the warning command be
executed?</span
></label
>
<div class="flex flex-row flex-wrap gap-4">
<Chips
v-model="task.warn_intervals"
:items="[5, 15, 30, 60, 120, 300, 600]"
multi
:never-empty="false"
:format-label="formatWarningIntervalLabel"
/>
</div>
</div>
<div class="mt-2 flex max-w-md gap-2">
<ButtonStyled color="brand">
<button :disabled="!canSave" @click="saveTask">
<SaveIcon />
Save
</button>
</ButtonStyled>
<ButtonStyled>
<button :disabled="loading" @click="closeModal">
<XIcon />
Cancel
</button>
</ButtonStyled>
</div>
</div>
</NewModal>
</template>
<script setup lang="ts">
import type { Schedule, ServerSchedule, ActionKind } from "@modrinth/utils";
import { ref, computed, watch } from "vue";
import { RadioButtons, TimePicker, Chips, ButtonStyled, NewModal } from "@modrinth/ui";
import { ClockIcon, CodeIcon, SaveIcon, XIcon, UnknownIcon } from "@modrinth/assets";
import { toString as cronToString } from "cronstrue";
import { ModrinthServer } from "~/composables/servers/modrinth-servers.ts";
const props = defineProps<{ server: ModrinthServer }>();
const modal = ref<InstanceType<typeof NewModal>>();
const loading = ref(false);
const error = ref<string | null>(null);
const task = ref<Partial<ServerSchedule | Schedule>>({});
const isNew = ref(true);
const originalTaskId = ref<number | null>(null);
const scheduleType = ref<"daily" | "custom">("daily");
const dayInterval = ref("1");
const selectedTime = ref({ hour: "9", minute: "0" });
const customCron = ref("0 0 9 * * *");
const actionKinds: ActionKind[] = ["restart", "game-command"];
const commandValue = computed({
get() {
return task.value.options && "command" in task.value.options ? task.value.options.command : "";
},
set(val: string) {
if (task.value.options && "command" in task.value.options) {
task.value.options.command = val;
} else if (task.value.action_kind === "game-command") {
task.value.options = { command: val };
}
},
});
const cronString = computed(() => {
if (scheduleType.value === "custom") {
return customCron.value.trim();
}
const minute = selectedTime.value.minute === "" ? "0" : selectedTime.value.minute;
const hour = selectedTime.value.hour === "" ? "0" : selectedTime.value.hour;
const days = dayInterval.value === "" || Number(dayInterval.value) < 1 ? "1" : dayInterval.value;
if (days === "1") {
return `0 ${minute} ${hour} * * *`;
} else {
return `0 ${minute} ${hour} */${days} * *`;
}
});
const CRON_REGEX =
/^\s*([0-9*/,-]+)\s+([0-9*/,-]+)\s+([0-9*/,-]+)\s+([0-9*/,-]+)\s+([0-9*/,-]+)\s+([0-9*/,-]+)\s*$/;
const isValidCron = computed(() => {
const cronToTest = scheduleType.value === "custom" ? customCron.value.trim() : cronString.value;
if (!CRON_REGEX.test(cronToTest)) {
return false;
}
if (scheduleType.value === "custom") {
try {
const parts = cronToTest.split(/\s+/);
if (parts.length === 6) {
cronToString(parts.slice(1).join(" "));
}
return true;
} catch {
return false;
}
}
return true;
});
const isValidGameCommand = computed(() => {
if (task.value.action_kind === "game-command") {
return commandValue.value && commandValue.value.trim().length > 0;
}
return true;
});
const isValidWarningCommand = computed(() => {
if (task.value.warn_intervals && task.value.warn_intervals.length > 0) {
return task.value.warn_msg && task.value.warn_msg.trim().length > 0;
}
return true;
});
const canSave = computed(() => {
return (
!loading.value &&
task.value.title &&
task.value.title.trim().length > 0 &&
isValidCron.value &&
isValidGameCommand.value &&
isValidWarningCommand.value
);
});
const humanReadableDescription = computed<string | undefined>(() => {
if (!isValidCron.value && scheduleType.value === "custom") return undefined;
if (scheduleType.value === "custom") {
try {
const parts = customCron.value.trim().split(/\s+/);
if (parts.length === 6) {
return cronToString(parts.slice(1).join(" "));
}
return "Invalid cron expression";
} catch {
return "Invalid cron expression";
}
}
const minute = selectedTime.value.minute === "" ? "0" : selectedTime.value.minute;
const hour = selectedTime.value.hour === "" ? "0" : selectedTime.value.hour;
const daysNum = Number(dayInterval.value || "1");
const timeStr = `${hour.padStart(2, "0")}:${minute.padStart(2, "0")}`;
if (daysNum <= 1) {
return `Every day at ${timeStr}`;
} else {
return `Every ${daysNum} days at ${timeStr}`;
}
});
function formatWarningIntervalLabel(seconds: number): string {
if (seconds < 60) {
return `${seconds}s`;
} else {
const minutes = Math.floor(seconds / 60);
return `${minutes}m`;
}
}
function onDayIntervalInput(event: Event) {
const input = event.target as HTMLInputElement;
let value = input.value.replace(/\D/g, "");
if (value === "") {
dayInterval.value = "";
return;
}
if (value.length > 1 && value.startsWith("0")) {
value = value.replace(/^0+/, "");
}
const num = parseInt(value);
if (num < 1) {
dayInterval.value = "1";
} else if (num > 365) {
dayInterval.value = "365";
} else {
dayInterval.value = String(num);
}
}
function resetForm() {
task.value = {
title: "",
action_kind: "restart",
options: {},
enabled: true,
warn_msg: '/tellraw @a "Restarting in {}!"',
warn_intervals: [],
};
scheduleType.value = "daily";
dayInterval.value = "1";
selectedTime.value = { hour: "9", minute: "0" };
customCron.value = "0 0 9 * * *";
isNew.value = true;
originalTaskId.value = null;
error.value = null;
if (isValidCron.value) {
task.value.every = cronString.value;
}
}
function loadTaskData(taskData: ServerSchedule | Schedule) {
task.value = { ...taskData };
isNew.value = false;
originalTaskId.value = "id" in taskData ? taskData.id : null;
if (task.value.every && typeof task.value.every === "string") {
const parts = task.value.every.split(/\s+/);
if (parts.length === 6) {
const second = parts[0];
const minute = parts[1];
const hour = parts[2];
const dayOfMonth = parts[3];
if (second === "0" && dayOfMonth.startsWith("*/")) {
scheduleType.value = "daily";
dayInterval.value = dayOfMonth.substring(2);
selectedTime.value = { hour, minute };
} else if (second === "0" && dayOfMonth === "*" && parts[4] === "*" && parts[5] === "*") {
scheduleType.value = "daily";
dayInterval.value = "1";
selectedTime.value = { hour, minute };
} else {
scheduleType.value = "custom";
customCron.value = task.value.every;
}
} else if (parts.length === 5) {
const minute = parts[0];
const hour = parts[1];
const dayOfMonth = parts[2];
if (dayOfMonth.startsWith("*/")) {
scheduleType.value = "daily";
dayInterval.value = dayOfMonth.substring(2);
selectedTime.value = { hour, minute };
} else if (dayOfMonth === "*" && parts[3] === "*" && parts[4] === "*") {
scheduleType.value = "daily";
dayInterval.value = "1";
selectedTime.value = { hour, minute };
} else {
scheduleType.value = "custom";
customCron.value = `0 ${task.value.every}`;
}
} else {
scheduleType.value = "custom";
customCron.value = task.value.every;
}
}
}
function show(taskData?: ServerSchedule | Schedule) {
if (taskData) {
loadTaskData(taskData);
} else {
resetForm();
}
modal.value?.show();
}
function closeModal() {
modal.value?.hide();
}
function onModalHide() {
// Reset form when modal is hidden
resetForm();
}
async function saveTask() {
loading.value = true;
error.value = null;
if (isValidCron.value) {
task.value.every = cronString.value;
} else {
error.value = "Cannot save with invalid cron expression.";
loading.value = false;
return;
}
try {
if (isNew.value) {
const scheduleToCreate: Schedule = {
title: task.value.title || "",
every: task.value.every!,
action_kind: task.value.action_kind!,
options: task.value.options!,
enabled: task.value.enabled !== undefined ? task.value.enabled : true,
warn_msg: task.value.warn_msg !== undefined ? task.value.warn_msg : "",
warn_intervals: task.value.warn_intervals || [],
};
await props.server.scheduling.createTask(scheduleToCreate);
closeModal();
} else if (originalTaskId.value != null) {
await props.server.scheduling.editTask(originalTaskId.value, task.value);
closeModal();
}
} catch (e) {
error.value = (e as Error).message || "Failed to save task.";
} finally {
loading.value = false;
}
}
watch([cronString, isValidCron], ([cron, valid]) => {
if (valid) {
task.value.every = cron;
}
});
watch(
() => task.value.action_kind,
(kind) => {
if (kind === "game-command") {
if (
!task.value.options ||
typeof task.value.options !== "object" ||
!("command" in task.value.options)
) {
task.value.options = { command: "" };
}
} else {
task.value.options = {};
}
},
{ immediate: true },
);
defineExpose({
show,
hide: closeModal,
});
</script>
<style scoped></style>

View File

@@ -11,7 +11,6 @@ import {
WSModule,
FSModule,
} from "./modules/index.ts";
import { SchedulingModule } from "./modules/scheduling.ts";
export function handleError(err: any) {
if (err instanceof ModrinthServerError && err.v1Error) {
@@ -41,7 +40,6 @@ export class ModrinthServer {
readonly startup: StartupModule;
readonly ws: WSModule;
readonly fs: FSModule;
readonly scheduling: SchedulingModule;
constructor(serverId: string) {
this.serverId = serverId;
@@ -53,7 +51,6 @@ export class ModrinthServer {
this.startup = new StartupModule(this);
this.ws = new WSModule(this);
this.fs = new FSModule(this);
this.scheduling = new SchedulingModule(this);
}
async createMissingFolders(path: string): Promise<void> {
@@ -200,16 +197,7 @@ export class ModrinthServer {
const modulesToRefresh =
modules.length > 0
? modules
: ([
"general",
"content",
"backups",
"network",
"startup",
"ws",
"fs",
"scheduling",
] as ModuleName[]);
: (["general", "content", "backups", "network", "startup", "ws", "fs"] as ModuleName[]);
for (const module of modulesToRefresh) {
try {
@@ -254,8 +242,6 @@ export class ModrinthServer {
case "fs":
await this.fs.fetch();
break;
case "scheduling":
await this.scheduling.fetch();
}
} catch (error) {
if (error instanceof ModrinthServerError) {

View File

@@ -1,80 +0,0 @@
import type { Schedule, ServerSchedule } from "@modrinth/utils";
import { useServersFetch } from "../servers-fetch.ts";
import { ServerModule } from "./base.ts";
export class SchedulingModule extends ServerModule {
tasks: ServerSchedule[] = [];
private optimisticUpdate(action: () => void): () => void {
const originalTasks = [...this.tasks];
action();
return () => {
this.tasks = originalTasks;
};
}
async fetch(): Promise<void> {
const response = await useServersFetch<{ schedules: { quota: 32; items: ServerSchedule[] } }>(
`servers/${this.serverId}/options`,
{ version: 1 },
);
this.tasks = response.schedules.items;
}
async deleteTask(task: ServerSchedule): Promise<void> {
const rollback = this.optimisticUpdate(() => {
this.tasks = this.tasks.filter((t) => t.id !== task.id);
});
try {
await useServersFetch(`servers/${this.serverId}/options/schedules/${task.id}`, {
method: "DELETE",
version: 1,
});
} catch (error) {
rollback();
throw error;
}
}
async createTask(task: Schedule): Promise<number> {
const rollback = this.optimisticUpdate(() => {});
try {
const response = await useServersFetch<{ id: number }>(
`servers/${this.serverId}/options/schedules`,
{
method: "POST",
body: task,
version: 1,
},
);
this.tasks.push({ ...task, id: response.id } as ServerSchedule);
return response.id;
} catch (error) {
rollback();
throw error;
}
}
async editTask(taskId: number, updatedTask: Partial<Schedule>): Promise<void> {
const rollback = this.optimisticUpdate(() => {
const taskIndex = this.tasks.findIndex((t) => t.id === taskId);
if (taskIndex !== -1) {
this.tasks[taskIndex] = { ...this.tasks[taskIndex], ...updatedTask };
}
});
try {
await useServersFetch(`servers/${this.serverId}/options/schedules/${taskId}`, {
method: "PATCH",
body: updatedTask,
version: 1,
});
} catch (error) {
rollback();
throw error;
}
}
}

View File

@@ -1,4 +1,4 @@
import { formatBytes } from "~/plugins/shorthands.js";
import { formatBytes } from "@modrinth/utils";
export const fileIsValid = (file, validationOptions) => {
const { maxSize, alertOnInvalid } = validationOptions;

View File

@@ -875,7 +875,14 @@ import {
useRelativeTime,
} from "@modrinth/ui";
import VersionSummary from "@modrinth/ui/src/components/version/VersionSummary.vue";
import { formatCategory, isRejected, isStaff, isUnderReview, renderString } from "@modrinth/utils";
import {
formatCategory,
formatProjectType,
isRejected,
isStaff,
isUnderReview,
renderString,
} from "@modrinth/utils";
import { navigateTo } from "#app";
import dayjs from "dayjs";
import Accordion from "~/components/ui/Accordion.vue";
@@ -1286,7 +1293,7 @@ featuredVersions.value.sort((a, b) => {
});
const projectTypeDisplay = computed(() =>
data.$formatProjectType(
formatProjectType(
data.$getProjectTypeForDisplay(project.value.project_type, project.value.loaders),
),
);

View File

@@ -104,7 +104,7 @@
<span class="label__title">Client-side</span>
<span class="label__description">
Select based on if the
{{ $formatProjectType(project.project_type).toLowerCase() }} has functionality on the
{{ formatProjectType(project.project_type).toLowerCase() }} has functionality on the
client side. Just because a mod works in Singleplayer doesn't mean it has actual
client-side functionality.
</span>
@@ -128,7 +128,7 @@
<span class="label__title">Server-side</span>
<span class="label__description">
Select based on if the
{{ $formatProjectType(project.project_type).toLowerCase() }} has functionality on the
{{ formatProjectType(project.project_type).toLowerCase() }} has functionality on the
<strong>logical</strong> server. Remember that Singleplayer contains an integrated
server.
</span>
@@ -239,7 +239,7 @@
</template>
<script setup>
import { formatProjectStatus } from "@modrinth/utils";
import { formatProjectStatus, formatProjectType } from "@modrinth/utils";
import { UploadIcon, SaveIcon, TrashIcon, XIcon, IssuesIcon, CheckIcon } from "@modrinth/assets";
import { Multiselect } from "vue-multiselect";
import { ConfirmModal, Avatar } from "@modrinth/ui";

View File

@@ -8,7 +8,7 @@
</div>
<p>
Accurate tagging is important to help people find your
{{ $formatProjectType(project.project_type).toLowerCase() }}. Make sure to select all tags
{{ formatProjectType(project.project_type).toLowerCase() }}. Make sure to select all tags
that apply.
</p>
<p v-if="project.versions.length === 0" class="known-errors">
@@ -18,25 +18,25 @@
<template v-for="header in Object.keys(categoryLists)" :key="`categories-${header}`">
<div class="label">
<h4>
<span class="label__title">{{ $formatCategoryHeader(header) }}</span>
<span class="label__title">{{ formatCategoryHeader(header) }}</span>
</h4>
<span class="label__description">
<template v-if="header === 'categories'">
Select all categories that reflect the themes or function of your
{{ $formatProjectType(project.project_type).toLowerCase() }}.
{{ formatProjectType(project.project_type).toLowerCase() }}.
</template>
<template v-else-if="header === 'features'">
Select all of the features that your
{{ $formatProjectType(project.project_type).toLowerCase() }} makes use of.
{{ formatProjectType(project.project_type).toLowerCase() }} makes use of.
</template>
<template v-else-if="header === 'resolutions'">
Select the resolution(s) of textures in your
{{ $formatProjectType(project.project_type).toLowerCase() }}.
{{ formatProjectType(project.project_type).toLowerCase() }}.
</template>
<template v-else-if="header === 'performance impact'">
Select the realistic performance impact of your
{{ $formatProjectType(project.project_type).toLowerCase() }}. Select multiple if the
{{ $formatProjectType(project.project_type).toLowerCase() }} is configurable to
{{ formatProjectType(project.project_type).toLowerCase() }}. Select multiple if the
{{ formatProjectType(project.project_type).toLowerCase() }} is configurable to
different levels of performance impact.
</template>
</span>
@@ -46,7 +46,7 @@
v-for="category in categoryLists[header]"
:key="`category-${header}-${category.name}`"
:model-value="selectedTags.includes(category)"
:description="$formatCategory(category.name)"
:description="formatCategory(category.name)"
class="category-selector"
@update:model-value="toggleCategory(category)"
>
@@ -57,7 +57,7 @@
class="icon"
v-html="category.icon"
/>
<span aria-hidden="true"> {{ $formatCategory(category.name) }}</span>
<span aria-hidden="true"> {{ formatCategory(category.name) }}</span>
</div>
</Checkbox>
</div>
@@ -80,7 +80,7 @@
:key="`featured-category-${category.name}`"
class="category-selector"
:model-value="featuredTags.includes(category)"
:description="$formatCategory(category.name)"
:description="formatCategory(category.name)"
:disabled="featuredTags.length >= 3 && !featuredTags.includes(category)"
@update:model-value="toggleFeaturedCategory(category)"
>
@@ -91,7 +91,7 @@
class="icon"
v-html="category.icon"
/>
<span aria-hidden="true"> {{ $formatCategory(category.name) }}</span>
<span aria-hidden="true"> {{ formatCategory(category.name) }}</span>
</div>
</Checkbox>
</div>
@@ -114,6 +114,7 @@
<script>
import { StarIcon, SaveIcon } from "@modrinth/assets";
import { formatCategory, formatCategoryHeader, formatProjectType } from "@modrinth/utils";
import Checkbox from "~/components/ui/Checkbox.vue";
export default defineNuxtComponent({
@@ -222,6 +223,9 @@ export default defineNuxtComponent({
},
},
methods: {
formatProjectType,
formatCategoryHeader,
formatCategory,
toggleCategory(category) {
if (this.selectedTags.includes(category)) {
this.selectedTags = this.selectedTags.filter((x) => x !== category);

View File

@@ -144,7 +144,7 @@
<div v-else class="input-group">
<ButtonStyled v-if="primaryFile" color="brand">
<a
v-tooltip="primaryFile.filename + ' (' + $formatBytes(primaryFile.size) + ')'"
v-tooltip="primaryFile.filename + ' (' + formatBytes(primaryFile.size) + ')'"
:href="primaryFile.url"
@click="emit('onDownload')"
>
@@ -320,7 +320,7 @@
<FileIcon aria-hidden="true" />
<span class="filename">
<strong>{{ replaceFile.name }}</strong>
<span class="file-size">({{ $formatBytes(replaceFile.size) }})</span>
<span class="file-size">({{ formatBytes(replaceFile.size) }})</span>
</span>
<FileInput
class="iconified-button raised-button"
@@ -345,7 +345,7 @@
<FileIcon aria-hidden="true" />
<span class="filename">
<strong>{{ file.filename }}</strong>
<span class="file-size">({{ $formatBytes(file.size) }})</span>
<span class="file-size">({{ formatBytes(file.size) }})</span>
<span v-if="primaryFile.hashes.sha1 === file.hashes.sha1" class="file-type">
Primary
</span>
@@ -412,7 +412,7 @@
<FileIcon aria-hidden="true" />
<span class="filename">
<strong>{{ file.name }}</strong>
<span class="file-size">({{ $formatBytes(file.size) }})</span>
<span class="file-size">({{ formatBytes(file.size) }})</span>
</span>
<multiselect
v-if="version.loaders.some((x) => tags.loaderData.dataPackLoaders.includes(x))"
@@ -533,7 +533,7 @@
)
.map((it) => it.name)
"
:custom-label="(value) => $formatCategory(value)"
:custom-label="formatCategory"
:loading="tags.loaders.length === 0"
:multiple="true"
:searchable="true"
@@ -657,6 +657,7 @@ import {
ChevronRightIcon,
} from "@modrinth/assets";
import { Multiselect } from "vue-multiselect";
import { formatBytes, formatCategory } from "@modrinth/utils";
import { acceptFileFromProjectType } from "~/helpers/fileUtils.js";
import { inferVersionInfo } from "~/helpers/infer.js";
import { createDataPackVersion } from "~/helpers/package.js";
@@ -962,6 +963,8 @@ export default defineNuxtComponent({
},
},
methods: {
formatBytes,
formatCategory,
async onImageUpload(file) {
const response = await useImageUpload(file, { context: "version" });

View File

@@ -26,7 +26,7 @@
v-if="notifTypes.length > 1"
v-model="selectedType"
:items="notifTypes"
:format-label="(x) => (x === 'all' ? 'All' : $formatProjectType(x).replace('_', ' ') + 's')"
:format-label="(x) => (x === 'all' ? 'All' : formatProjectType(x).replace('_', ' ') + 's')"
:capitalize="false"
/>
<p v-if="pending">Loading notifications...</p>
@@ -58,6 +58,7 @@
<script setup>
import { Button, Pagination, Chips } from "@modrinth/ui";
import { HistoryIcon, CheckCheckIcon } from "@modrinth/assets";
import { formatProjectType } from "@modrinth/utils";
import {
fetchExtraNotificationData,
groupNotifications,

View File

@@ -239,7 +239,7 @@
<div>
<nuxt-link
tabindex="-1"
:to="`/${$getProjectTypeForUrl(project.project_type, project.loaders)}/${
:to="`/${getProjectTypeForUrl(project.project_type, project.loaders)}/${
project.slug ? project.slug : project.id
}`"
>
@@ -261,7 +261,7 @@
<nuxt-link
class="hover-link wrap-as-needed"
:to="`/${$getProjectTypeForUrl(project.project_type, project.loaders)}/${
:to="`/${getProjectTypeForUrl(project.project_type, project.loaders)}/${
project.slug ? project.slug : project.id
}`"
>
@@ -275,7 +275,7 @@
</div>
<div>
{{ $formatProjectType($getProjectTypeForUrl(project.project_type, project.loaders)) }}
{{ formatProjectType(getProjectTypeForUrl(project.project_type, project.loaders)) }}
</div>
<div>
@@ -285,7 +285,7 @@
<div>
<ButtonStyled circular>
<nuxt-link
:to="`/${$getProjectTypeForUrl(project.project_type, project.loaders)}/${
:to="`/${getProjectTypeForUrl(project.project_type, project.loaders)}/${
project.slug ? project.slug : project.id
}/settings`"
>
@@ -321,9 +321,11 @@ import {
ProjectStatusBadge,
commonMessages,
} from "@modrinth/ui";
import { formatProjectType } from "@modrinth/utils";
import Modal from "~/components/ui/Modal.vue";
import ModalCreation from "~/components/ui/ModalCreation.vue";
import { getProjectTypeForUrl } from "~/helpers/projects.js";
export default defineNuxtComponent({
components: {
@@ -395,6 +397,8 @@ export default defineNuxtComponent({
this.DELETE_PROJECT = 1 << 7;
},
methods: {
getProjectTypeForUrl,
formatProjectType,
updateDescending() {
this.descending = !this.descending;
this.projects = this.updateSort(this.projects, this.sortBy, this.descending);

View File

@@ -76,7 +76,7 @@
</span>
<template v-if="payout.method">
<span>⋅</span>
<span>{{ $formatWallet(payout.method) }} ({{ payout.method_address }})</span>
<span>{{ formatWallet(payout.method) }} ({{ payout.method_address }})</span>
</template>
</div>
</div>
@@ -95,7 +95,7 @@
</template>
<script setup>
import { XIcon, PayPalIcon, UnknownIcon } from "@modrinth/assets";
import { capitalizeString } from "@modrinth/utils";
import { capitalizeString, formatWallet } from "@modrinth/utils";
import { Badge, Breadcrumbs, DropdownSelect } from "@modrinth/ui";
import dayjs from "dayjs";
import TremendousIcon from "~/assets/images/external/tremendous.svg?component";

View File

@@ -139,8 +139,8 @@
<template v-if="knownErrors.length === 0 && amount">
<Checkbox v-if="fees > 0" v-model="agreedFees" description="Consent to fee">
I acknowledge that an estimated
{{ $formatMoney(fees) }} will be deducted from the amount I receive to cover
{{ $formatWallet(selectedMethod.type) }} processing fees.
{{ formatMoney(fees) }} will be deducted from the amount I receive to cover
{{ formatWallet(selectedMethod.type) }} processing fees.
</Checkbox>
<Checkbox v-model="agreedTransfer" description="Confirm transfer">
<template v-if="selectedMethod.type === 'tremendous'">
@@ -149,7 +149,7 @@
</template>
<template v-else>
I confirm that I am initiating a transfer to the following
{{ $formatWallet(selectedMethod.type) }} account: {{ withdrawAccount }}
{{ formatWallet(selectedMethod.type) }} account: {{ withdrawAccount }}
</template>
</Checkbox>
<Checkbox v-model="agreedTerms" class="rewards-checkbox">
@@ -198,6 +198,7 @@ import {
} from "@modrinth/assets";
import { Chips, Checkbox, Breadcrumbs } from "@modrinth/ui";
import { all } from "iso-3166-1";
import { formatMoney, formatWallet } from "@modrinth/utils";
import VenmoIcon from "~/assets/images/external/venmo.svg?component";
const auth = await useAuth();
@@ -360,9 +361,7 @@ async function withdraw() {
text:
selectedMethod.value.type === "tremendous"
? "An email has been sent to your account with further instructions on how to redeem your payout!"
: `Payment has been sent to your ${data.$formatWallet(
selectedMethod.value.type,
)} account!`,
: `Payment has been sent to your ${formatWallet(selectedMethod.value.type)} account!`,
type: "success",
});
} catch (err) {

View File

@@ -32,7 +32,7 @@
</div>
</template>
<script setup>
import { formatNumber } from "~/plugins/shorthands.js";
import { formatNumber } from "@modrinth/utils";
useHead({
title: "Staff overview - Modrinth",

View File

@@ -5,7 +5,7 @@
<Chips
v-model="projectType"
:items="projectTypes"
:format-label="(x) => (x === 'all' ? 'All' : $formatProjectType(x) + 's')"
:format-label="(x) => (x === 'all' ? 'All' : formatProjectType(x) + 's')"
/>
<button v-if="oldestFirst" class="iconified-button push-right" @click="oldestFirst = false">
<SortDescendingIcon />
@@ -56,7 +56,7 @@
<Avatar :src="project.icon_url" size="xs" no-shadow raised />
<span class="stacked">
<span class="title">{{ project.name }}</span>
<span>{{ $formatProjectType(project.inferred_project_type) }}</span>
<span>{{ formatProjectType(project.inferred_project_type) }}</span>
</span>
</nuxt-link>
</div>
@@ -114,7 +114,7 @@ import {
IssuesIcon,
ScaleIcon,
} from "@modrinth/assets";
import { formatProjectType } from "~/plugins/shorthands.js";
import { formatProjectType } from "@modrinth/utils";
import { asEncodedJsonArray, fetchSegmented } from "~/utils/fetch-helpers.ts";
useHead({

View File

@@ -272,7 +272,7 @@
<div class="table-cell">
<BoxIcon />
<span>{{
$formatProjectType(
formatProjectType(
$getProjectTypeForDisplay(project.project_types[0] ?? "project", project.loaders),
)
}}</span>
@@ -313,6 +313,7 @@ import {
} from "@modrinth/assets";
import { Button, Modal, Avatar, CopyCode, Badge, Checkbox, commonMessages } from "@modrinth/ui";
import { formatProjectType } from "@modrinth/utils";
import ModalCreation from "~/components/ui/ModalCreation.vue";
import OrganizationProjectTransferModal from "~/components/ui/OrganizationProjectTransferModal.vue";

View File

@@ -417,7 +417,7 @@ const loadModulesPromise = Promise.resolve().then(() => {
if (server.general?.status === "suspended") {
return;
}
return server.refresh(["content", "backups", "network", "startup", "fs", "scheduling"]);
return server.refresh(["content", "backups", "network", "startup", "fs"]);
});
provide("modulesLoaded", loadModulesPromise);

View File

@@ -16,7 +16,6 @@ import {
CardIcon,
UserIcon,
WrenchIcon,
CalendarSyncIcon,
} from "@modrinth/assets";
import { ModrinthServer } from "~/composables/servers/modrinth-servers.ts";
import type { BackupInProgressReason } from "~/pages/servers/manage/[id].vue";
@@ -36,11 +35,6 @@ useHead({
const navLinks = [
{ icon: SettingsIcon, label: "General", href: `/servers/manage/${serverId}/options` },
{ icon: WrenchIcon, label: "Platform", href: `/servers/manage/${serverId}/options/loader` },
{
icon: CalendarSyncIcon,
label: "Task Scheduling",
href: `/servers/manage/${serverId}/options/scheduling`,
},
{ icon: TextQuoteIcon, label: "Startup", href: `/servers/manage/${serverId}/options/startup` },
{ icon: VersionIcon, label: "Network", href: `/servers/manage/${serverId}/options/network` },
{ icon: ListIcon, label: "Properties", href: `/servers/manage/${serverId}/options/properties` },

View File

@@ -1,437 +0,0 @@
<template>
<EditScheduledTaskModal ref="modal" :server="server"></EditScheduledTaskModal>
<div class="relative h-full w-full overflow-y-auto">
<div class="flex h-full w-full flex-col">
<section class="universal-card">
<div class="mb-6 flex items-center justify-between">
<div class="flex h-full flex-col justify-center">
<h2 class="m-0 text-lg font-bold text-contrast">Task scheduling</h2>
<span v-if="tasks.length < 1">
No scheduled tasks yet. Click the button to create your first task.
</span>
<span v-else-if="!isMobile"
>You can manage multiple tasks at once by selecting them below.</span
>
</div>
<div>
<ButtonStyled color="green"
><button @click="modal?.show()"><PlusIcon /> Create task</button></ButtonStyled
>
</div>
</div>
<template v-if="tasks.length > 0">
<div v-if="!isMobile" class="input-group">
<ButtonStyled>
<button :disabled="selectedTasks.length === 0" @click="handleBulkToggle">
<ToggleRightIcon />
Toggle selected
</button>
</ButtonStyled>
<ButtonStyled color="red">
<button :disabled="selectedTasks.length === 0" @click="handleBulkDelete">
<TrashIcon />
Delete selected
</button>
</ButtonStyled>
<div class="push-right">
<div class="labeled-control-row">
Sort by
<Multiselect
v-model="sortBy"
:searchable="false"
class="small-select"
:options="['Name', 'Type', 'Enabled', 'Schedule']"
:close-on-select="true"
:show-labels="false"
:allow-empty="false"
@update:model-value="updateSort"
/>
<button
v-tooltip="descending ? 'Descending' : 'Ascending'"
class="square-button"
@click="updateDescending"
>
<DescendingIcon v-if="descending" />
<AscendingIcon v-else />
</button>
</div>
</div>
</div>
<div v-if="!isMobile" class="grid-table">
<div class="grid-table__row grid-table__header">
<div>
<Checkbox
:model-value="selectedTasks.length === tasks.length && tasks.length > 0"
@update:model-value="handleSelectAll"
/>
</div>
<div>Type</div>
<div>Task Details</div>
<div class="schedule-col">Schedule</div>
<div class="details-col">Warnings</div>
<div>Enabled</div>
<div>Actions</div>
</div>
<div
v-for="(task, index) in sortedTasks"
:key="`task-${index}`"
class="grid-table__row"
>
<div>
<Checkbox
:model-value="selectedTasks.includes(task)"
@update:model-value="(value) => handleTaskSelect(task, value)"
/>
</div>
<div>
<RaisedBadge
:text="task.action_kind === 'restart' ? 'Restart' : 'Game Command'"
:icon="task.action_kind === 'restart' ? UpdatedIcon : CodeIcon"
/>
</div>
<div>
<span class="mb-1 block font-medium text-primary">{{ task.title }}</span>
<div
v-if="task.action_kind === 'game-command' && task.options?.command"
class="mt-1"
>
<code
class="break-all rounded-sm bg-button-bg px-1 py-0.5 text-xs text-secondary"
>
{{ task.options.command }}
</code>
</div>
</div>
<div class="schedule-col">
<span class="text-sm text-secondary">{{ getHumanReadableCron(task.every) }}</span>
</div>
<div class="details-col">
<div
v-if="task.warn_intervals && task.warn_intervals.length > 0"
class="flex flex-col gap-1"
>
<span class="text-sm font-medium text-primary">
{{ task.warn_intervals.length }} warnings
</span>
<div class="font-mono text-xs text-secondary">
{{ formatWarningIntervals(task.warn_intervals) }}
</div>
</div>
<span v-else class="text-sm italic text-secondary">No warnings</span>
</div>
<div>
<Toggle
:model-value="task.enabled"
@update:model-value="(value) => handleTaskToggle(task, value || false)"
/>
</div>
<div>
<div class="flex gap-1">
<ButtonStyled icon-only circular>
<button :v-tooltip="'Edit Task'" @click="modal?.show(task)">
<EditIcon />
</button>
</ButtonStyled>
<ButtonStyled icon-only circular color="red">
<button @click="handleTaskDelete(task)">
<TrashIcon />
</button>
</ButtonStyled>
</div>
</div>
</div>
</div>
<div v-else class="mt-4 flex flex-col gap-3">
<Card
v-for="(task, index) in sortedTasks"
:key="`mobile-task-${index}`"
class="rounded-lg border !bg-bg p-4 shadow-sm"
>
<div class="flex items-center justify-between gap-2">
<h3 class="mb-0 truncate font-medium">{{ task.title }}</h3>
<Toggle
:model-value="task.enabled"
@update:model-value="(value) => handleTaskToggle(task, value || false)"
/>
</div>
<div class="mt-2 flex items-center gap-2">
<RaisedBadge
:text="task.action_kind === 'restart' ? 'Restart' : 'Command'"
:icon="task.action_kind === 'restart' ? UpdatedIcon : CodeIcon"
class="text-xs"
/>
<div class="ml-auto flex flex-row gap-2">
<ButtonStyled icon-only circular>
<button class="p-1" @click="modal?.show(task)">
<EditIcon />
</button>
</ButtonStyled>
<ButtonStyled icon-only circular color="red">
<button class="p-1" @click="handleTaskDelete(task)">
<TrashIcon />
</button>
</ButtonStyled>
</div>
</div>
</Card>
</div>
</template>
</section>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, onBeforeMount } from "vue";
import { Multiselect } from "vue-multiselect";
import {
PlusIcon,
TrashIcon,
ToggleRightIcon,
EditIcon,
UpdatedIcon,
CodeIcon,
SortAscendingIcon as AscendingIcon,
SortDescendingIcon as DescendingIcon,
} from "@modrinth/assets";
import { Toggle, Checkbox, RaisedBadge, ButtonStyled, Card } from "@modrinth/ui";
import cronstrue from "cronstrue";
import type { ServerSchedule } from "@modrinth/utils";
import { ModrinthServer } from "~/composables/servers/modrinth-servers.ts";
import EditScheduledTaskModal from "~/components/ui/servers/scheduling/EditScheduledTaskModal.vue";
const props = defineProps<{
server: ModrinthServer;
}>();
onBeforeMount(async () => {
await props.server.scheduling.fetch();
});
const selectedTasks = ref<ServerSchedule[]>([]);
const sortBy = ref("Name");
const descending = ref(false);
const modal = ref<typeof EditScheduledTaskModal>();
const isMobile = ref(true);
const tasks = computed(() => props.server.scheduling.tasks as ServerSchedule[]);
const sortedTasks = computed(() => {
const sorted = [...tasks.value];
switch (sortBy.value) {
case "Name":
sorted.sort((a, b) => a.title.localeCompare(b.title));
break;
case "Type":
sorted.sort((a, b) => a.action_kind.localeCompare(b.action_kind));
break;
case "Enabled":
sorted.sort((a, b) => {
if (a.enabled === b.enabled) return 0;
return a.enabled ? -1 : 1;
});
break;
case "Schedule":
sorted.sort((a, b) => a.every.localeCompare(b.every));
break;
}
return descending.value ? sorted.reverse() : sorted;
});
function checkMobile() {
isMobile.value = window.innerWidth < 874;
}
onMounted(() => {
checkMobile();
window.addEventListener("resize", checkMobile);
});
onUnmounted(() => {
window.removeEventListener("resize", checkMobile);
});
function handleSelectAll(selected: boolean): void {
selectedTasks.value = selected ? [...tasks.value] : [];
}
function handleTaskSelect(task: ServerSchedule, selected: boolean): void {
if (selected) {
selectedTasks.value.push(task);
} else {
selectedTasks.value = selectedTasks.value.filter((t) => t !== task);
}
}
async function handleTaskToggle(task: ServerSchedule, enabled: boolean): Promise<void> {
try {
await props.server.scheduling.editTask(task.id, { enabled });
console.log("Toggle task:", task.id, enabled);
} catch (error) {
console.error("Failed to toggle task:", error);
task.enabled = !enabled;
}
}
async function handleTaskDelete(task: ServerSchedule): Promise<void> {
if (confirm(`Are you sure you want to delete "${task.title}"?`)) {
try {
await props.server.scheduling.deleteTask(task);
selectedTasks.value = selectedTasks.value.filter((t) => t !== task);
console.log("Delete task:", task.title);
} catch (error) {
console.error("Failed to delete task:", error);
}
}
}
async function handleBulkToggle(): Promise<void> {
const enabledCount = selectedTasks.value.filter((t) => t.enabled).length;
const shouldEnable = enabledCount < selectedTasks.value.length / 2;
try {
await Promise.all(
selectedTasks.value.map((task) =>
props.server.scheduling.editTask(task.id, { enabled: shouldEnable }),
),
);
console.log("Bulk toggle tasks:", selectedTasks.value.length, "to", shouldEnable);
} catch (error) {
console.error("Failed to bulk toggle tasks:", error);
}
}
async function handleBulkDelete(): Promise<void> {
if (confirm(`Are you sure you want to delete ${selectedTasks.value.length} selected tasks?`)) {
try {
await Promise.all(
selectedTasks.value.map((task) => props.server.scheduling.deleteTask(task)),
);
selectedTasks.value = [];
console.log("Bulk delete completed");
} catch (error) {
console.error("Failed to bulk delete tasks:", error);
}
}
}
function updateSort(): void {
// Trigger reactivity for sortedTasks
}
function updateDescending(): void {
descending.value = !descending.value;
}
function getHumanReadableCron(cronExpression: string): string {
try {
return cronstrue.toString(cronExpression);
} catch {
return cronExpression;
}
}
function formatWarningIntervals(intervals: number[]): string {
return intervals
.sort((a, b) => b - a)
.map((seconds) => {
if (seconds >= 3600) return `${Math.floor(seconds / 3600)}h`;
if (seconds >= 60) return `${Math.floor(seconds / 60)}m`;
return `${seconds}s`;
})
.join(", ");
}
</script>
<style lang="scss" scoped>
.grid-table {
display: grid;
grid-template-columns:
min-content minmax(min-content, 120px) minmax(min-content, 2fr)
minmax(min-content, 1fr) minmax(min-content, 120px) min-content min-content;
border-radius: var(--size-rounded-sm);
overflow: hidden;
margin-top: var(--spacing-card-md);
outline: 1px solid transparent;
.grid-table__row {
display: contents;
> div {
display: flex;
flex-direction: column;
justify-content: center;
padding: var(--spacing-card-sm);
&:first-child {
padding-left: var(--spacing-card-bg);
}
&:last-child {
padding-right: var(--spacing-card-bg);
}
}
&:nth-child(2n + 1) > div {
background-color: var(--color-table-alternate-row);
}
&.grid-table__header > div {
background-color: var(--color-bg);
font-weight: bold;
color: var(--color-text-dark);
padding-top: var(--spacing-card-bg);
padding-bottom: var(--spacing-card-bg);
}
}
}
.labeled-control-row {
flex: 1;
display: flex;
flex-direction: row;
min-width: 0;
align-items: center;
gap: var(--spacing-card-md);
white-space: nowrap;
}
.small-select {
width: -moz-fit-content;
width: fit-content;
}
.push-right {
margin-left: auto;
}
@media (max-width: 1050px) {
.schedule-col {
display: none !important;
}
.grid-table {
grid-template-columns:
min-content minmax(min-content, 120px) minmax(min-content, 2fr) minmax(min-content, 120px)
min-content min-content;
}
}
@media (max-width: 1010px) {
.details-col {
display: none !important;
}
.grid-table {
grid-template-columns:
min-content minmax(min-content, 120px) minmax(min-content, 2fr) minmax(min-content, 120px)
min-content;
}
}
</style>

View File

@@ -200,9 +200,9 @@
<script setup lang="ts">
import { CodeIcon, RadioButtonCheckedIcon, RadioButtonIcon } from "@modrinth/assets";
import { Button, ThemeSelector } from "@modrinth/ui";
import { formatProjectType } from "@modrinth/utils";
import MessageBanner from "~/components/ui/MessageBanner.vue";
import type { DisplayLocation } from "~/plugins/cosmetics";
import { formatProjectType } from "~/plugins/shorthands.js";
import { isDarkTheme, type Theme } from "~/plugins/theme/index.ts";
useHead({

View File

@@ -13,11 +13,6 @@ export default defineNuxtPlugin((nuxtApp) => {
return cosmeticsStore.externalLinksNewTab ? "_blank" : "";
});
nuxtApp.provide("formatBytes", formatBytes);
nuxtApp.provide("formatWallet", formatWallet);
nuxtApp.provide("formatProjectType", formatProjectType);
nuxtApp.provide("formatCategory", formatCategory);
nuxtApp.provide("formatCategoryHeader", formatCategoryHeader);
/*
Only use on the complete list of versions for a project, partial lists will generate
@@ -156,89 +151,10 @@ export const formatMoney = (number, abbreviate = false) => {
}
};
export const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) {
return "0 Bytes";
}
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KiB", "MiB", "GiB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
};
export const capitalizeString = (name) => {
return name ? name.charAt(0).toUpperCase() + name.slice(1) : name;
};
export const formatWallet = (name) => {
if (name === "paypal") {
return "PayPal";
}
return capitalizeString(name);
};
export const formatProjectType = (name) => {
if (name === "resourcepack") {
return "Resource Pack";
} else if (name === "datapack") {
return "Data Pack";
}
return capitalizeString(name);
};
export const formatCategory = (name) => {
if (name === "modloader") {
return "Risugami's ModLoader";
} else if (name === "bungeecord") {
return "BungeeCord";
} else if (name === "liteloader") {
return "LiteLoader";
} else if (name === "neoforge") {
return "NeoForge";
} else if (name === "game-mechanics") {
return "Game Mechanics";
} else if (name === "worldgen") {
return "World Generation";
} else if (name === "core-shaders") {
return "Core Shaders";
} else if (name === "gui") {
return "GUI";
} else if (name === "8x-") {
return "8x or lower";
} else if (name === "512x+") {
return "512x or higher";
} else if (name === "kitchen-sink") {
return "Kitchen Sink";
} else if (name === "path-tracing") {
return "Path Tracing";
} else if (name === "pbr") {
return "PBR";
} else if (name === "datapack") {
return "Data Pack";
} else if (name === "colored-lighting") {
return "Colored Lighting";
} else if (name === "optifine") {
return "OptiFine";
} else if (name === "mrpack") {
return "Modpack";
} else if (name === "minecraft") {
return "Resource Pack";
} else if (name === "vanilla") {
return "Vanilla Shader";
}
return capitalizeString(name);
};
export const formatCategoryHeader = (name) => {
return capitalizeString(name);
};
export const formatVersions = (tag, versionArray) => {
const allVersions = tag.value.gameVersions.slice().reverse();
const allReleases = allVersions.filter((x) => x.version_type === "release");

View File

@@ -28,15 +28,19 @@ CLOUDFLARE_INTEGRATION=false
STORAGE_BACKEND=local
MOCK_FILE_PATH=/tmp/modrinth
BACKBLAZE_KEY_ID=none
BACKBLAZE_KEY=none
BACKBLAZE_BUCKET_ID=none
S3_PUBLIC_BUCKET_NAME=none
S3_PUBLIC_USES_PATH_STYLE_BUCKET=false
S3_PUBLIC_REGION=none
S3_PUBLIC_URL=none
S3_PUBLIC_ACCESS_TOKEN=none
S3_PUBLIC_SECRET=none
S3_ACCESS_TOKEN=none
S3_SECRET=none
S3_URL=none
S3_REGION=none
S3_BUCKET_NAME=none
S3_PRIVATE_BUCKET_NAME=none
S3_PRIVATE_USES_PATH_STYLE_BUCKET=false
S3_PRIVATE_REGION=none
S3_PRIVATE_URL=none
S3_PRIVATE_ACCESS_TOKEN=none
S3_PRIVATE_SECRET=none
# 1 hour
LOCAL_INDEX_INTERVAL=3600

View File

@@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO shared_instance_users (user_id, shared_instance_id, permissions)\n VALUES ($1, $2, $3)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8"
]
},
"nullable": []
},
"hash": "09ebec1a568edf1959f20b33d8ba2b8edb55d93ada8f2243448865163f555d8d"
}

View File

@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, title, owner_id, public, current_version_id\n FROM shared_instances\n WHERE id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "title",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "owner_id",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "public",
"type_info": "Bool"
},
{
"ordinal": 4,
"name": "current_version_id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
true
]
},
"hash": "1ebe19b7b4f10039065967a0b1ca4bb38acc54e4ea5de020fffef7457000fa6e"
}

View File

@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, shared_instance_id, size, sha512, created\n FROM shared_instance_versions\n WHERE shared_instance_id = $1\n ORDER BY created DESC\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "shared_instance_id",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "size",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "sha512",
"type_info": "Bytea"
},
{
"ordinal": 4,
"name": "created",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "265c4d6f33714c8a5cf3137c429e2b57e917e9507942d65f40c1b733209cabf0"
}

View File

@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "\n DELETE FROM shared_instance_versions\n WHERE id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": []
},
"hash": "47130ef29ce5914528e5424fe516a9158a3ea08f8720f6df5b4902cd8094d3bb"
}

View File

@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE shared_instances SET current_version_id = $1 WHERE id = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8"
]
},
"nullable": []
},
"hash": "47ec9f179f1c52213bd32b37621ab13ae43d180b8c86cb2a6fab0253dd4eba55"
}

View File

@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE shared_instances\n SET public = $1\n WHERE id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Bool",
"Int8"
]
},
"nullable": []
},
"hash": "6b166d129b0ee028898620054a58fa4c3641eb2221e522bf50abad4f5e977599"
}

View File

@@ -0,0 +1,17 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO shared_instances (id, title, owner_id, current_version_id)\n VALUES ($1, $2, $3, $4)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Varchar",
"Int8",
"Int8"
]
},
"nullable": []
},
"hash": "6f72c853e139f23322fe6f1f02e4e07e5ae80b5dfca6dc041a03c0c7a30a5cf1"
}

View File

@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE shared_instances\n SET owner_id = $1\n WHERE owner_id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8"
]
},
"nullable": []
},
"hash": "72ae0e8debd06067894a2f7bea279446dd964da4efa49c5464cebde57860f741"
}

View File

@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT EXISTS(SELECT 1 FROM shared_instance_versions WHERE id=$1)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "exists",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
null
]
},
"hash": "7c445073f61e30723416a9690aa9d227d95f2a8f2eb9852833e14c723903988b"
}

View File

@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "\n -- See https://github.com/launchbadge/sqlx/issues/1266 for why we need all the \"as\"\n SELECT\n id as \"id!\",\n title as \"title!\",\n public as \"public!\",\n owner_id as \"owner_id!\",\n current_version_id\n FROM shared_instances\n WHERE owner_id = $1\n UNION\n SELECT\n id as \"id!\",\n title as \"title!\",\n public as \"public!\",\n owner_id as \"owner_id!\",\n current_version_id\n FROM shared_instances\n JOIN shared_instance_users ON id = shared_instance_id\n WHERE user_id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id!",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "title!",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "public!",
"type_info": "Bool"
},
{
"ordinal": 3,
"name": "owner_id!",
"type_info": "Int8"
},
{
"ordinal": 4,
"name": "current_version_id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
null,
null,
null,
null,
null
]
},
"hash": "9c6e18cb19251e54b3b96446ab88d84842152b82c9a0032d1db587d7099b8550"
}

View File

@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE shared_instances\n SET title = $1\n WHERE id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Int8"
]
},
"nullable": []
},
"hash": "9ccaf8ea52b1b6f0880d34cdb4a9405e28c265bef6121b457c4f39cacf00683f"
}

View File

@@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT shared_instance_id, user_id, permissions\n FROM shared_instance_users\n WHERE shared_instance_id = ANY($1)\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "shared_instance_id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "permissions",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Int8Array"
]
},
"nullable": [
false,
false,
false
]
},
"hash": "aec58041cf5e5e68501652336581b8c709645ef29f3b5fb6e8e07fc212b36798"
}

View File

@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, shared_instance_id, size, sha512, created\n FROM shared_instance_versions\n WHERE id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "shared_instance_id",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "size",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "sha512",
"type_info": "Bytea"
},
{
"ordinal": 4,
"name": "created",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "b93253bbc35b24974d13bc8ee0447be2a18275f33f8991d910f693fbcc1ff731"
}

View File

@@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT permissions\n FROM shared_instance_users\n WHERE shared_instance_id = $1 AND user_id = $2\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "permissions",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Int8",
"Int8"
]
},
"nullable": [
false
]
},
"hash": "c3869a595693757ccf81085d0c8eb2231578aff18c93d02ead97c3c07f0b27ea"
}

View File

@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "\n DELETE FROM shared_instances\n WHERE id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": []
},
"hash": "cef730c02bb67b0536d35e5aaca0bd34c3893e8b55bbd126a988137ec7bf1ff9"
}

View File

@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT EXISTS(SELECT 1 FROM shared_instances WHERE id=$1)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "exists",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
null
]
},
"hash": "d8558a8039ade3b383db4f0e095e6826f46c27ab3a21520e9e169fd1491521c4"
}

View File

@@ -0,0 +1,18 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO shared_instance_versions (id, shared_instance_id, size, sha512, created)\n VALUES ($1, $2, $3, $4, $5)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8",
"Bytea",
"Timestamptz"
]
},
"nullable": []
},
"hash": "d8a1d710f86b3df4d99c2d2ec26ec405531e4270be85087122245991ec88473e"
}

View File

@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE shared_instances\n SET current_version_id = (\n SELECT id FROM shared_instance_versions\n WHERE shared_instance_id = $1\n ORDER BY created DESC\n LIMIT 1\n )\n WHERE id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": []
},
"hash": "f6388b5026e25191840d1a157a9ed48aaedab5db381f4efc389b852d9020a0e6"
}

View File

@@ -0,0 +1,43 @@
CREATE TABLE shared_instances (
id BIGINT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
owner_id BIGINT NOT NULL REFERENCES users,
current_version_id BIGINT NULL,
public BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX shared_instances_owner_id ON shared_instances(owner_id);
CREATE TABLE shared_instance_users (
user_id BIGINT NOT NULL REFERENCES users ON DELETE CASCADE,
shared_instance_id BIGINT NOT NULL REFERENCES shared_instances ON DELETE CASCADE,
permissions BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, shared_instance_id)
);
CREATE TABLE shared_instance_invited_users (
id BIGINT PRIMARY KEY,
shared_instance_id BIGINT NOT NULL REFERENCES shared_instances ON DELETE CASCADE,
invited_user_id BIGINT NULL REFERENCES users ON DELETE CASCADE
);
CREATE INDEX shared_instance_invited_users_shared_instance_id ON shared_instance_invited_users(shared_instance_id);
CREATE INDEX shared_instance_invited_users_invited_user_id ON shared_instance_invited_users(invited_user_id);
CREATE TABLE shared_instance_invite_links (
id BIGINT PRIMARY KEY,
shared_instance_id BIGINT NOT NULL REFERENCES shared_instances ON DELETE CASCADE,
expiration timestamptz NULL,
remaining_uses BIGINT CHECK ( remaining_uses >= 0 ) NULL
);
CREATE INDEX shared_instance_invite_links_shared_instance_id ON shared_instance_invite_links(shared_instance_id);
CREATE TABLE shared_instance_versions (
id BIGINT PRIMARY KEY,
shared_instance_id BIGINT NOT NULL REFERENCES shared_instances ON DELETE CASCADE,
size BIGINT NOT NULL,
sha512 bytea NOT NULL,
created timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE shared_instances
ADD FOREIGN KEY (current_version_id) REFERENCES shared_instance_versions(id) ON DELETE SET NULL;

View File

@@ -9,7 +9,7 @@ use ariadne::ids::DecodingError;
#[error("{}", .error_type)]
pub struct OAuthError {
#[source]
pub error_type: OAuthErrorType,
pub error_type: Box<OAuthErrorType>,
pub state: Option<String>,
pub valid_redirect_uri: Option<ValidatedRedirectUri>,
@@ -32,7 +32,7 @@ impl OAuthError {
/// See: IETF RFC 6749 4.1.2.1 (https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1)
pub fn error(error_type: impl Into<OAuthErrorType>) -> Self {
Self {
error_type: error_type.into(),
error_type: Box::new(error_type.into()),
valid_redirect_uri: None,
state: None,
}
@@ -48,7 +48,7 @@ impl OAuthError {
valid_redirect_uri: &ValidatedRedirectUri,
) -> Self {
Self {
error_type: err.into(),
error_type: Box::new(err.into()),
state: state.clone(),
valid_redirect_uri: Some(valid_redirect_uri.clone()),
}
@@ -57,7 +57,7 @@ impl OAuthError {
impl actix_web::ResponseError for OAuthError {
fn status_code(&self) -> StatusCode {
match self.error_type {
match *self.error_type {
OAuthErrorType::AuthenticationError(_)
| OAuthErrorType::FailedScopeParse(_)
| OAuthErrorType::ScopesTooBroad

View File

@@ -101,7 +101,7 @@ mod tests {
);
assert!(validated.is_err_and(|e| matches!(
e.error_type,
*e.error_type,
OAuthErrorType::RedirectUriNotConfigured(_)
)));
}

View File

@@ -10,6 +10,40 @@ use actix_web::HttpRequest;
use actix_web::http::header::{AUTHORIZATION, HeaderValue};
use chrono::Utc;
pub async fn get_maybe_user_from_headers<'a, E>(
req: &HttpRequest,
executor: E,
redis: &RedisPool,
session_queue: &AuthQueue,
required_scopes: Scopes,
) -> Result<Option<(Scopes, User)>, AuthenticationError>
where
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
{
if !req.headers().contains_key(AUTHORIZATION) {
return Ok(None);
}
// Fetch DB user record and minos user from headers
let Some((scopes, db_user)) = get_user_record_from_bearer_token(
req,
None,
executor,
redis,
session_queue,
)
.await?
else {
return Ok(None);
};
if !scopes.contains(required_scopes) {
return Ok(None);
}
Ok(Some((scopes, User::from_full(db_user))))
}
pub async fn get_user_from_headers<'a, E>(
req: &HttpRequest,
executor: E,

View File

@@ -3,8 +3,9 @@ use crate::models::ids::{
ChargeId, CollectionId, FileId, ImageId, NotificationId,
OAuthAccessTokenId, OAuthClientAuthorizationId, OAuthClientId,
OAuthRedirectUriId, OrganizationId, PatId, PayoutId, ProductId,
ProductPriceId, ProjectId, ReportId, SessionId, TeamId, TeamMemberId,
ThreadId, ThreadMessageId, UserSubscriptionId, VersionId,
ProductPriceId, ProjectId, ReportId, SessionId, SharedInstanceId,
SharedInstanceVersionId, TeamId, TeamMemberId, ThreadId, ThreadMessageId,
UserSubscriptionId, VersionId,
};
use ariadne::ids::base62_impl::to_base62;
use ariadne::ids::{UserId, random_base62_rng, random_base62_rng_range};
@@ -88,39 +89,50 @@ macro_rules! generate_bulk_ids {
};
}
macro_rules! impl_db_id_interface {
($id_struct:ident, $db_id_struct:ident, $(, generator: $generator_function:ident @ $db_table:expr, $(bulk_generator: $bulk_generator_function:ident,)?)?) => {
#[derive(Copy, Clone, Debug, Type, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[sqlx(transparent)]
pub struct $db_id_struct(pub i64);
impl From<$id_struct> for $db_id_struct {
fn from(id: $id_struct) -> Self {
Self(id.0 as i64)
}
}
impl From<$db_id_struct> for $id_struct {
fn from(id: $db_id_struct) -> Self {
Self(id.0 as u64)
}
}
$(
generate_ids!(
$generator_function,
$db_id_struct,
"SELECT EXISTS(SELECT 1 FROM " + $db_table + " WHERE id=$1)"
);
$(
generate_bulk_ids!(
$bulk_generator_function,
$db_id_struct,
"SELECT EXISTS(SELECT 1 FROM " + $db_table + " WHERE id = ANY($1))"
);
)?
)?
};
}
macro_rules! db_id_interface {
($id_struct:ident $(, generator: $generator_function:ident @ $db_table:expr, $(bulk_generator: $bulk_generator_function:ident,)?)?) => {
paste! {
#[derive(Copy, Clone, Debug, Type, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[sqlx(transparent)]
pub struct [< DB $id_struct >](pub i64);
impl From<$id_struct> for [< DB $id_struct >] {
fn from(id: $id_struct) -> Self {
Self(id.0 as i64)
}
}
impl From<[< DB $id_struct >]> for $id_struct {
fn from(id: [< DB $id_struct >]) -> Self {
Self(id.0 as u64)
}
}
$(
generate_ids!(
$generator_function,
[< DB $id_struct >],
"SELECT EXISTS(SELECT 1 FROM " + $db_table + " WHERE id=$1)"
);
$(
generate_bulk_ids!(
$bulk_generator_function,
[< DB $id_struct >],
"SELECT EXISTS(SELECT 1 FROM " + $db_table + " WHERE id = ANY($1))"
);
)?
)?
impl_db_id_interface!(
$id_struct,
[< DB $id_struct >],
$(, generator: $generator_function @ $db_table, $(bulk_generator: $bulk_generator_function,)?)?
);
}
};
}
@@ -212,6 +224,14 @@ db_id_interface!(
SessionId,
generator: generate_session_id @ "sessions",
);
db_id_interface!(
SharedInstanceId,
generator: generate_shared_instance_id @ "shared_instances",
);
db_id_interface!(
SharedInstanceVersionId,
generator: generate_shared_instance_version_id @ "shared_instance_versions",
);
db_id_interface!(
TeamId,
generator: generate_team_id @ "teams",

View File

@@ -20,6 +20,7 @@ pub mod product_item;
pub mod project_item;
pub mod report_item;
pub mod session_item;
pub mod shared_instance_item;
pub mod team_item;
pub mod thread_item;
pub mod user_item;

View File

@@ -0,0 +1,335 @@
use crate::database::models::{
DBSharedInstanceId, DBSharedInstanceVersionId, DBUserId,
};
use crate::database::redis::RedisPool;
use crate::models::shared_instances::SharedInstanceUserPermissions;
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use futures_util::TryStreamExt;
use serde::{Deserialize, Serialize};
//region shared_instances
pub struct DBSharedInstance {
pub id: DBSharedInstanceId,
pub title: String,
pub owner_id: DBUserId,
pub public: bool,
pub current_version_id: Option<DBSharedInstanceVersionId>,
}
struct SharedInstanceQueryResult {
id: i64,
title: String,
owner_id: i64,
public: bool,
current_version_id: Option<i64>,
}
impl From<SharedInstanceQueryResult> for DBSharedInstance {
fn from(val: SharedInstanceQueryResult) -> Self {
DBSharedInstance {
id: DBSharedInstanceId(val.id),
title: val.title,
owner_id: DBUserId(val.owner_id),
public: val.public,
current_version_id: val
.current_version_id
.map(DBSharedInstanceVersionId),
}
}
}
impl DBSharedInstance {
pub async fn insert(
&self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<(), sqlx::Error> {
sqlx::query!(
"
INSERT INTO shared_instances (id, title, owner_id, current_version_id)
VALUES ($1, $2, $3, $4)
",
self.id as DBSharedInstanceId,
self.title,
self.owner_id as DBUserId,
self.current_version_id.map(|x| x.0),
)
.execute(&mut **transaction)
.await?;
Ok(())
}
pub async fn get(
id: DBSharedInstanceId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<Self>, sqlx::Error> {
let result = sqlx::query_as!(
SharedInstanceQueryResult,
"
SELECT id, title, owner_id, public, current_version_id
FROM shared_instances
WHERE id = $1
",
id.0,
)
.fetch_optional(exec)
.await?;
Ok(result.map(Into::into))
}
pub async fn list_for_user(
user: DBUserId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<Self>, sqlx::Error> {
let results = sqlx::query_as!(
SharedInstanceQueryResult,
r#"
-- See https://github.com/launchbadge/sqlx/issues/1266 for why we need all the "as"
SELECT
id as "id!",
title as "title!",
public as "public!",
owner_id as "owner_id!",
current_version_id
FROM shared_instances
WHERE owner_id = $1
UNION
SELECT
id as "id!",
title as "title!",
public as "public!",
owner_id as "owner_id!",
current_version_id
FROM shared_instances
JOIN shared_instance_users ON id = shared_instance_id
WHERE user_id = $1
"#,
user.0,
)
.fetch_all(exec)
.await?;
Ok(results.into_iter().map(Into::into).collect())
}
}
//endregion
//region shared_instance_users
const USERS_NAMESPACE: &str = "shared_instance_users";
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct DBSharedInstanceUser {
pub user_id: DBUserId,
pub shared_instance_id: DBSharedInstanceId,
pub permissions: SharedInstanceUserPermissions,
}
impl DBSharedInstanceUser {
pub async fn insert(
&self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<(), sqlx::Error> {
sqlx::query!(
"
INSERT INTO shared_instance_users (user_id, shared_instance_id, permissions)
VALUES ($1, $2, $3)
",
self.user_id as DBUserId,
self.shared_instance_id as DBSharedInstanceId,
self.permissions.bits() as i64,
)
.execute(&mut **transaction)
.await?;
Ok(())
}
pub async fn get_user_permissions(
instance_id: DBSharedInstanceId,
user_id: DBUserId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<SharedInstanceUserPermissions>, super::DatabaseError>
{
let permissions = sqlx::query!(
"
SELECT permissions
FROM shared_instance_users
WHERE shared_instance_id = $1 AND user_id = $2
",
instance_id as DBSharedInstanceId,
user_id as DBUserId,
)
.fetch_optional(exec)
.await?
.map(|x| {
SharedInstanceUserPermissions::from_bits(x.permissions as u64)
.unwrap_or(SharedInstanceUserPermissions::empty())
});
Ok(permissions)
}
pub async fn get_from_instance(
instance_id: DBSharedInstanceId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
redis: &RedisPool,
) -> Result<Vec<DBSharedInstanceUser>, super::DatabaseError> {
Self::get_from_instance_many(&[instance_id], exec, redis).await
}
pub async fn get_from_instance_many(
instance_ids: &[DBSharedInstanceId],
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
redis: &RedisPool,
) -> Result<Vec<DBSharedInstanceUser>, super::DatabaseError> {
if instance_ids.is_empty() {
return Ok(vec![]);
}
let users = redis
.get_cached_keys(
USERS_NAMESPACE,
&instance_ids.iter().map(|id| id.0).collect::<Vec<_>>(),
async |user_ids| {
let users = sqlx::query!(
"
SELECT shared_instance_id, user_id, permissions
FROM shared_instance_users
WHERE shared_instance_id = ANY($1)
",
&user_ids
)
.fetch(exec)
.try_fold(DashMap::new(), |acc: DashMap<_, Vec<_>>, m| {
acc.entry(m.shared_instance_id).or_default().push(
DBSharedInstanceUser {
user_id: DBUserId(m.user_id),
shared_instance_id: DBSharedInstanceId(
m.shared_instance_id,
),
permissions:
SharedInstanceUserPermissions::from_bits(
m.permissions as u64,
)
.unwrap_or(
SharedInstanceUserPermissions::empty(),
),
},
);
async move { Ok(acc) }
})
.await?;
Ok(users)
},
)
.await?;
Ok(users.into_iter().flatten().collect())
}
pub async fn clear_cache(
instance_id: DBSharedInstanceId,
redis: &RedisPool,
) -> Result<(), super::DatabaseError> {
let mut redis = redis.connect().await?;
redis.delete(USERS_NAMESPACE, instance_id.0).await?;
Ok(())
}
}
//endregion
//region shared_instance_versions
pub struct DBSharedInstanceVersion {
pub id: DBSharedInstanceVersionId,
pub shared_instance_id: DBSharedInstanceId,
pub size: u64,
pub sha512: Vec<u8>,
pub created: DateTime<Utc>,
}
struct SharedInstanceVersionQueryResult {
id: i64,
shared_instance_id: i64,
size: i64,
sha512: Vec<u8>,
created: DateTime<Utc>,
}
impl From<SharedInstanceVersionQueryResult> for DBSharedInstanceVersion {
fn from(val: SharedInstanceVersionQueryResult) -> Self {
DBSharedInstanceVersion {
id: DBSharedInstanceVersionId(val.id),
shared_instance_id: DBSharedInstanceId(val.shared_instance_id),
size: val.size as u64,
sha512: val.sha512,
created: val.created,
}
}
}
impl DBSharedInstanceVersion {
pub async fn insert(
&self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<(), sqlx::Error> {
sqlx::query!(
"
INSERT INTO shared_instance_versions (id, shared_instance_id, size, sha512, created)
VALUES ($1, $2, $3, $4, $5)
",
self.id as DBSharedInstanceVersionId,
self.shared_instance_id as DBSharedInstanceId,
self.size as i64,
self.sha512,
self.created,
)
.execute(&mut **transaction)
.await?;
Ok(())
}
pub async fn get(
id: DBSharedInstanceVersionId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Option<Self>, sqlx::Error> {
let result = sqlx::query_as!(
SharedInstanceVersionQueryResult,
"
SELECT id, shared_instance_id, size, sha512, created
FROM shared_instance_versions
WHERE id = $1
",
id as DBSharedInstanceVersionId,
)
.fetch_optional(exec)
.await?;
Ok(result.map(Into::into))
}
pub async fn get_for_instance(
instance_id: DBSharedInstanceId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<Self>, sqlx::Error> {
let results = sqlx::query_as!(
SharedInstanceVersionQueryResult,
"
SELECT id, shared_instance_id, size, sha512, created
FROM shared_instance_versions
WHERE shared_instance_id = $1
ORDER BY created DESC
",
instance_id as DBSharedInstanceId,
)
.fetch_all(exec)
.await?;
Ok(results.into_iter().map(Into::into).collect())
}
}
//endregion

View File

@@ -511,6 +511,18 @@ impl DBUser {
.execute(&mut **transaction)
.await?;
sqlx::query!(
"
UPDATE shared_instances
SET owner_id = $1
WHERE owner_id = $2
",
deleted_user as DBUserId,
id as DBUserId,
)
.execute(&mut **transaction)
.await?;
use futures::TryStreamExt;
let notifications: Vec<i64> = sqlx::query!(
"

View File

@@ -1,108 +0,0 @@
use super::{DeleteFileData, FileHost, FileHostingError, UploadFileData};
use async_trait::async_trait;
use bytes::Bytes;
use reqwest::Response;
use serde::Deserialize;
use sha2::Digest;
mod authorization;
mod delete;
mod upload;
pub struct BackblazeHost {
upload_url_data: authorization::UploadUrlData,
authorization_data: authorization::AuthorizationData,
}
impl BackblazeHost {
pub async fn new(key_id: &str, key: &str, bucket_id: &str) -> Self {
let authorization_data =
authorization::authorize_account(key_id, key).await.unwrap();
let upload_url_data =
authorization::get_upload_url(&authorization_data, bucket_id)
.await
.unwrap();
BackblazeHost {
upload_url_data,
authorization_data,
}
}
}
#[async_trait]
impl FileHost for BackblazeHost {
async fn upload_file(
&self,
content_type: &str,
file_name: &str,
file_bytes: Bytes,
) -> Result<UploadFileData, FileHostingError> {
let content_sha512 = format!("{:x}", sha2::Sha512::digest(&file_bytes));
let upload_data = upload::upload_file(
&self.upload_url_data,
content_type,
file_name,
file_bytes,
)
.await?;
Ok(UploadFileData {
file_id: upload_data.file_id,
file_name: upload_data.file_name,
content_length: upload_data.content_length,
content_sha512,
content_sha1: upload_data.content_sha1,
content_md5: upload_data.content_md5,
content_type: upload_data.content_type,
upload_timestamp: upload_data.upload_timestamp,
})
}
/*
async fn upload_file_streaming(
&self,
content_type: &str,
file_name: &str,
stream: reqwest::Body
) -> Result<UploadFileData, FileHostingError> {
use futures::stream::StreamExt;
let mut data = Vec::new();
while let Some(chunk) = stream.next().await {
data.extend_from_slice(&chunk.map_err(|e| FileHostingError::Other(e))?);
}
self.upload_file(content_type, file_name, data).await
}
*/
async fn delete_file_version(
&self,
file_id: &str,
file_name: &str,
) -> Result<DeleteFileData, FileHostingError> {
let delete_data = delete::delete_file_version(
&self.authorization_data,
file_id,
file_name,
)
.await?;
Ok(DeleteFileData {
file_id: delete_data.file_id,
file_name: delete_data.file_name,
})
}
}
pub async fn process_response<T>(
response: Response,
) -> Result<T, FileHostingError>
where
T: for<'de> Deserialize<'de>,
{
if response.status().is_success() {
Ok(response.json().await?)
} else {
Err(FileHostingError::BackblazeError(response.json().await?))
}
}

View File

@@ -1,81 +0,0 @@
use crate::file_hosting::FileHostingError;
use base64::Engine;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationPermissions {
bucket_id: Option<String>,
bucket_name: Option<String>,
capabilities: Vec<String>,
name_prefix: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationData {
pub absolute_minimum_part_size: i32,
pub account_id: String,
pub allowed: AuthorizationPermissions,
pub api_url: String,
pub authorization_token: String,
pub download_url: String,
pub recommended_part_size: i32,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UploadUrlData {
pub bucket_id: String,
pub upload_url: String,
pub authorization_token: String,
}
pub async fn authorize_account(
key_id: &str,
application_key: &str,
) -> Result<AuthorizationData, FileHostingError> {
let combined_key = format!("{key_id}:{application_key}");
let formatted_key = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(combined_key)
);
let response = reqwest::Client::new()
.get("https://api.backblazeb2.com/b2api/v2/b2_authorize_account")
.header(reqwest::header::CONTENT_TYPE, "application/json")
.header(reqwest::header::AUTHORIZATION, formatted_key)
.send()
.await?;
super::process_response(response).await
}
pub async fn get_upload_url(
authorization_data: &AuthorizationData,
bucket_id: &str,
) -> Result<UploadUrlData, FileHostingError> {
let response = reqwest::Client::new()
.post(
format!(
"{}/b2api/v2/b2_get_upload_url",
authorization_data.api_url
)
.to_string(),
)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.header(
reqwest::header::AUTHORIZATION,
&authorization_data.authorization_token,
)
.body(
serde_json::json!({
"bucketId": bucket_id,
})
.to_string(),
)
.send()
.await?;
super::process_response(response).await
}

View File

@@ -1,38 +0,0 @@
use super::authorization::AuthorizationData;
use crate::file_hosting::FileHostingError;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DeleteFileData {
pub file_id: String,
pub file_name: String,
}
pub async fn delete_file_version(
authorization_data: &AuthorizationData,
file_id: &str,
file_name: &str,
) -> Result<DeleteFileData, FileHostingError> {
let response = reqwest::Client::new()
.post(format!(
"{}/b2api/v2/b2_delete_file_version",
authorization_data.api_url
))
.header(reqwest::header::CONTENT_TYPE, "application/json")
.header(
reqwest::header::AUTHORIZATION,
&authorization_data.authorization_token,
)
.body(
serde_json::json!({
"fileName": file_name,
"fileId": file_id
})
.to_string(),
)
.send()
.await?;
super::process_response(response).await
}

View File

@@ -1,47 +0,0 @@
use super::authorization::UploadUrlData;
use crate::file_hosting::FileHostingError;
use bytes::Bytes;
use hex::ToHex;
use serde::{Deserialize, Serialize};
use sha1::Digest;
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UploadFileData {
pub file_id: String,
pub file_name: String,
pub account_id: String,
pub bucket_id: String,
pub content_length: u32,
pub content_sha1: String,
pub content_md5: Option<String>,
pub content_type: String,
pub upload_timestamp: u64,
}
//Content Types found here: https://www.backblaze.com/b2/docs/content-types.html
pub async fn upload_file(
url_data: &UploadUrlData,
content_type: &str,
file_name: &str,
file_bytes: Bytes,
) -> Result<UploadFileData, FileHostingError> {
let response = reqwest::Client::new()
.post(&url_data.upload_url)
.header(
reqwest::header::AUTHORIZATION,
&url_data.authorization_token,
)
.header("X-Bz-File-Name", file_name)
.header(reqwest::header::CONTENT_TYPE, content_type)
.header(reqwest::header::CONTENT_LENGTH, file_bytes.len())
.header(
"X-Bz-Content-Sha1",
sha1::Sha1::digest(&file_bytes).encode_hex::<String>(),
)
.body(file_bytes)
.send()
.await?;
super::process_response(response).await
}

View File

@@ -1,9 +1,13 @@
use super::{DeleteFileData, FileHost, FileHostingError, UploadFileData};
use super::{
DeleteFileData, FileHost, FileHostPublicity, FileHostingError,
UploadFileData,
};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::Utc;
use hex::ToHex;
use sha2::Digest;
use std::path::PathBuf;
#[derive(Default)]
pub struct MockHost(());
@@ -20,11 +24,10 @@ impl FileHost for MockHost {
&self,
content_type: &str,
file_name: &str,
file_publicity: FileHostPublicity,
file_bytes: Bytes,
) -> Result<UploadFileData, FileHostingError> {
let path =
std::path::Path::new(&dotenvy::var("MOCK_FILE_PATH").unwrap())
.join(file_name.replace("../", ""));
let path = get_file_path(file_name, file_publicity);
std::fs::create_dir_all(
path.parent().ok_or(FileHostingError::InvalidFilename)?,
)?;
@@ -33,8 +36,8 @@ impl FileHost for MockHost {
std::fs::write(path, &*file_bytes)?;
Ok(UploadFileData {
file_id: String::from("MOCK_FILE_ID"),
file_name: file_name.to_string(),
file_publicity,
content_length: file_bytes.len() as u32,
content_sha512,
content_sha1,
@@ -44,20 +47,40 @@ impl FileHost for MockHost {
})
}
async fn delete_file_version(
async fn get_url_for_private_file(
&self,
file_id: &str,
file_name: &str,
_expiry_secs: u32,
) -> Result<String, FileHostingError> {
let cdn_url = dotenvy::var("CDN_URL").unwrap();
Ok(format!("{cdn_url}/private/{file_name}"))
}
async fn delete_file(
&self,
file_name: &str,
file_publicity: FileHostPublicity,
) -> Result<DeleteFileData, FileHostingError> {
let path =
std::path::Path::new(&dotenvy::var("MOCK_FILE_PATH").unwrap())
.join(file_name.replace("../", ""));
let path = get_file_path(file_name, file_publicity);
if path.exists() {
std::fs::remove_file(path)?;
}
Ok(DeleteFileData {
file_id: file_id.to_string(),
file_name: file_name.to_string(),
})
}
}
fn get_file_path(
file_name: &str,
file_publicity: FileHostPublicity,
) -> PathBuf {
let mut path = PathBuf::from(dotenvy::var("MOCK_FILE_PATH").unwrap());
if matches!(file_publicity, FileHostPublicity::Private) {
path.push("private");
}
path.push(file_name.replace("../", ""));
path
}

View File

@@ -1,23 +1,17 @@
use async_trait::async_trait;
use thiserror::Error;
mod backblaze;
mod mock;
mod s3_host;
pub use backblaze::BackblazeHost;
use bytes::Bytes;
pub use mock::MockHost;
pub use s3_host::S3Host;
pub use s3_host::{S3BucketConfig, S3Host};
#[derive(Error, Debug)]
pub enum FileHostingError {
#[error("Error while accessing the data from backblaze")]
HttpError(#[from] reqwest::Error),
#[error("Backblaze error: {0}")]
BackblazeError(serde_json::Value),
#[error("S3 error: {0}")]
S3Error(String),
#[error("S3 error when {0}: {1}")]
S3Error(&'static str, s3::error::S3Error),
#[error("File system error in file hosting: {0}")]
FileSystemError(#[from] std::io::Error),
#[error("Invalid Filename")]
@@ -26,8 +20,8 @@ pub enum FileHostingError {
#[derive(Debug, Clone)]
pub struct UploadFileData {
pub file_id: String,
pub file_name: String,
pub file_publicity: FileHostPublicity,
pub content_length: u32,
pub content_sha512: String,
pub content_sha1: String,
@@ -38,22 +32,34 @@ pub struct UploadFileData {
#[derive(Debug, Clone)]
pub struct DeleteFileData {
pub file_id: String,
pub file_name: String,
}
#[derive(Debug, Copy, Clone)]
pub enum FileHostPublicity {
Public,
Private,
}
#[async_trait]
pub trait FileHost {
async fn upload_file(
&self,
content_type: &str,
file_name: &str,
file_publicity: FileHostPublicity,
file_bytes: Bytes,
) -> Result<UploadFileData, FileHostingError>;
async fn delete_file_version(
async fn get_url_for_private_file(
&self,
file_id: &str,
file_name: &str,
expiry_secs: u32,
) -> Result<String, FileHostingError>;
async fn delete_file(
&self,
file_name: &str,
file_publicity: FileHostPublicity,
) -> Result<DeleteFileData, FileHostingError>;
}

View File

@@ -1,5 +1,6 @@
use crate::file_hosting::{
DeleteFileData, FileHost, FileHostingError, UploadFileData,
DeleteFileData, FileHost, FileHostPublicity, FileHostingError,
UploadFileData,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -10,50 +11,70 @@ use s3::creds::Credentials;
use s3::region::Region;
use sha2::Digest;
pub struct S3BucketConfig {
pub name: String,
pub uses_path_style: bool,
pub region: String,
pub url: String,
pub access_token: String,
pub secret: String,
}
pub struct S3Host {
bucket: Bucket,
public_bucket: Bucket,
private_bucket: Bucket,
}
impl S3Host {
pub fn new(
bucket_name: &str,
bucket_region: &str,
url: &str,
access_token: &str,
secret: &str,
public_bucket: S3BucketConfig,
private_bucket: S3BucketConfig,
) -> Result<S3Host, FileHostingError> {
let bucket = Bucket::new(
bucket_name,
if bucket_region == "r2" {
Region::R2 {
account_id: url.to_string(),
}
} else {
Region::Custom {
region: bucket_region.to_string(),
endpoint: url.to_string(),
}
},
Credentials::new(
Some(access_token),
Some(secret),
None,
None,
None,
)
.map_err(|_| {
FileHostingError::S3Error(
"Error while creating credentials".to_string(),
let create_bucket =
|config: S3BucketConfig| -> Result<_, FileHostingError> {
let mut bucket = Bucket::new(
"",
if config.region == "r2" {
Region::R2 {
account_id: config.url,
}
} else {
Region::Custom {
region: config.region,
endpoint: config.url,
}
},
Credentials {
access_key: Some(config.access_token),
secret_key: Some(config.secret),
..Credentials::anonymous().unwrap()
},
)
})?,
)
.map_err(|_| {
FileHostingError::S3Error(
"Error while creating Bucket instance".to_string(),
)
})?;
.map_err(|e| {
FileHostingError::S3Error("creating Bucket instance", e)
})?;
Ok(S3Host { bucket: *bucket })
bucket.name = config.name;
if config.uses_path_style {
bucket.set_path_style();
} else {
bucket.set_subdomain_style();
}
Ok(bucket)
};
Ok(S3Host {
public_bucket: *create_bucket(public_bucket)?,
private_bucket: *create_bucket(private_bucket)?,
})
}
fn get_bucket(&self, publicity: FileHostPublicity) -> &Bucket {
match publicity {
FileHostPublicity::Public => &self.public_bucket,
FileHostPublicity::Private => &self.private_bucket,
}
}
}
@@ -63,27 +84,24 @@ impl FileHost for S3Host {
&self,
content_type: &str,
file_name: &str,
file_publicity: FileHostPublicity,
file_bytes: Bytes,
) -> Result<UploadFileData, FileHostingError> {
let content_sha1 = sha1::Sha1::digest(&file_bytes).encode_hex();
let content_sha512 = format!("{:x}", sha2::Sha512::digest(&file_bytes));
self.bucket
self.get_bucket(file_publicity)
.put_object_with_content_type(
format!("/{file_name}"),
&file_bytes,
content_type,
)
.await
.map_err(|err| {
FileHostingError::S3Error(format!(
"Error while uploading file {file_name} to S3: {err}"
))
})?;
.map_err(|e| FileHostingError::S3Error("uploading file", e))?;
Ok(UploadFileData {
file_id: file_name.to_string(),
file_name: file_name.to_string(),
file_publicity,
content_length: file_bytes.len() as u32,
content_sha512,
content_sha1,
@@ -93,22 +111,32 @@ impl FileHost for S3Host {
})
}
async fn delete_file_version(
async fn get_url_for_private_file(
&self,
file_id: &str,
file_name: &str,
expiry_secs: u32,
) -> Result<String, FileHostingError> {
let url = self
.private_bucket
.presign_get(format!("/{file_name}"), expiry_secs, None)
.await
.map_err(|e| {
FileHostingError::S3Error("generating presigned URL", e)
})?;
Ok(url)
}
async fn delete_file(
&self,
file_name: &str,
file_publicity: FileHostPublicity,
) -> Result<DeleteFileData, FileHostingError> {
self.bucket
self.get_bucket(file_publicity)
.delete_object(format!("/{file_name}"))
.await
.map_err(|err| {
FileHostingError::S3Error(format!(
"Error while deleting file {file_name} to S3: {err}"
))
})?;
.map_err(|e| FileHostingError::S3Error("deleting file", e))?;
Ok(DeleteFileData {
file_id: file_id.to_string(),
file_name: file_name.to_string(),
})
}

View File

@@ -334,7 +334,7 @@ pub fn app_config(
pub fn check_env_vars() -> bool {
let mut failed = false;
fn check_var<T: std::str::FromStr>(var: &'static str) -> bool {
fn check_var<T: std::str::FromStr>(var: &str) -> bool {
let check = parse_var::<T>(var).is_none();
if check {
warn!(
@@ -361,25 +361,33 @@ pub fn check_env_vars() -> bool {
let storage_backend = dotenvy::var("STORAGE_BACKEND").ok();
match storage_backend.as_deref() {
Some("backblaze") => {
failed |= check_var::<String>("BACKBLAZE_KEY_ID");
failed |= check_var::<String>("BACKBLAZE_KEY");
failed |= check_var::<String>("BACKBLAZE_BUCKET_ID");
}
Some("s3") => {
failed |= check_var::<String>("S3_ACCESS_TOKEN");
failed |= check_var::<String>("S3_SECRET");
failed |= check_var::<String>("S3_URL");
failed |= check_var::<String>("S3_REGION");
failed |= check_var::<String>("S3_BUCKET_NAME");
let mut check_var_set = |var_prefix| {
failed |= check_var::<String>(&format!(
"S3_{var_prefix}_BUCKET_NAME"
));
failed |= check_var::<bool>(&format!(
"S3_{var_prefix}_USES_PATH_STYLE_BUCKET"
));
failed |=
check_var::<String>(&format!("S3_{var_prefix}_REGION"));
failed |= check_var::<String>(&format!("S3_{var_prefix}_URL"));
failed |= check_var::<String>(&format!(
"S3_{var_prefix}_ACCESS_TOKEN"
));
failed |=
check_var::<String>(&format!("S3_{var_prefix}_SECRET"));
};
check_var_set("PUBLIC");
check_var_set("PRIVATE");
}
Some("local") => {
failed |= check_var::<String>("MOCK_FILE_PATH");
}
Some(backend) => {
warn!(
"Variable `STORAGE_BACKEND` contains an invalid value: {}. Expected \"backblaze\", \"s3\", or \"local\".",
backend
"Variable `STORAGE_BACKEND` contains an invalid value: {backend}. Expected \"s3\" or \"local\"."
);
failed |= true;
}

View File

@@ -4,8 +4,9 @@ use actix_web_prom::PrometheusMetricsBuilder;
use clap::Parser;
use labrinth::background_task::BackgroundTask;
use labrinth::database::redis::RedisPool;
use labrinth::file_hosting::S3Host;
use labrinth::file_hosting::{S3BucketConfig, S3Host};
use labrinth::search;
use labrinth::util::env::parse_var;
use labrinth::util::ratelimit::rate_limit_middleware;
use labrinth::{check_env_vars, clickhouse, database, file_hosting, queue};
use std::ffi::CStr;
@@ -51,6 +52,7 @@ async fn main() -> std::io::Result<()> {
if check_env_vars() {
error!("Some environment variables are missing!");
std::process::exit(1);
}
// DSN is from SENTRY_DSN env variable.
@@ -93,24 +95,33 @@ async fn main() -> std::io::Result<()> {
let file_host: Arc<dyn file_hosting::FileHost + Send + Sync> =
match storage_backend.as_str() {
"backblaze" => Arc::new(
file_hosting::BackblazeHost::new(
&dotenvy::var("BACKBLAZE_KEY_ID").unwrap(),
&dotenvy::var("BACKBLAZE_KEY").unwrap(),
&dotenvy::var("BACKBLAZE_BUCKET_ID").unwrap(),
"s3" => {
let config_from_env = |bucket_type| S3BucketConfig {
name: parse_var(&format!("S3_{bucket_type}_BUCKET_NAME"))
.unwrap(),
uses_path_style: parse_var(&format!(
"S3_{bucket_type}_USES_PATH_STYLE_BUCKET"
))
.unwrap(),
region: parse_var(&format!("S3_{bucket_type}_REGION"))
.unwrap(),
url: parse_var(&format!("S3_{bucket_type}_URL")).unwrap(),
access_token: parse_var(&format!(
"S3_{bucket_type}_ACCESS_TOKEN"
))
.unwrap(),
secret: parse_var(&format!("S3_{bucket_type}_SECRET"))
.unwrap(),
};
Arc::new(
S3Host::new(
config_from_env("PUBLIC"),
config_from_env("PRIVATE"),
)
.unwrap(),
)
.await,
),
"s3" => Arc::new(
S3Host::new(
&dotenvy::var("S3_BUCKET_NAME").unwrap(),
&dotenvy::var("S3_REGION").unwrap(),
&dotenvy::var("S3_URL").unwrap(),
&dotenvy::var("S3_ACCESS_TOKEN").unwrap(),
&dotenvy::var("S3_SECRET").unwrap(),
)
.unwrap(),
),
}
"local" => Arc::new(file_hosting::MockHost::new()),
_ => panic!("Invalid storage backend specified. Aborting startup!"),
};

View File

@@ -16,6 +16,7 @@ pub use v3::payouts;
pub use v3::projects;
pub use v3::reports;
pub use v3::sessions;
pub use v3::shared_instances;
pub use v3::teams;
pub use v3::threads;
pub use v3::users;

View File

@@ -17,6 +17,8 @@ base62_id!(ProductPriceId);
base62_id!(ProjectId);
base62_id!(ReportId);
base62_id!(SessionId);
base62_id!(SharedInstanceId);
base62_id!(SharedInstanceVersionId);
base62_id!(TeamId);
base62_id!(TeamMemberId);
base62_id!(ThreadId);

View File

@@ -12,6 +12,7 @@ pub mod payouts;
pub mod projects;
pub mod reports;
pub mod sessions;
pub mod shared_instances;
pub mod teams;
pub mod threads;
pub mod users;

View File

@@ -100,6 +100,24 @@ bitflags::bitflags! {
// only accessible by modrinth-issued sessions
const SESSION_ACCESS = 1 << 39;
// create a shared instance
const SHARED_INSTANCE_CREATE = 1 << 40;
// read a shared instance
const SHARED_INSTANCE_READ = 1 << 41;
// write to a shared instance
const SHARED_INSTANCE_WRITE = 1 << 42;
// delete a shared instance
const SHARED_INSTANCE_DELETE = 1 << 43;
// create a shared instance version
const SHARED_INSTANCE_VERSION_CREATE = 1 << 44;
// read a shared instance version
const SHARED_INSTANCE_VERSION_READ = 1 << 45;
// write to a shared instance version
const SHARED_INSTANCE_VERSION_WRITE = 1 << 46;
// delete a shared instance version
const SHARED_INSTANCE_VERSION_DELETE = 1 << 47;
const NONE = 0b0;
}
}

View File

@@ -0,0 +1,89 @@
use crate::bitflags_serde_impl;
use crate::database::models::shared_instance_item::{
DBSharedInstance, DBSharedInstanceUser, DBSharedInstanceVersion,
};
use crate::models::ids::{SharedInstanceId, SharedInstanceVersionId};
use ariadne::ids::UserId;
use bitflags::bitflags;
use chrono::{DateTime, Utc};
use hex::ToHex;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedInstance {
pub id: SharedInstanceId,
pub title: String,
pub owner: UserId,
pub public: bool,
pub current_version: Option<SharedInstanceVersion>,
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_users: Option<Vec<SharedInstanceUser>>,
}
impl SharedInstance {
pub fn from_db(
instance: DBSharedInstance,
users: Option<Vec<DBSharedInstanceUser>>,
current_version: Option<DBSharedInstanceVersion>,
) -> Self {
SharedInstance {
id: instance.id.into(),
title: instance.title,
owner: instance.owner_id.into(),
public: instance.public,
current_version: current_version.map(Into::into),
additional_users: users
.map(|x| x.into_iter().map(Into::into).collect()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedInstanceVersion {
pub id: SharedInstanceVersionId,
pub shared_instance: SharedInstanceId,
pub size: u64,
pub sha512: String,
pub created: DateTime<Utc>,
}
impl From<DBSharedInstanceVersion> for SharedInstanceVersion {
fn from(value: DBSharedInstanceVersion) -> Self {
let version_id = value.id.into();
let shared_instance_id = value.shared_instance_id.into();
SharedInstanceVersion {
id: version_id,
shared_instance: shared_instance_id,
size: value.size,
sha512: value.sha512.encode_hex(),
created: value.created,
}
}
}
bitflags! {
#[derive(Copy, Clone, Debug)]
pub struct SharedInstanceUserPermissions: u64 {
const EDIT = 1 << 0;
const DELETE = 1 << 1;
const UPLOAD_VERSION = 1 << 2;
const DELETE_VERSION = 1 << 3;
}
}
bitflags_serde_impl!(SharedInstanceUserPermissions, u64);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharedInstanceUser {
pub user: UserId,
pub permissions: SharedInstanceUserPermissions,
}
impl From<DBSharedInstanceUser> for SharedInstanceUser {
fn from(user: DBSharedInstanceUser) -> Self {
SharedInstanceUser {
user: user.user_id.into(),
permissions: user.permissions,
}
}
}

View File

@@ -4,7 +4,7 @@ use crate::auth::{AuthProvider, AuthenticationError, get_user_from_headers};
use crate::database::models::DBUser;
use crate::database::models::flow_item::DBFlow;
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::pats::Scopes;
use crate::models::users::{Badges, Role};
use crate::queue::session::AuthQueue;
@@ -136,6 +136,7 @@ impl TempUser {
let upload_result = upload_image_optimized(
&format!("user/{}", ariadne::ids::UserId::from(user_id)),
FileHostPublicity::Public,
bytes,
ext,
Some(96),

View File

@@ -4,7 +4,7 @@ use crate::database::models::{
collection_item, generate_collection_id, project_item,
};
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::collections::{Collection, CollectionStatus};
use crate::models::ids::{CollectionId, ProjectId};
use crate::models::pats::Scopes;
@@ -12,7 +12,7 @@ use crate::queue::session::AuthQueue;
use crate::routes::ApiError;
use crate::routes::v3::project_creation::CreateError;
use crate::util::img::delete_old_images;
use crate::util::routes::read_from_payload;
use crate::util::routes::read_limited_from_payload;
use crate::util::validate::validation_errors_to_string;
use crate::{database, models};
use actix_web::web::Data;
@@ -413,11 +413,12 @@ pub async fn collection_icon_edit(
delete_old_images(
collection_item.icon_url,
collection_item.raw_icon_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;
let bytes = read_from_payload(
let bytes = read_limited_from_payload(
&mut payload,
262144,
"Icons must be smaller than 256KiB",
@@ -427,6 +428,7 @@ pub async fn collection_icon_edit(
let collection_id: CollectionId = collection_item.id.into();
let upload_result = crate::util::img::upload_image_optimized(
&format!("data/{collection_id}"),
FileHostPublicity::Public,
bytes.freeze(),
&ext.ext,
Some(96),
@@ -493,6 +495,7 @@ pub async fn delete_collection_icon(
delete_old_images(
collection_item.icon_url,
collection_item.raw_icon_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;

View File

@@ -8,13 +8,13 @@ use crate::database::models::{
project_item, report_item, thread_item, version_item,
};
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::ids::{ReportId, ThreadMessageId, VersionId};
use crate::models::images::{Image, ImageContext};
use crate::queue::session::AuthQueue;
use crate::routes::ApiError;
use crate::util::img::upload_image_optimized;
use crate::util::routes::read_from_payload;
use crate::util::routes::read_limited_from_payload;
use actix_web::{HttpRequest, HttpResponse, web};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
@@ -176,7 +176,7 @@ pub async fn images_add(
}
// Upload the image to the file host
let bytes = read_from_payload(
let bytes = read_limited_from_payload(
&mut payload,
1_048_576,
"Icons must be smaller than 1MiB",
@@ -186,6 +186,7 @@ pub async fn images_add(
let content_length = bytes.len();
let upload_result = upload_image_optimized(
"data/cached_images",
FileHostPublicity::Public, // FIXME: Maybe use private images for threads
bytes.freeze(),
&data.ext,
None,

View File

@@ -13,6 +13,8 @@ pub mod payouts;
pub mod project_creation;
pub mod projects;
pub mod reports;
pub mod shared_instance_version_creation;
pub mod shared_instances;
pub mod statistics;
pub mod tags;
pub mod teams;
@@ -36,6 +38,8 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.configure(project_creation::config)
.configure(projects::config)
.configure(reports::config)
.configure(shared_instance_version_creation::config)
.configure(shared_instances::config)
.configure(statistics::config)
.configure(tags::config)
.configure(teams::config)

View File

@@ -1,6 +1,9 @@
use std::{collections::HashSet, fmt::Display, sync::Arc};
use super::ApiError;
use crate::file_hosting::FileHostPublicity;
use crate::models::ids::OAuthClientId;
use crate::util::img::{delete_old_images, upload_image_optimized};
use crate::{
auth::{checks::ValidateAuthorized, get_user_from_headers},
database::{
@@ -23,7 +26,7 @@ use crate::{
};
use crate::{
file_hosting::FileHost, models::oauth_clients::DeleteOAuthClientQueryParam,
util::routes::read_from_payload,
util::routes::read_limited_from_payload,
};
use actix_web::{
HttpRequest, HttpResponse, delete, get, patch, post,
@@ -38,9 +41,6 @@ use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use validator::Validate;
use crate::models::ids::OAuthClientId;
use crate::util::img::{delete_old_images, upload_image_optimized};
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
scope("oauth")
@@ -381,11 +381,12 @@ pub async fn oauth_client_icon_edit(
delete_old_images(
client.icon_url.clone(),
client.raw_icon_url.clone(),
FileHostPublicity::Public,
&***file_host,
)
.await?;
let bytes = read_from_payload(
let bytes = read_limited_from_payload(
&mut payload,
262144,
"Icons must be smaller than 256KiB",
@@ -393,6 +394,7 @@ pub async fn oauth_client_icon_edit(
.await?;
let upload_result = upload_image_optimized(
&format!("data/{client_id}"),
FileHostPublicity::Public,
bytes.freeze(),
&ext.ext,
Some(96),
@@ -447,6 +449,7 @@ pub async fn oauth_client_icon_delete(
delete_old_images(
client.icon_url.clone(),
client.raw_icon_url.clone(),
FileHostPublicity::Public,
&***file_host,
)
.await?;

View File

@@ -8,14 +8,14 @@ use crate::database::models::{
DBOrganization, generate_organization_id, team_item,
};
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::ids::OrganizationId;
use crate::models::pats::Scopes;
use crate::models::teams::{OrganizationPermissions, ProjectPermissions};
use crate::queue::session::AuthQueue;
use crate::routes::v3::project_creation::CreateError;
use crate::util::img::delete_old_images;
use crate::util::routes::read_from_payload;
use crate::util::routes::read_limited_from_payload;
use crate::util::validate::validation_errors_to_string;
use crate::{database, models};
use actix_web::{HttpRequest, HttpResponse, web};
@@ -1088,11 +1088,12 @@ pub async fn organization_icon_edit(
delete_old_images(
organization_item.icon_url,
organization_item.raw_icon_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;
let bytes = read_from_payload(
let bytes = read_limited_from_payload(
&mut payload,
262144,
"Icons must be smaller than 256KiB",
@@ -1102,6 +1103,7 @@ pub async fn organization_icon_edit(
let organization_id: OrganizationId = organization_item.id.into();
let upload_result = crate::util::img::upload_image_optimized(
&format!("data/{organization_id}"),
FileHostPublicity::Public,
bytes.freeze(),
&ext.ext,
Some(96),
@@ -1191,6 +1193,7 @@ pub async fn delete_organization_icon(
delete_old_images(
organization_item.icon_url,
organization_item.raw_icon_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;

View File

@@ -6,7 +6,7 @@ use crate::database::models::loader_fields::{
use crate::database::models::thread_item::ThreadBuilder;
use crate::database::models::{self, DBUser, image_item};
use crate::database::redis::RedisPool;
use crate::file_hosting::{FileHost, FileHostingError};
use crate::file_hosting::{FileHost, FileHostPublicity, FileHostingError};
use crate::models::error::ApiError;
use crate::models::ids::{ImageId, OrganizationId, ProjectId, VersionId};
use crate::models::images::{Image, ImageContext};
@@ -240,18 +240,16 @@ pub struct NewGalleryItem {
}
pub struct UploadedFile {
pub file_id: String,
pub file_name: String,
pub name: String,
pub publicity: FileHostPublicity,
}
pub async fn undo_uploads(
file_host: &dyn FileHost,
uploaded_files: &[UploadedFile],
) -> Result<(), CreateError> {
) -> Result<(), FileHostingError> {
for file in uploaded_files {
file_host
.delete_file_version(&file.file_id, &file.file_name)
.await?;
file_host.delete_file(&file.name, file.publicity).await?;
}
Ok(())
}
@@ -309,13 +307,13 @@ Get logged in user
2. Upload
- Icon: check file format & size
- Upload to backblaze & record URL
- Upload to S3 & record URL
- Project files
- Check for matching version
- File size limits?
- Check file type
- Eventually, malware scan
- Upload to backblaze & create VersionFileBuilder
- Upload to S3 & create VersionFileBuilder
-
3. Creation
@@ -334,7 +332,7 @@ async fn project_create_inner(
redis: &RedisPool,
session_queue: &AuthQueue,
) -> Result<HttpResponse, CreateError> {
// The base URL for files uploaded to backblaze
// The base URL for files uploaded to S3
let cdn_url = dotenvy::var("CDN_URL")?;
// The currently logged in user
@@ -516,6 +514,7 @@ async fn project_create_inner(
let url = format!("data/{project_id}/images");
let upload_result = upload_image_optimized(
&url,
FileHostPublicity::Public,
data.freeze(),
file_extension,
Some(350),
@@ -526,8 +525,8 @@ async fn project_create_inner(
.map_err(|e| CreateError::InvalidIconFormat(e.to_string()))?;
uploaded_files.push(UploadedFile {
file_id: upload_result.raw_url_path.clone(),
file_name: upload_result.raw_url_path,
name: upload_result.raw_url_path,
publicity: FileHostPublicity::Public,
});
gallery_urls.push(crate::models::projects::GalleryItem {
url: upload_result.url,
@@ -1010,6 +1009,7 @@ async fn process_icon_upload(
.await?;
let upload_result = crate::util::img::upload_image_optimized(
&format!("data/{}", to_base62(id)),
FileHostPublicity::Public,
data.freeze(),
file_extension,
Some(96),
@@ -1020,13 +1020,13 @@ async fn process_icon_upload(
.map_err(|e| CreateError::InvalidIconFormat(e.to_string()))?;
uploaded_files.push(UploadedFile {
file_id: upload_result.raw_url_path.clone(),
file_name: upload_result.raw_url_path,
name: upload_result.raw_url_path,
publicity: FileHostPublicity::Public,
});
uploaded_files.push(UploadedFile {
file_id: upload_result.url_path.clone(),
file_name: upload_result.url_path,
name: upload_result.url_path,
publicity: FileHostPublicity::Public,
});
Ok((

View File

@@ -9,7 +9,7 @@ use crate::database::models::thread_item::ThreadMessageBuilder;
use crate::database::models::{DBTeamMember, ids as db_ids, image_item};
use crate::database::redis::RedisPool;
use crate::database::{self, models as db_models};
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models;
use crate::models::ids::ProjectId;
use crate::models::images::ImageContext;
@@ -28,7 +28,7 @@ use crate::search::indexing::remove_documents;
use crate::search::{SearchConfig, SearchError, search_for_project};
use crate::util::img;
use crate::util::img::{delete_old_images, upload_image_optimized};
use crate::util::routes::read_from_payload;
use crate::util::routes::read_limited_from_payload;
use crate::util::validate::validation_errors_to_string;
use actix_web::{HttpRequest, HttpResponse, web};
use ariadne::ids::base62_impl::parse_base62;
@@ -1487,11 +1487,12 @@ pub async fn project_icon_edit(
delete_old_images(
project_item.inner.icon_url,
project_item.inner.raw_icon_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;
let bytes = read_from_payload(
let bytes = read_limited_from_payload(
&mut payload,
262144,
"Icons must be smaller than 256KiB",
@@ -1501,6 +1502,7 @@ pub async fn project_icon_edit(
let project_id: ProjectId = project_item.inner.id.into();
let upload_result = upload_image_optimized(
&format!("data/{project_id}"),
FileHostPublicity::Public,
bytes.freeze(),
&ext.ext,
Some(96),
@@ -1597,6 +1599,7 @@ pub async fn delete_project_icon(
delete_old_images(
project_item.inner.icon_url,
project_item.inner.raw_icon_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;
@@ -1709,7 +1712,7 @@ pub async fn add_gallery_item(
}
}
let bytes = read_from_payload(
let bytes = read_limited_from_payload(
&mut payload,
2 * (1 << 20),
"Gallery image exceeds the maximum of 2MiB.",
@@ -1719,6 +1722,7 @@ pub async fn add_gallery_item(
let id: ProjectId = project_item.inner.id.into();
let upload_result = upload_image_optimized(
&format!("data/{id}/images"),
FileHostPublicity::Public,
bytes.freeze(),
&ext.ext,
Some(350),
@@ -2049,6 +2053,7 @@ pub async fn delete_gallery_item(
delete_old_images(
Some(item.image_url),
Some(item.raw_image_url),
FileHostPublicity::Public,
&***file_host,
)
.await?;

View File

@@ -14,11 +14,11 @@ use crate::models::threads::{MessageBody, ThreadType};
use crate::queue::session::AuthQueue;
use crate::routes::ApiError;
use crate::util::img;
use crate::util::routes::read_typed_from_payload;
use actix_web::{HttpRequest, HttpResponse, web};
use ariadne::ids::UserId;
use ariadne::ids::base62_impl::parse_base62;
use chrono::Utc;
use futures::StreamExt;
use serde::Deserialize;
use sqlx::PgPool;
use validator::Validate;
@@ -63,15 +63,7 @@ pub async fn report_create(
.await?
.1;
let mut bytes = web::BytesMut::new();
while let Some(item) = body.next().await {
bytes.extend_from_slice(&item.map_err(|_| {
ApiError::InvalidInput(
"Error while parsing request payload!".to_string(),
)
})?);
}
let new_report: CreateReport = serde_json::from_slice(bytes.as_ref())?;
let new_report: CreateReport = read_typed_from_payload(&mut body).await?;
let id =
crate::database::models::generate_report_id(&mut transaction).await?;

View File

@@ -0,0 +1,200 @@
use crate::auth::get_user_from_headers;
use crate::database::models::shared_instance_item::{
DBSharedInstance, DBSharedInstanceUser, DBSharedInstanceVersion,
};
use crate::database::models::{
DBSharedInstanceId, DBSharedInstanceVersionId,
generate_shared_instance_version_id,
};
use crate::database::redis::RedisPool;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::ids::{SharedInstanceId, SharedInstanceVersionId};
use crate::models::pats::Scopes;
use crate::models::shared_instances::{
SharedInstanceUserPermissions, SharedInstanceVersion,
};
use crate::queue::session::AuthQueue;
use crate::routes::ApiError;
use crate::routes::v3::project_creation::UploadedFile;
use crate::util::ext::MRPACK_MIME_TYPE;
use actix_web::http::header::ContentLength;
use actix_web::web::Data;
use actix_web::{HttpRequest, HttpResponse, web};
use bytes::BytesMut;
use chrono::Utc;
use futures_util::StreamExt;
use hex::FromHex;
use sqlx::{PgPool, Postgres, Transaction};
use std::sync::Arc;
const MAX_FILE_SIZE: usize = 500 * 1024 * 1024;
const MAX_FILE_SIZE_TEXT: &str = "500 MB";
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.route(
"shared-instance/{id}/version",
web::post().to(shared_instance_version_create),
);
}
#[allow(clippy::too_many_arguments)]
pub async fn shared_instance_version_create(
req: HttpRequest,
pool: Data<PgPool>,
payload: web::Payload,
web::Header(ContentLength(content_length)): web::Header<ContentLength>,
redis: Data<RedisPool>,
file_host: Data<Arc<dyn FileHost + Send + Sync>>,
info: web::Path<(SharedInstanceId,)>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
if content_length > MAX_FILE_SIZE {
return Err(ApiError::InvalidInput(format!(
"File size exceeds the maximum limit of {MAX_FILE_SIZE_TEXT}"
)));
}
let mut transaction = pool.begin().await?;
let mut uploaded_files = vec![];
let result = shared_instance_version_create_inner(
req,
&pool,
payload,
content_length,
&redis,
&***file_host,
info.into_inner().0.into(),
&session_queue,
&mut transaction,
&mut uploaded_files,
)
.await;
if result.is_err() {
let undo_result = super::project_creation::undo_uploads(
&***file_host,
&uploaded_files,
)
.await;
let rollback_result = transaction.rollback().await;
undo_result?;
if let Err(e) = rollback_result {
return Err(e.into());
}
} else {
transaction.commit().await?;
}
result
}
#[allow(clippy::too_many_arguments)]
async fn shared_instance_version_create_inner(
req: HttpRequest,
pool: &PgPool,
mut payload: web::Payload,
content_length: usize,
redis: &RedisPool,
file_host: &dyn FileHost,
instance_id: DBSharedInstanceId,
session_queue: &AuthQueue,
transaction: &mut Transaction<'_, Postgres>,
uploaded_files: &mut Vec<UploadedFile>,
) -> Result<HttpResponse, ApiError> {
let user = get_user_from_headers(
&req,
pool,
redis,
session_queue,
Scopes::SHARED_INSTANCE_VERSION_CREATE,
)
.await?
.1;
let Some(instance) = DBSharedInstance::get(instance_id, pool).await? else {
return Err(ApiError::NotFound);
};
if !user.role.is_mod() && instance.owner_id != user.id.into() {
let permissions = DBSharedInstanceUser::get_user_permissions(
instance_id,
user.id.into(),
pool,
)
.await?;
if let Some(permissions) = permissions {
if !permissions
.contains(SharedInstanceUserPermissions::UPLOAD_VERSION)
{
return Err(ApiError::CustomAuthentication(
"You do not have permission to upload a version for this shared instance.".to_string()
));
}
} else {
return Err(ApiError::NotFound);
}
}
let version_id =
generate_shared_instance_version_id(&mut *transaction).await?;
let mut file_data = BytesMut::new();
while let Some(chunk) = payload.next().await {
let chunk = chunk.map_err(|_| {
ApiError::InvalidInput(
"Unable to parse bytes in payload sent!".to_string(),
)
})?;
if file_data.len() + chunk.len() <= MAX_FILE_SIZE {
file_data.extend_from_slice(&chunk);
} else {
file_data
.extend_from_slice(&chunk[..MAX_FILE_SIZE - file_data.len()]);
break;
}
}
let file_data = file_data.freeze();
let file_path = format!(
"shared_instance/{}.mrpack",
SharedInstanceVersionId::from(version_id),
);
let upload_data = file_host
.upload_file(
MRPACK_MIME_TYPE,
&file_path,
FileHostPublicity::Private,
file_data,
)
.await?;
uploaded_files.push(UploadedFile {
name: file_path,
publicity: upload_data.file_publicity,
});
let sha512 = Vec::<u8>::from_hex(upload_data.content_sha512).unwrap();
let new_version = DBSharedInstanceVersion {
id: version_id,
shared_instance_id: instance_id,
size: content_length as u64,
sha512,
created: Utc::now(),
};
new_version.insert(transaction).await?;
sqlx::query!(
"UPDATE shared_instances SET current_version_id = $1 WHERE id = $2",
new_version.id as DBSharedInstanceVersionId,
instance_id as DBSharedInstanceId,
)
.execute(&mut **transaction)
.await?;
let version: SharedInstanceVersion = new_version.into();
Ok(HttpResponse::Created().json(version))
}

View File

@@ -0,0 +1,612 @@
use crate::auth::get_user_from_headers;
use crate::auth::validate::get_maybe_user_from_headers;
use crate::database::models::shared_instance_item::{
DBSharedInstance, DBSharedInstanceUser, DBSharedInstanceVersion,
};
use crate::database::models::{
DBSharedInstanceId, DBSharedInstanceVersionId, generate_shared_instance_id,
};
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::models::ids::{SharedInstanceId, SharedInstanceVersionId};
use crate::models::pats::Scopes;
use crate::models::shared_instances::{
SharedInstance, SharedInstanceUserPermissions, SharedInstanceVersion,
};
use crate::models::users::User;
use crate::queue::session::AuthQueue;
use crate::routes::ApiError;
use crate::util::routes::read_typed_from_payload;
use actix_web::web::{Data, Redirect};
use actix_web::{HttpRequest, HttpResponse, web};
use futures_util::future::try_join_all;
use serde::Deserialize;
use sqlx::PgPool;
use std::sync::Arc;
use validator::Validate;
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.route("shared-instance", web::post().to(shared_instance_create));
cfg.route("shared-instance", web::get().to(shared_instance_list));
cfg.service(
web::scope("shared-instance")
.route("{id}", web::get().to(shared_instance_get))
.route("{id}", web::patch().to(shared_instance_edit))
.route("{id}", web::delete().to(shared_instance_delete))
.route("{id}/version", web::get().to(shared_instance_version_list)),
);
cfg.service(
web::scope("shared-instance-version")
.route("{id}", web::get().to(shared_instance_version_get))
.route("{id}", web::delete().to(shared_instance_version_delete))
.route(
"{id}/download",
web::get().to(shared_instance_version_download),
),
);
}
#[derive(Deserialize, Validate)]
pub struct CreateSharedInstance {
#[validate(
length(min = 3, max = 64),
custom(function = "crate::util::validate::validate_name")
)]
pub title: String,
#[serde(default)]
pub public: bool,
}
pub async fn shared_instance_create(
req: HttpRequest,
pool: Data<PgPool>,
mut body: web::Payload,
redis: Data<RedisPool>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let new_instance: CreateSharedInstance =
read_typed_from_payload(&mut body).await?;
let mut transaction = pool.begin().await?;
let user = get_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_CREATE,
)
.await?
.1;
let id = generate_shared_instance_id(&mut transaction).await?;
let instance = DBSharedInstance {
id,
title: new_instance.title,
owner_id: user.id.into(),
public: new_instance.public,
current_version_id: None,
};
instance.insert(&mut transaction).await?;
transaction.commit().await?;
Ok(HttpResponse::Created().json(SharedInstance {
id: id.into(),
title: instance.title,
owner: user.id,
public: instance.public,
current_version: None,
additional_users: Some(vec![]),
}))
}
pub async fn shared_instance_list(
req: HttpRequest,
pool: Data<PgPool>,
redis: Data<RedisPool>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let user = get_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_READ,
)
.await?
.1;
// TODO: Something for moderators to be able to see all instances?
let instances =
DBSharedInstance::list_for_user(user.id.into(), &**pool).await?;
let instances = try_join_all(instances.into_iter().map(
async |instance| -> Result<SharedInstance, ApiError> {
let version = if let Some(version_id) = instance.current_version_id
{
DBSharedInstanceVersion::get(version_id, &**pool).await?
} else {
None
};
let instance_id = instance.id;
Ok(SharedInstance::from_db(
instance,
Some(
DBSharedInstanceUser::get_from_instance(
instance_id,
&**pool,
&redis,
)
.await?,
),
version,
))
},
))
.await?;
Ok(HttpResponse::Ok().json(instances))
}
pub async fn shared_instance_get(
req: HttpRequest,
pool: Data<PgPool>,
redis: Data<RedisPool>,
info: web::Path<(SharedInstanceId,)>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let id = info.into_inner().0.into();
let user = get_maybe_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_READ,
)
.await?
.map(|(_, user)| user);
let shared_instance = DBSharedInstance::get(id, &**pool).await?;
if let Some(shared_instance) = shared_instance {
let users =
DBSharedInstanceUser::get_from_instance(id, &**pool, &redis)
.await?;
let privately_accessible = user.is_some_and(|user| {
can_access_instance_privately(&shared_instance, &users, &user)
});
if !shared_instance.public && !privately_accessible {
return Err(ApiError::NotFound);
}
let current_version =
if let Some(version_id) = shared_instance.current_version_id {
DBSharedInstanceVersion::get(version_id, &**pool).await?
} else {
None
};
let shared_instance = SharedInstance::from_db(
shared_instance,
privately_accessible.then_some(users),
current_version,
);
Ok(HttpResponse::Ok().json(shared_instance))
} else {
Err(ApiError::NotFound)
}
}
fn can_access_instance_privately(
instance: &DBSharedInstance,
users: &[DBSharedInstanceUser],
user: &User,
) -> bool {
user.role.is_mod()
|| instance.owner_id == user.id.into()
|| users.iter().any(|x| x.user_id == user.id.into())
}
#[derive(Deserialize, Validate)]
pub struct EditSharedInstance {
#[validate(
length(min = 3, max = 64),
custom(function = "crate::util::validate::validate_name")
)]
pub title: Option<String>,
pub public: Option<bool>,
}
pub async fn shared_instance_edit(
req: HttpRequest,
pool: Data<PgPool>,
mut body: web::Payload,
redis: Data<RedisPool>,
info: web::Path<(SharedInstanceId,)>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let id = info.into_inner().0.into();
let edit_instance: EditSharedInstance =
read_typed_from_payload(&mut body).await?;
let mut transaction = pool.begin().await?;
let user = get_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_WRITE,
)
.await?
.1;
let Some(instance) = DBSharedInstance::get(id, &**pool).await? else {
return Err(ApiError::NotFound);
};
if !user.role.is_mod() && instance.owner_id != user.id.into() {
let permissions = DBSharedInstanceUser::get_user_permissions(
id,
user.id.into(),
&**pool,
)
.await?;
if let Some(permissions) = permissions {
if !permissions.contains(SharedInstanceUserPermissions::EDIT) {
return Err(ApiError::CustomAuthentication(
"You do not have permission to edit this shared instance."
.to_string(),
));
}
} else {
return Err(ApiError::NotFound);
}
}
if let Some(title) = edit_instance.title {
sqlx::query!(
"
UPDATE shared_instances
SET title = $1
WHERE id = $2
",
title,
id as DBSharedInstanceId,
)
.execute(&mut *transaction)
.await?;
}
if let Some(public) = edit_instance.public {
sqlx::query!(
"
UPDATE shared_instances
SET public = $1
WHERE id = $2
",
public,
id as DBSharedInstanceId,
)
.execute(&mut *transaction)
.await?;
}
transaction.commit().await?;
Ok(HttpResponse::NoContent().body(""))
}
pub async fn shared_instance_delete(
req: HttpRequest,
pool: Data<PgPool>,
redis: Data<RedisPool>,
info: web::Path<(SharedInstanceId,)>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let id: DBSharedInstanceId = info.into_inner().0.into();
let user = get_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_DELETE,
)
.await?
.1;
let Some(instance) = DBSharedInstance::get(id, &**pool).await? else {
return Err(ApiError::NotFound);
};
if !user.role.is_mod() && instance.owner_id != user.id.into() {
let permissions = DBSharedInstanceUser::get_user_permissions(
id,
user.id.into(),
&**pool,
)
.await?;
if let Some(permissions) = permissions {
if !permissions.contains(SharedInstanceUserPermissions::DELETE) {
return Err(ApiError::CustomAuthentication(
"You do not have permission to delete this shared instance.".to_string()
));
}
} else {
return Err(ApiError::NotFound);
}
}
sqlx::query!(
"
DELETE FROM shared_instances
WHERE id = $1
",
id as DBSharedInstanceId,
)
.execute(&**pool)
.await?;
DBSharedInstanceUser::clear_cache(id, &redis).await?;
Ok(HttpResponse::NoContent().body(""))
}
pub async fn shared_instance_version_list(
req: HttpRequest,
pool: Data<PgPool>,
redis: Data<RedisPool>,
info: web::Path<(SharedInstanceId,)>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let id = info.into_inner().0.into();
let user = get_maybe_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_READ,
)
.await?
.map(|(_, user)| user);
let shared_instance = DBSharedInstance::get(id, &**pool).await?;
if let Some(shared_instance) = shared_instance {
if !can_access_instance_as_maybe_user(
&pool,
&redis,
&shared_instance,
user,
)
.await?
{
return Err(ApiError::NotFound);
}
let versions =
DBSharedInstanceVersion::get_for_instance(id, &**pool).await?;
let versions = versions
.into_iter()
.map(Into::into)
.collect::<Vec<SharedInstanceVersion>>();
Ok(HttpResponse::Ok().json(versions))
} else {
Err(ApiError::NotFound)
}
}
pub async fn shared_instance_version_get(
req: HttpRequest,
pool: Data<PgPool>,
redis: Data<RedisPool>,
info: web::Path<(SharedInstanceVersionId,)>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let version_id = info.into_inner().0.into();
let user = get_maybe_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_READ,
)
.await?
.map(|(_, user)| user);
let version = DBSharedInstanceVersion::get(version_id, &**pool).await?;
if let Some(version) = version {
let instance =
DBSharedInstance::get(version.shared_instance_id, &**pool).await?;
if let Some(instance) = instance {
if !can_access_instance_as_maybe_user(
&pool, &redis, &instance, user,
)
.await?
{
return Err(ApiError::NotFound);
}
let version: SharedInstanceVersion = version.into();
Ok(HttpResponse::Ok().json(version))
} else {
Err(ApiError::NotFound)
}
} else {
Err(ApiError::NotFound)
}
}
async fn can_access_instance_as_maybe_user(
pool: &PgPool,
redis: &RedisPool,
instance: &DBSharedInstance,
user: Option<User>,
) -> Result<bool, ApiError> {
if instance.public {
return Ok(true);
}
let users =
DBSharedInstanceUser::get_from_instance(instance.id, pool, redis)
.await?;
Ok(user.is_some_and(|user| {
can_access_instance_privately(instance, &users, &user)
}))
}
pub async fn shared_instance_version_delete(
req: HttpRequest,
pool: Data<PgPool>,
redis: Data<RedisPool>,
info: web::Path<(SharedInstanceVersionId,)>,
session_queue: Data<AuthQueue>,
) -> Result<HttpResponse, ApiError> {
let version_id = info.into_inner().0.into();
let user = get_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_VERSION_DELETE,
)
.await?
.1;
let shared_instance_version =
DBSharedInstanceVersion::get(version_id, &**pool).await?;
if let Some(shared_instance_version) = shared_instance_version {
let shared_instance = DBSharedInstance::get(
shared_instance_version.shared_instance_id,
&**pool,
)
.await?;
if let Some(shared_instance) = shared_instance {
if !user.role.is_mod() && shared_instance.owner_id != user.id.into()
{
let permissions = DBSharedInstanceUser::get_user_permissions(
shared_instance.id,
user.id.into(),
&**pool,
)
.await?;
if let Some(permissions) = permissions {
if !permissions
.contains(SharedInstanceUserPermissions::DELETE)
{
return Err(ApiError::CustomAuthentication(
"You do not have permission to delete this shared instance version.".to_string()
));
}
} else {
return Err(ApiError::NotFound);
}
}
delete_instance_version(shared_instance.id, version_id, &pool)
.await?;
Ok(HttpResponse::NoContent().body(""))
} else {
Err(ApiError::NotFound)
}
} else {
Err(ApiError::NotFound)
}
}
async fn delete_instance_version(
instance_id: DBSharedInstanceId,
version_id: DBSharedInstanceVersionId,
pool: &PgPool,
) -> Result<(), ApiError> {
let mut transaction = pool.begin().await?;
sqlx::query!(
"
DELETE FROM shared_instance_versions
WHERE id = $1
",
version_id as DBSharedInstanceVersionId,
)
.execute(&mut *transaction)
.await?;
sqlx::query!(
"
UPDATE shared_instances
SET current_version_id = (
SELECT id FROM shared_instance_versions
WHERE shared_instance_id = $1
ORDER BY created DESC
LIMIT 1
)
WHERE id = $1
",
instance_id as DBSharedInstanceId,
)
.execute(&mut *transaction)
.await?;
transaction.commit().await?;
Ok(())
}
pub async fn shared_instance_version_download(
req: HttpRequest,
pool: Data<PgPool>,
redis: Data<RedisPool>,
file_host: Data<Arc<dyn FileHost + Send + Sync>>,
info: web::Path<(SharedInstanceVersionId,)>,
session_queue: Data<AuthQueue>,
) -> Result<Redirect, ApiError> {
let version_id = info.into_inner().0.into();
let user = get_maybe_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Scopes::SHARED_INSTANCE_VERSION_READ,
)
.await?
.map(|(_, user)| user);
let version = DBSharedInstanceVersion::get(version_id, &**pool).await?;
if let Some(version) = version {
let instance =
DBSharedInstance::get(version.shared_instance_id, &**pool).await?;
if let Some(instance) = instance {
if !can_access_instance_as_maybe_user(
&pool, &redis, &instance, user,
)
.await?
{
return Err(ApiError::NotFound);
}
let file_name = format!(
"shared_instance/{}.mrpack",
SharedInstanceVersionId::from(version_id)
);
let url =
file_host.get_url_for_private_file(&file_name, 180).await?;
Ok(Redirect::to(url).see_other())
} else {
Err(ApiError::NotFound)
}
} else {
Err(ApiError::NotFound)
}
}

View File

@@ -6,7 +6,7 @@ use crate::database::models::image_item;
use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::thread_item::ThreadMessageBuilder;
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::ids::{ThreadId, ThreadMessageId};
use crate::models::images::{Image, ImageContext};
use crate::models::notifications::NotificationBody;
@@ -606,7 +606,12 @@ pub async fn message_delete(
for image in images {
let name = image.url.split(&format!("{cdn_url}/")).nth(1);
if let Some(icon_path) = name {
file_host.delete_file_version("", icon_path).await?;
file_host
.delete_file(
icon_path,
FileHostPublicity::Public, // FIXME: Consider using private file storage?
)
.await?;
}
database::DBImage::remove(image.id, &mut transaction, &redis)
.await?;

View File

@@ -1,6 +1,7 @@
use std::{collections::HashMap, sync::Arc};
use super::{ApiError, oauth_clients::get_user_clients};
use crate::file_hosting::FileHostPublicity;
use crate::util::img::delete_old_images;
use crate::{
auth::{filter_visible_projects, get_user_from_headers},
@@ -14,7 +15,10 @@ use crate::{
users::{Badges, Role},
},
queue::session::AuthQueue,
util::{routes::read_from_payload, validate::validation_errors_to_string},
util::{
routes::read_limited_from_payload,
validate::validation_errors_to_string,
},
};
use actix_web::{HttpRequest, HttpResponse, web};
use ariadne::ids::UserId;
@@ -576,11 +580,12 @@ pub async fn user_icon_edit(
delete_old_images(
actual_user.avatar_url,
actual_user.raw_avatar_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;
let bytes = read_from_payload(
let bytes = read_limited_from_payload(
&mut payload,
262144,
"Icons must be smaller than 256KiB",
@@ -590,6 +595,7 @@ pub async fn user_icon_edit(
let user_id: UserId = actual_user.id.into();
let upload_result = crate::util::img::upload_image_optimized(
&format!("data/{user_id}"),
FileHostPublicity::Public,
bytes.freeze(),
&ext.ext,
Some(96),
@@ -648,6 +654,7 @@ pub async fn user_icon_delete(
delete_old_images(
actual_user.avatar_url,
actual_user.raw_avatar_url,
FileHostPublicity::Public,
&***file_host,
)
.await?;

View File

@@ -9,7 +9,7 @@ use crate::database::models::version_item::{
};
use crate::database::models::{self, DBOrganization, image_item};
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::ids::{ImageId, ProjectId, VersionId};
use crate::models::images::{Image, ImageContext};
use crate::models::notifications::NotificationBody;
@@ -952,12 +952,12 @@ pub async fn upload_file(
format!("data/{}/versions/{}/{}", project_id, version_id, &file_name);
let upload_data = file_host
.upload_file(content_type, &file_path, data)
.upload_file(content_type, &file_path, FileHostPublicity::Public, data)
.await?;
uploaded_files.push(UploadedFile {
file_id: upload_data.file_id,
file_name: file_path,
name: file_path,
publicity: FileHostPublicity::Public,
});
let sha1_bytes = upload_data.content_sha1.into_bytes();

View File

@@ -1,6 +1,6 @@
use std::str::FromStr;
pub fn parse_var<T: FromStr>(var: &'static str) -> Option<T> {
pub fn parse_var<T: FromStr>(var: &str) -> Option<T> {
dotenvy::var(var).ok().and_then(|i| i.parse().ok())
}
pub fn parse_strings_from_var(var: &'static str) -> Option<Vec<String>> {

View File

@@ -1,3 +1,5 @@
pub const MRPACK_MIME_TYPE: &str = "application/x-modrinth-modpack+zip";
pub fn get_image_content_type(extension: &str) -> Option<&'static str> {
match extension {
"bmp" => Some("image/bmp"),
@@ -24,7 +26,7 @@ pub fn project_file_type(ext: &str) -> Option<&str> {
match ext {
"jar" => Some("application/java-archive"),
"zip" | "litemod" => Some("application/zip"),
"mrpack" => Some("application/x-modrinth-modpack+zip"),
"mrpack" => Some(MRPACK_MIME_TYPE),
_ => None,
}
}

View File

@@ -1,7 +1,7 @@
use crate::database;
use crate::database::models::image_item;
use crate::database::redis::RedisPool;
use crate::file_hosting::FileHost;
use crate::file_hosting::{FileHost, FileHostPublicity};
use crate::models::images::ImageContext;
use crate::routes::ApiError;
use color_thief::ColorFormat;
@@ -38,11 +38,14 @@ pub struct UploadImageResult {
pub raw_url: String,
pub raw_url_path: String,
pub publicity: FileHostPublicity,
pub color: Option<u32>,
}
pub async fn upload_image_optimized(
upload_folder: &str,
publicity: FileHostPublicity,
bytes: bytes::Bytes,
file_extension: &str,
target_width: Option<u32>,
@@ -80,6 +83,7 @@ pub async fn upload_image_optimized(
target_width.unwrap_or(0),
processed_image_ext
),
publicity,
processed_image,
)
.await?,
@@ -92,6 +96,7 @@ pub async fn upload_image_optimized(
.upload_file(
content_type,
&format!("{upload_folder}/{hash}.{file_extension}"),
publicity,
bytes,
)
.await?;
@@ -107,6 +112,9 @@ pub async fn upload_image_optimized(
raw_url: url,
raw_url_path: upload_data.file_name,
publicity,
color,
})
}
@@ -165,6 +173,7 @@ fn convert_to_webp(img: &DynamicImage) -> Result<Vec<u8>, ImageError> {
pub async fn delete_old_images(
image_url: Option<String>,
raw_image_url: Option<String>,
publicity: FileHostPublicity,
file_host: &dyn FileHost,
) -> Result<(), ApiError> {
let cdn_url = dotenvy::var("CDN_URL")?;
@@ -173,7 +182,7 @@ pub async fn delete_old_images(
let name = image_url.split(&cdn_url_start).nth(1);
if let Some(icon_path) = name {
file_host.delete_file_version("", icon_path).await?;
file_host.delete_file(icon_path, publicity).await?;
}
}
@@ -181,7 +190,7 @@ pub async fn delete_old_images(
let name = raw_image_url.split(&cdn_url_start).nth(1);
if let Some(icon_path) = name {
file_host.delete_file_version("", icon_path).await?;
file_host.delete_file(icon_path, publicity).await?;
}
}

View File

@@ -1,11 +1,14 @@
use crate::routes::ApiError;
use crate::routes::v3::project_creation::CreateError;
use crate::util::validate::validation_errors_to_string;
use actix_multipart::Field;
use actix_web::web::Payload;
use bytes::BytesMut;
use futures::StreamExt;
use serde::de::DeserializeOwned;
use validator::Validate;
pub async fn read_from_payload(
pub async fn read_limited_from_payload(
payload: &mut Payload,
cap: usize,
err_msg: &'static str,
@@ -25,6 +28,28 @@ pub async fn read_from_payload(
Ok(bytes)
}
pub async fn read_typed_from_payload<T>(
payload: &mut Payload,
) -> Result<T, ApiError>
where
T: DeserializeOwned + Validate,
{
let mut bytes = BytesMut::new();
while let Some(item) = payload.next().await {
bytes.extend_from_slice(&item.map_err(|_| {
ApiError::InvalidInput(
"Unable to parse bytes in payload sent!".to_string(),
)
})?);
}
let parsed: T = serde_json::from_slice(&bytes)?;
parsed.validate().map_err(|err| {
ApiError::InvalidInput(validation_errors_to_string(err, None))
})?;
Ok(parsed)
}
pub async fn read_from_field(
field: &mut Field,
cap: usize,

View File

@@ -71,7 +71,6 @@ pub enum DecodingError {
}
#[macro_export]
#[doc(hidden)]
macro_rules! impl_base62_display {
($struct:ty) => {
impl std::fmt::Display for $struct {

View File

@@ -1,12 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="lucide lucide-calendar-sync-icon lucide-calendar-sync">
<path d="M11 10v4h4"/>
<path d="m11 14 1.535-1.605a5 5 0 0 1 8 1.5"/>
<path d="M16 2v4"/>
<path d="m21 18-1.535 1.605a5 5 0 0 1-8-1.5"/>
<path d="M21 22v-4h-4"/>
<path d="M21 8.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h4.3"/>
<path d="M3 10h4"/>
<path d="M8 2v4"/>
</svg>

Before

Width:  |  Height:  |  Size: 551 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-clock-icon lucide-clock"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>

Before

Width:  |  Height:  |  Size: 302 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-toggle-right-icon lucide-toggle-right"><circle cx="15" cy="12" r="3"/><rect width="20" height="14" x="2" y="5" rx="7"/></svg>

Before

Width:  |  Height:  |  Size: 327 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-triangle-alert-icon lucide-triangle-alert"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>

Before

Width:  |  Height:  |  Size: 376 B

View File

@@ -66,7 +66,6 @@ import _ChevronRightIcon from './icons/chevron-right.svg?component'
import _ClearIcon from './icons/clear.svg?component'
import _ClientIcon from './icons/client.svg?component'
import _ClipboardCopyIcon from './icons/clipboard-copy.svg?component'
import _ClockIcon from './icons/clock.svg?component'
import _CodeIcon from './icons/code.svg?component'
import _CoffeeIcon from './icons/coffee.svg?component'
import _CoinsIcon from './icons/coins.svg?component'
@@ -183,7 +182,6 @@ import _TagsIcon from './icons/tags.svg?component'
import _TerminalSquareIcon from './icons/terminal-square.svg?component'
import _TransferIcon from './icons/transfer.svg?component'
import _TrashIcon from './icons/trash.svg?component'
import _TriangleAlertIcon from './icons/triangle-alert.svg?component'
import _UndoIcon from './icons/undo.svg?component'
import _RedoIcon from './icons/redo.svg?component'
import _UnknownIcon from './icons/unknown.svg?component'
@@ -212,8 +210,6 @@ import _CPUIcon from './icons/cpu.svg?component'
import _LoaderIcon from './icons/loader.svg?component'
import _ImportIcon from './icons/import.svg?component'
import _TimerIcon from './icons/timer.svg?component'
import _CalendarSyncIcon from './icons/calendar-sync.svg?component'
import _ToggleRightIcon from './icons/toggle-right.svg?component'
// Editor Icons
import _BoldIcon from './icons/bold.svg?component'
@@ -289,7 +285,6 @@ export const ChevronRightIcon = _ChevronRightIcon
export const ClearIcon = _ClearIcon
export const ClientIcon = _ClientIcon
export const ClipboardCopyIcon = _ClipboardCopyIcon
export const ClockIcon = _ClockIcon
export const CodeIcon = _CodeIcon
export const CoffeeIcon = _CoffeeIcon
export const CoinsIcon = _CoinsIcon
@@ -446,6 +441,3 @@ export const LoaderIcon = _LoaderIcon
export const ImportIcon = _ImportIcon
export const CardIcon = _CardIcon
export const TimerIcon = _TimerIcon
export const CalendarSyncIcon = _CalendarSyncIcon
export const ToggleRightIcon = _ToggleRightIcon
export const TriangleAlertIcon = _TriangleAlertIcon

View File

@@ -84,6 +84,10 @@
--color-platform-velocity: #4b98b0;
--color-platform-waterfall: #5f83cb;
--color-platform-sponge: #c49528;
--color-platform-ornithe: #6097ca;
--color-platform-bta-babric: #5ba938;
--color-platform-legacy-fabric: #6879f6;
--color-platform-nilloader: #dd5088;
--hover-brightness: 0.9;
}
@@ -198,6 +202,10 @@ html {
--color-platform-velocity: #83d5ef;
--color-platform-waterfall: #78a4fb;
--color-platform-sponge: #f9e580;
--color-platform-ornithe: #87c7ff;
--color-platform-bta-babric: #72cc4a;
--color-platform-legacy-fabric: #6879f6;
--color-platform-nilloader: #f45e9a;
--hover-brightness: 1.25;

View File

@@ -33,7 +33,6 @@
"@types/markdown-it": "^14.1.1",
"@vintl/how-ago": "^3.0.1",
"apexcharts": "^3.44.0",
"cronstrue": "^2.61.0",
"dayjs": "^1.11.10",
"floating-vue": "^5.2.2",
"highlight.js": "^11.9.0",

View File

@@ -4,10 +4,10 @@
v-for="item in items"
:key="formatLabel(item)"
class="btn"
:class="{ selected: isSelected(item), capitalize: capitalize }"
:class="{ selected: selected === item, capitalize: capitalize }"
@click="toggleItem(item)"
>
<CheckIcon v-if="isSelected(item)" />
<CheckIcon v-if="selected === item" />
<span>{{ formatLabel(item) }}</span>
</Button>
</div>
@@ -23,48 +23,26 @@ const props = withDefaults(
formatLabel?: (item: T) => string
neverEmpty?: boolean
capitalize?: boolean
multi?: boolean
}>(),
{
neverEmpty: true,
// Intentional any type, as this default should only be used for primitives (string or number)
formatLabel: (item) => item.toString(),
capitalize: true,
multi: false,
},
)
const selected = defineModel<T | null | T[]>()
const selected = defineModel<T | null>()
// If one always has to be selected, default to the first one
if (props.items.length > 0 && props.neverEmpty && !selected.value) {
selected.value = props.multi ? [props.items[0]] : props.items[0]
}
function isSelected(item: T): boolean {
if (props.multi) {
return Array.isArray(selected.value) && selected.value.includes(item)
}
return selected.value === item
selected.value = props.items[0]
}
function toggleItem(item: T) {
if (props.multi) {
const currentSelection = Array.isArray(selected.value) ? selected.value : []
const isCurrentlySelected = currentSelection.includes(item)
if (isCurrentlySelected) {
if (!props.neverEmpty || currentSelection.length > 1) {
selected.value = currentSelection.filter((i) => i !== item)
}
} else {
selected.value = [...currentSelection, item]
}
if (selected.value === item && !props.neverEmpty) {
selected.value = null
} else {
if (selected.value === item && !props.neverEmpty) {
selected.value = null
} else {
selected.value = item
}
selected.value = item
}
}
</script>

View File

@@ -1,17 +0,0 @@
<template>
<div class="flex items-center gap-2 w-fit px-3 py-1 bg-button-bg rounded-full text-sm">
<component :is="icon" v-if="icon" class="w-4 h-4" />
<span class="whitespace-nowrap">
{{ text }}
</span>
</div>
</template>
<script setup lang="ts">
import type { Component } from 'vue'
defineProps<{
text: string
icon?: Component
}>()
</script>

Some files were not shown because too many files have changed in this diff Show More