Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 63 additions & 39 deletions src/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -682,12 +682,14 @@ export class ContentService {
async conflicts(instance: Instance): Promise<string[]> {
const items = (await this.list(instance)).filter((i) => i.enabled && i.kind === 'mod');
const warnings: string[] = [];
const localWarnings = new Map<string, string[]>();
const localModules: FabricModule[] = [];
let remoteUnavailable = false;
const ids = new Map<string, string>();
for (const item of items) {
const found: string[] = [];
localWarnings.set(item.file, found);
if (instance.loader === 'vanilla')
warnings.push(`${item.name}: ${t('requires a mod loader', '需要模组加载器')}`);
found.push(`${item.name}: ${t('requires a mod loader', '需要模组加载器')}`);
try {
const zip = new AdmZip(path.join(instance.directory, 'mods', item.file));
const fabric = zip.getEntry('fabric.mod.json');
Expand All @@ -696,51 +698,73 @@ export class ContentService {
...readFabricMetadata(path.join(instance.directory, 'mods', item.file)),
);
const meta = JSON.parse(fabric.getData().toString());
if (ids.has(meta.id)) warnings.push(`${meta.id}: ${ids.get(meta.id)} / ${item.file}`);
if (ids.has(meta.id)) found.push(`${meta.id}: ${ids.get(meta.id)} / ${item.file}`);
ids.set(meta.id, item.file);
if (!['fabric', 'quilt'].includes(instance.loader))
warnings.push(`${item.name}: Fabric / Quilt ${t('required', '必需')}`);
found.push(`${item.name}: Fabric / Quilt ${t('required', '必需')}`);
}
} catch {
warnings.push(`${item.file}: ${t('unreadable mod archive', '无法读取模组文件')}`);
found.push(`${item.file}: ${t('unreadable mod archive', '无法读取模组文件')}`);
}
if (item.versionId && !remoteUnavailable) {
try {
const version = await this.net.json<ModVersion>(`${api}/version/${item.versionId}`);
if (
!version.game_versions.includes(instance.minecraft) ||
!version.loaders.includes(instance.loader)
)
warnings.push(`${item.name}: ${t('version or loader mismatch', '版本或加载器不匹配')}`);
for (const dep of version.dependencies) {
const found = items.some((i) =>
dep.project_id
? i.projectId === dep.project_id &&
(!dep.version_id || i.versionId === dep.version_id)
: i.versionId === dep.version_id,
);
if (
(dep.dependency_type === 'required' && !found) ||
(dep.dependency_type === 'incompatible' && found)
)
warnings.push(
`${item.name}: ${dep.dependency_type} ${dep.project_id || dep.version_id}`,
);
}
} catch (error) {
if (error instanceof HttpError) warnings.push(`${item.name}: HTTP ${error.status}`);
else {
remoteUnavailable = true;
warnings.push(
t(
'Online metadata unavailable; local checks only.',
'在线元数据不可用,仅完成本地检查。',
),
);
}
}
const remote: ({ item: Content; version: ModVersion } | { item: Content; error: unknown })[] =
await Promise.all(
items
.filter((item) => item.versionId)
.map(async (item) => {
try {
return { item, version: await this.version(item.versionId!) };
} catch (error) {
return { item, error };
}
}),
);
let remoteUnavailable = false;
const remoteWarnings = new Map<string, string[]>();
for (const result of remote) {
const item = result.item;
const found: string[] = [];
remoteWarnings.set(item.file, found);
if ('error' in result) {
if (result.error instanceof HttpError)
found.push(`${item.name}: HTTP ${result.error.status}`);
else if (!remoteUnavailable) {
remoteUnavailable = true;
found.push(
t(
'Online metadata unavailable; local checks only.',
'在线元数据不可用,仅完成本地检查。',
),
);
}
continue;
}
const version = result.version;
if (
!version.game_versions.includes(instance.minecraft) ||
!version.loaders.includes(instance.loader)
)
found.push(`${item.name}: ${t('version or loader mismatch', '版本或加载器不匹配')}`);
for (const dep of version.dependencies) {
const installed = items.some((i) =>
dep.project_id
? i.projectId === dep.project_id && (!dep.version_id || i.versionId === dep.version_id)
: i.versionId === dep.version_id,
);
if (
(dep.dependency_type === 'required' && !installed) ||
(dep.dependency_type === 'incompatible' && installed)
)
found.push(`${item.name}: ${dep.dependency_type} ${dep.project_id || dep.version_id}`);
}
}
// Warnings keep the per-mod ordering the sequential version produced: local
// checks first, then the online ones for the same mod.
for (const item of items)
warnings.push(
...(localWarnings.get(item.file) ?? []),
...(remoteWarnings.get(item.file) ?? []),
);
if (['fabric', 'quilt'].includes(instance.loader)) {
const native: Record<string, string> = { minecraft: instance.minecraft };
if (instance.loader === 'fabric' && instance.loaderVersion)
Expand Down
56 changes: 39 additions & 17 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,28 @@ import { config, t } from './config';
import { exists } from './files';
import { Workbench } from './workbench';
import { Consent } from './consent';
import { resolveProxy } from './proxy';
import { describeError } from './errors';
import { extensionVersion, userAgent } from './user-agent';

const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '');

function createNetwork(proxy: string, output: vscode.LogOutputChannel): Network {
const options = {
proxy,
userAgent: userAgent(extensionVersion()),
sources: config('sources', {}),
concurrency: Math.max(1, Math.min(32, config('downloadConcurrency', 6))),
retries: config('downloadRetries', 2),
timeout: config('networkTimeout', 30000),
};
try {
return new Network(options);
} catch (error) {
output.error(`Proxy disabled: ${describeError(error)}`);
return new Network({ ...options, proxy: '' });
}
}

export async function activate(context: vscode.ExtensionContext) {
const output = vscode.window.createOutputChannel('Minecraft Workbench', { log: true });
Expand Down Expand Up @@ -68,24 +90,24 @@ export async function activate(context: vscode.ExtensionContext) {
return;
}
context.subscriptions.push(store);
let proxy =
config('proxy', '').trim() ||
vscode.workspace.getConfiguration('http').get<string>('proxy', '').trim();
const proxySetting =
text(config<unknown>('proxy', '')) ||
text(vscode.workspace.getConfiguration('http').get<unknown>('proxy', ''));
const credentials = await context.secrets.get('minecraftWorkbench.proxyCredentials');
if (proxy && credentials) {
const url = new URL(proxy);
const value = JSON.parse(credentials);
url.username = value.username;
url.password = value.password;
proxy = url.toString();
}
const network = new Network({
proxy,
sources: config('sources', {}),
concurrency: Math.max(1, Math.min(32, config('downloadConcurrency', 6))),
retries: config('downloadRetries', 2),
timeout: config('networkTimeout', 30000),
});
const resolved = resolveProxy(proxySetting, credentials);
if (resolved.problem)
void vscode.window.showWarningMessage(
resolved.problem === 'unsupported'
? t(
'Ignoring the proxy setting: use an HTTP, HTTPS, SOCKS5 or SOCKS5h proxy.',
'已忽略代理设置:请使用 HTTP、HTTPS、SOCKS5 或 SOCKS5h 代理。',
)
: t(
'Ignoring the proxy setting: it is not a valid proxy URL.',
'已忽略代理设置:代理地址不是有效的 URL。',
),
);
const network = createNetwork(resolved.proxy, output);
context.subscriptions.push({
dispose: () => {
void network.close();
Expand Down
16 changes: 16 additions & 0 deletions src/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@ export function filename(name: string): string {
throw new Error('Invalid filename');
return name;
}
const illegal = /[\x00-\x1f<>:"/\\|?*]+/g;
const device = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
/**
* Suggests a file name for an exported instance. Characters that Windows and
* macOS reject become underscores, while letters from every script are kept:
* the previous pattern rewrote CJK names into a run of underscores. Windows
* also refuses the reserved device names no matter the extension.
*/
export function suggestedFilename(value: string, fallback = 'instance'): string {
const kept = value.replace(illegal, '_').replace(/\s+/g, ' ').trim().slice(0, 80);
// A hard cut can land between the halves of a surrogate pair; dropping the
// orphan keeps the suggestion a string the file system will accept.
const name = /[\uD800-\uDBFF]$/.test(kept) ? kept.slice(0, -1) : kept;
const cleaned = name.replace(/^[.\s]+/, '').replace(/[.\s]+$/, '') || fallback;
return device.test(cleaned.split('.')[0]) ? `${cleaned}_` : cleaned;
}
export async function exists(target: string): Promise<boolean> {
try {
await fs.access(target);
Expand Down
10 changes: 7 additions & 3 deletions src/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface NetworkOptions {
concurrency: number;
retries?: number;
timeout?: number;
userAgent?: string;
}
interface JsonOptions {
method?: 'GET' | 'POST';
Expand All @@ -34,12 +35,15 @@ export class HttpError extends Error {
}
export class Network {
readonly dispatcher: Dispatcher;
readonly userAgent: string;
constructor(readonly options: NetworkOptions) {
this.userAgent = options.userAgent?.trim() || 'MinecraftWorkbench';
if (/^socks/.test(options.proxy)) {
const proxy = new URL(options.proxy);
if (!['socks:', 'socks5:', 'socks5h:'].includes(proxy.protocol))
throw new Error('Use SOCKS5 or SOCKS5h');
this.dispatcher = new Agent({
connections: options.concurrency,
connect: (opts, callback) => {
void (async () => {
let host = opts.hostname;
Expand Down Expand Up @@ -73,7 +77,7 @@ export class Network {
});
} else
this.dispatcher = options.proxy
? new ProxyAgent(options.proxy)
? new ProxyAgent({ uri: options.proxy, connections: options.concurrency })
: new Agent({
connections: options.concurrency,
connect: { timeout: options.timeout || 30000 },
Expand All @@ -96,7 +100,7 @@ export class Network {
dispatcher: this.dispatcher,
method: options.method || 'GET',
headers: {
'user-agent': 'MinecraftWorkbench/0.3.1',
'user-agent': this.userAgent,
...(options.body ? { 'content-type': 'application/json' } : {}),
...(options.form ? { 'content-type': 'application/x-www-form-urlencoded' } : {}),
...options.headers,
Expand Down Expand Up @@ -151,7 +155,7 @@ export class Network {
dispatcher: this.dispatcher,
signal: options.signal,
headers: {
'user-agent': 'MinecraftWorkbench/0.3.1',
'user-agent': this.userAgent,
...(offset
? {
Range: `bytes=${offset}-`,
Expand Down
56 changes: 56 additions & 0 deletions src/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
export type ProxyProblem = 'invalid' | 'unsupported';

export interface ProxyResolution {
proxy: string;
problem?: ProxyProblem;
}

const schemes = ['http:', 'https:', 'socks:', 'socks5:', 'socks5h:'];

function parseCredentials(value: unknown): { username: string; password: string } | undefined {
let source = value;
if (typeof source === 'string') {
if (!source.trim()) return undefined;
try {
source = JSON.parse(source);
} catch {
return undefined;
}
}
if (!source || typeof source !== 'object') return undefined;
const record = source as Record<string, unknown>;
const username = typeof record.username === 'string' ? record.username : '';
const password = typeof record.password === 'string' ? record.password : '';
if (!username && !password) return undefined;
return { username, password };
}

/**
* Turns the configured proxy plus the stored credentials into the URL handed to
* the network layer. Invalid input is reported instead of thrown so that a bad
* `http.proxy` value can never stop the extension from activating.
*/
export function resolveProxy(raw: unknown, credentials?: unknown): ProxyResolution {
const proxy = typeof raw === 'string' ? raw.trim() : '';
if (!proxy) return { proxy: '' };
let url: URL;
try {
url = new URL(proxy);
} catch {
return { proxy: '', problem: 'invalid' };
}
if (!schemes.includes(url.protocol)) return { proxy: '', problem: 'unsupported' };
const value = parseCredentials(credentials);
if (!value) return { proxy };
url.username = value.username;
url.password = value.password;
const serialized = url.toString();
// `URL` adds an implicit trailing slash to http(s) URLs. Drop it again so the
// value keeps the shape the user typed instead of differing from the
// credential-less branch for no functional reason.
const trimmed =
url.pathname === '/' && !url.search && !url.hash && !proxy.endsWith('/')
? serialized.replace(/\/$/, '')
: serialized;
return { proxy: trimmed };
}
6 changes: 3 additions & 3 deletions src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { Backups } from './backups';
import { Item } from './views';
import { Instance, Content, ContentKind, Account } from './models';
import { config, t, trusted, setLanguage } from './config';
import { exists, writeJson } from './files';
import { exists, suggestedFilename, writeJson } from './files';
import { describeError } from './errors';
import { InstanceFiles } from './instance-files';
import { ContentInstallOptions, contentFile } from './modrinth';
Expand Down Expand Up @@ -246,7 +246,7 @@ export class UI {
const instance = await this.instance(item);
this.idle(instance);
const destination = await vscode.window.showSaveDialog({
defaultUri: vscode.Uri.file(`${instance.name.replace(/[^\w.-]/g, '_')}.mrpack`),
defaultUri: vscode.Uri.file(`${suggestedFilename(instance.name)}.mrpack`),
filters: { 'Modrinth modpack': ['mrpack'] },
});
if (!destination) return;
Expand Down Expand Up @@ -504,7 +504,7 @@ export class UI {
async exportInstance(item?: Item) {
const instance = await this.instance(item);
const destination = await vscode.window.showSaveDialog({
defaultUri: vscode.Uri.file(`${instance.name.replace(/[^\w.-]/g, '_')}.json`),
defaultUri: vscode.Uri.file(`${suggestedFilename(instance.name)}.json`),
filters: { JSON: ['json'] },
});
if (destination)
Expand Down
21 changes: 21 additions & 0 deletions src/user-agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as vscode from 'vscode';

export const extensionId = 'minecraft-workbench.minecraft-workbench';

export function userAgent(version: string): string {
const value = version.trim();
return value ? `MinecraftWorkbench/${value}` : 'MinecraftWorkbench';
}

/**
* Reads the version from the installed manifest so the User-Agent always
* matches the running build instead of drifting away from package.json.
*/
export function extensionVersion(): string {
try {
const value = vscode.extensions?.getExtension?.(extensionId)?.packageJSON?.version;
return typeof value === 'string' ? value : '';
} catch {
return '';
}
}
Loading