Add shared mods management

Add the ability to manage a set of mods to be shared by the master
server to the rest of the cluster.  This implements storage, uploads,
downloads, deletetion, and listing details of mods but does not actually
do anything with the stored mods.
This commit is contained in:
Hornwitser committed 2022-09-13 19:15:46 +02:00
1 parent 2ab915cc00
commit 3b57c1e0ae
23 files changed
+1311 -5

No files matched your search

+165
View File
@@ -0,0 +1,165 @@
import React, { Fragment, useContext } from "react";
import { Button, Descriptions, Grid, PageHeader, Popconfirm, Space, Table, Typography, Upload } from "antd";
import UploadOutlined from "@ant-design/icons/UploadOutlined";
import { libHelpers, libLink } from "@clusterio/lib";
import { useAccount } from "../model/account";
import { useModList } from "../model/mods";
import { notifyErrorHandler } from "../util/notify";
import ControlContext from "./ControlContext";
import PageLayout from "./PageLayout";
import PluginExtra from "./PluginExtra";
const { useBreakpoint } = Grid;
const strcmp = new Intl.Collator(undefined, { numerice: "true", sensitivity: "base" }).compare;
export default function ModsPage() {
let account = useAccount();
let control = useContext(ControlContext);
let [modList] = useModList();
let screens = useBreakpoint();
function actions(mod) {
return <Space>
{account.hasPermission("core.mod.download")
&& <Typography.Link
onClick={() => {
libLink.messages.downloadMod.send(
control, { name: mod.name, version: mod.version }
).then(response => {
let url = new URL(webRoot, document.location);
url.pathname += `api/stream/${response.stream_id}`;
document.location = url;
}).catch(
notifyErrorHandler("Error downloading save")
);
}}
>download</Typography.Link>
}
{account.hasPermission("core.mod.delete")
&& <Popconfirm
title="Are you sure you want to delete this mod?"
onConfirm={event => {
libLink.messages.deleteMod.send(
control, { name: mod.name, version: mod.version }
).catch(notifyErrorHandler("Error deleting mod"));
}}
okText="Delete"
okButtonProps={{ danger: true }}
>
<Typography.Link type="danger">delete</Typography.Link>
</Popconfirm>
}
</Space>;
}
let uploadButton;
if (account.hasPermission("core.mod.upload")) {
uploadButton = <Upload
name="file"
accept=".zip"
multiple
headers={{
"X-Access-Token": control.connector.token,
}}
action={`${webRoot}api/upload-mod`}
>
<Button icon={<UploadOutlined/>}>Upload</Button>
</Upload>;
}
return <PageLayout nav={[{ name: "Mods" }]}>
<PageHeader
className="site-page-header"
title="Mods"
extra={uploadButton}
/>
<Table
columns={[
{
title: "Name",
dataIndex: "title",
defaultSortOrder: "ascend",
sorter: (a, b) => (
strcmp(a.name, b.name) || a.integerVersion - b.integerVersion
),
},
{
title: "Version",
key: "version",
align: "right",
render: mod => <>
{`${mod.version} `}
<Typography.Text type="secondary">{`/ ${mod.factorioVersion}`}</Typography.Text>
</>,
},
{
title: "Filename",
dataIndex: "filename",
responsive: ["xl"],
sorter: (a, b) => strcmp(a.filename, b.filename),
},
{
title: "Size",
key: "size",
responsive: ["lg"],
render: mod => libHelpers.formatBytes(mod.size),
align: "right",
sorter: (a, b) => a.size - b.size,
},
{
title: "Action",
key: "action",
responsive: ["lg"],
render: mod => actions(mod),
},
]}
expandable={{
expandedRowRender: mod => <>
<Descriptions className="borderless" bordered size="small" column={{ xs: 1, sm: 1, md: 1, lg: 2 }}>
{!screens.lg
&& <Descriptions.Item label="Action">{actions(mod)}</Descriptions.Item>
}
<Descriptions.Item label="Title">{mod.title}</Descriptions.Item>
<Descriptions.Item label="Version">{mod.version}</Descriptions.Item>
{mod.description
&& <Descriptions.Item label="Description" span={2}>{mod.description}</Descriptions.Item>
}
<Descriptions.Item label="Author" span={2}>{mod.author}</Descriptions.Item>
<Descriptions.Item label="Mod&nbsp;Portal" span={2}>
<Typography.Link href={`https://mods.factorio.com/mod/${mod.name}`}>
{`https://mods.factorio.com/mod/${mod.name}`}
</Typography.Link>
</Descriptions.Item>
{mod.contact
&& <Descriptions.Item label="Contact" span={2}>{mod.contact}</Descriptions.Item>
}
{mod.homepage
&& <Descriptions.Item label="Homepage" span={2}>{mod.homepage}</Descriptions.Item>
}
<Descriptions.Item label="Internal&nbsp;Name">{mod.name}</Descriptions.Item>
<Descriptions.Item label="Factorio&nbsp;Version">{mod.factorioVersion}</Descriptions.Item>
<Descriptions.Item label="Filename">{mod.filename}</Descriptions.Item>
<Descriptions.Item label="Size">{libHelpers.formatBytes(mod.size)}</Descriptions.Item>
<Descriptions.Item label="Hash" span={2}>{mod.hash}</Descriptions.Item>
{mod.dependencies.length
&& <Descriptions.Item label="Dependencies" span={2}>
{mod.dependencies
.filter(e => !e.startsWith("(?)"))
.map((e, i) => <Fragment key={i}>{e}<br/></Fragment>)
}
</Descriptions.Item>
}
</Descriptions>
</>,
expandedRowClassName: () => "no-expanded-padding",
}}
dataSource={modList}
pagination={false}
rowKey={mod => `${mod.name}_${mod.version}`}
/>
<PluginExtra component="ModsPage" />
</PageLayout>;
}
+9
View File
@@ -314,3 +314,12 @@ body {
top: 8px;
right: 8px;
}
.ant-descriptions-bordered.borderless > .ant-descriptions-view {
border: none;
}
tr.no-expanded-padding > td {
padding: 0;
}
+50
View File
@@ -0,0 +1,50 @@
import { useContext, useEffect, useState } from "react";
import { libData, libLink, libLogging } from "@clusterio/lib";
import ControlContext from "../components/ControlContext";
const { logger } = libLogging;
export function useModList() {
let control = useContext(ControlContext);
let [modList, setModList] = useState([]);
function updateModList() {
libLink.messages.listMods.send(control).then(result => {
setModList(result.list.map(mod => new libData.ModInfo(mod)));
}).catch(err => {
logger.error(`Failed to list mods:\n${err}`);
});
}
useEffect(() => {
updateModList();
function updateHandler(newMod) {
setModList(oldList => {
let newList = oldList.concat();
let index = newList.findIndex(mod => mod.name === newMod.name && mod.version === newMod.version);
if (!newMod.isDeleted) {
if (index !== -1) {
newList[index] = newMod;
} else {
newList.push(newMod);
}
} else if (index !== -1) {
newList.splice(index, 1);
}
return newList;
});
}
control.onModUpdate(null, updateHandler);
return () => {
control.offModUpdate(null, updateHandler);
};
}, []);
return [modList];
}
+7
View File
@@ -5,6 +5,7 @@ import SlavesPage from "./components/SlavesPage";
import SlaveViewPage from "./components/SlaveViewPage";
import InstancesPage from "./components/InstancesPage";
import InstanceViewPage from "./components/InstanceViewPage";
import ModsPage from "./components/ModsPage";
import UsersPage from "./components/UsersPage";
import UserViewPage from "./components/UserViewPage";
import RolesPage from "./components/RolesPage";
@@ -41,6 +42,12 @@ export const pages = [
sidebarPath: "/instances",
content: <InstanceViewPage />,
},
{
path: "/mods",
sidebarName: "Mods",
permission: "core.mod.list",
content: <ModsPage />,
},
{
path: "/users",
sidebarName: "Users",
+63 -1
View File
@@ -1,4 +1,4 @@
import { libErrors, libLink, libLogging, libPlugin } from "@clusterio/lib";
import { libData, libErrors, libLink, libLogging, libPlugin } from "@clusterio/lib";
const { logger } = libLogging;
import packageJson from "../../package.json";
@@ -86,6 +86,7 @@ export class Control extends libLink.Link {
this.slaveUpdateHandlers = new Map();
this.instanceUpdateHandlers = new Map();
this.saveListUpdateHandlers = new Map();
this.modUpdateHandlers = new Map();
this.userUpdateHandlers = new Map();
this.logHandlers = new Map();
@@ -102,6 +103,9 @@ export class Control extends libLink.Link {
this.updateSaveListSubscriptions().catch(err => logger.error(
`Unexpected error updating save list subscriptions:\n${err.stack}`
));
this.updateModSubscriptions().catch(err => logger.error(
`Unexpected error updating mod subscriptions:\n${err.stack}`
));
this.updateUserSubscriptions().catch(err => logger.error(
`Unexpected error updating user subscriptions:\n${err.stack}`
));
@@ -319,6 +323,64 @@ export class Control extends libLink.Link {
});
}
async modUpdateEventHandler(message) {
let mod = new libData.ModInfo(message.data.mod);
let handlers = [].concat(
this.modUpdateHandlers.get(null) || [],
this.modUpdateHandlers.get(mod.name) || []
);
for (let handler of handlers) {
handler(mod);
}
}
async onModUpdate(name, handler) {
if (name !== null && typeof name !== "string") {
throw new Error("Invalid mod name");
}
let handlers = this.modUpdateHandlers.get(name);
if (!handlers) {
handlers = [];
this.modUpdateHandlers.set(name, handlers);
}
handlers.push(handler);
if (handlers.length === 1) {
await this.updateModSubscriptions();
}
}
async offModUpdate(name, handler) {
let handlers = this.modUpdateHandlers.get(name);
if (!handlers || !handlers.length) {
throw new Error(`No handlers for mod pack ${name} exist`);
}
let index = handlers.lastIndexOf(handler);
if (index === -1) {
throw new Error(`Given handler is not registered for mod pack ${name}`);
}
handlers.splice(index, 1);
if (!handlers.length) {
this.modUpdateHandlers.delete(name);
await this.updateModSubscriptions();
}
}
async updateModSubscriptions() {
if (!this.connector.connected) {
return;
}
await libLink.messages.setModSubscriptions.send(this, {
all: this.modUpdateHandlers.has(null),
mod_names: [...this.modUpdateHandlers.keys()].filter(k => k !== null),
});
}
async userUpdateEventHandler(message) {
let handlers = [].concat(
this.userUpdateHandlers.get(null) || [],