Initial commit: BRAT fork with Gitea support
Tatortreiniger / tatort-reinigen (release) Has been cancelled
Tatortreiniger / tatort-reinigen (release) Has been cancelled
This commit is contained in:
1 parent
bd3153fd32
commit
8de00536fa
44 files changed
+5172
-3
No files matched your search
@@ -0,0 +1,800 @@
|
||||
import type { PluginManifest } from "obsidian";
|
||||
import {
|
||||
apiVersion,
|
||||
Notice,
|
||||
normalizePath,
|
||||
Platform,
|
||||
requireApiVersion,
|
||||
} from "obsidian";
|
||||
import { confirm } from "src/ui/ConfirmModal";
|
||||
import {
|
||||
ProviderRateLimitError,
|
||||
ProviderResponseError,
|
||||
} from "src/providers/ProviderErrors";
|
||||
import type { ParsedRepo, PluginProvider, Release } from "src/providers/PluginProvider";
|
||||
import { parseWithProvider } from "src/providers/index";
|
||||
import { addBetaPluginToList } from "src/settings";
|
||||
import type BratPlugin from "../main";
|
||||
import AddNewPluginModal from "../ui/AddNewPluginModal";
|
||||
import { isConnectedToInternet } from "../utils/internetconnection";
|
||||
import { toastMessage } from "../utils/notifications";
|
||||
import type { ReleaseFiles } from "./BetaPluginsTypes";
|
||||
|
||||
const compareVersions = require("semver/functions/compare");
|
||||
const semverCoerce = require("semver/functions/coerce");
|
||||
|
||||
interface PluginManifestEx extends PluginManifest {
|
||||
brat: {
|
||||
isIncompatible?: boolean;
|
||||
isDesktopOnlyOriginal?: boolean;
|
||||
minAppVersionOriginal?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Primary handler for adding, updating, deleting beta plugins tracked by this plugin.
|
||||
*
|
||||
* Uses a provider abstraction (GitHubProvider / GiteaProvider) so that
|
||||
* plugins hosted on any git forge with releases & assets can be installed.
|
||||
*/
|
||||
export default class BetaPlugins {
|
||||
plugin: BratPlugin;
|
||||
|
||||
constructor(plugin: BratPlugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the provider and parsed repo for a given repository path.
|
||||
* Supports GitHub (bare `user/repo` or `github.com/user/repo`)
|
||||
* and Gitea (`https://git.example.com/user/repo`) URLs.
|
||||
*/
|
||||
private resolveProvider(repoPath: string): {
|
||||
provider: PluginProvider;
|
||||
parsed: ParsedRepo;
|
||||
} {
|
||||
return parseWithProvider(repoPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the Gitea instance URL stored per-plugin in settings (if any).
|
||||
* For plugins added before Gitea support, this could be empty.
|
||||
*/
|
||||
private getGiteaUrlForRepo(repoPath: string): string {
|
||||
const entry = this.plugin.settings.pluginSubListFrozenVersion.find(
|
||||
(p) => p.repo === repoPath,
|
||||
);
|
||||
return entry?.giteaUrl ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the token value for a given plugin.
|
||||
* Checks per-repo secret first, then global token.
|
||||
*/
|
||||
private async getTokenForRepo(repoPath: string, secretName?: string): Promise<string> {
|
||||
if (secretName) {
|
||||
return (await this.plugin.app.secretStorage.getSecret(secretName)) || "";
|
||||
}
|
||||
if (this.plugin.settings.globalTokenName) {
|
||||
return (
|
||||
(await this.plugin.app.secretStorage.getSecret(
|
||||
this.plugin.settings.globalTokenName,
|
||||
)) || ""
|
||||
);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* opens the AddNewPluginModal to get info for a new beta plugin
|
||||
* @param openSettingsTabAfterwards - will open settings screen afterwards. Used when this command is called from settings tab
|
||||
* @param useFrozenVersion - install the plugin using frozen version.
|
||||
* @param prefillRepo - prefill the repository field in the modal.
|
||||
* @param prefillVersion - prefill the version field in the modal.
|
||||
* @param prefillSecretName - prefill the secret name field in the modal (name of secret in SecretStorage).
|
||||
*/
|
||||
displayAddNewPluginModal(
|
||||
openSettingsTabAfterwards = false,
|
||||
useFrozenVersion = false,
|
||||
prefillRepo = "",
|
||||
prefillVersion = "",
|
||||
prefillSecretName = "",
|
||||
): void {
|
||||
const newPlugin = new AddNewPluginModal(
|
||||
this.plugin,
|
||||
this,
|
||||
openSettingsTabAfterwards,
|
||||
useFrozenVersion,
|
||||
prefillRepo,
|
||||
prefillVersion,
|
||||
prefillSecretName,
|
||||
);
|
||||
newPlugin.open();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a repository to determine if it contains a valid Obsidian plugin.
|
||||
*
|
||||
* Works with both GitHub and Gitea repositories. Auto-detects the provider
|
||||
* from the repository URL.
|
||||
*/
|
||||
async validateRepository(
|
||||
repositoryPath: string,
|
||||
getBetaManifest = false,
|
||||
reportIssues = false,
|
||||
specifyVersion = "",
|
||||
privateApiKey = "",
|
||||
giteaUrl = "",
|
||||
): Promise<PluginManifest | null> {
|
||||
const noticeTimeout = 15;
|
||||
|
||||
const { provider, parsed } = this.resolveProvider(repositoryPath);
|
||||
const token = privateApiKey;
|
||||
|
||||
try {
|
||||
// Check if the repository is private
|
||||
const repoInfo = await provider.getRepoInfo(parsed, token);
|
||||
|
||||
// Grab the manifest.json for the latest release from the repository
|
||||
const release: Release | null = await provider.getRelease(
|
||||
parsed,
|
||||
specifyVersion || undefined,
|
||||
getBetaManifest,
|
||||
token,
|
||||
);
|
||||
|
||||
if (!release) {
|
||||
if (reportIssues) {
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nThis does not seem to be an obsidian plugin with valid releases, as there are no releases available.`,
|
||||
noticeTimeout,
|
||||
);
|
||||
console.error("BRAT: validateRepository", repositoryPath);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const rawManifest = await provider.getAsset(
|
||||
release,
|
||||
"manifest.json",
|
||||
repoInfo.isPrivate,
|
||||
token,
|
||||
);
|
||||
|
||||
if (!rawManifest) {
|
||||
if (reportIssues) {
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nThis does not seem to be an obsidian plugin, as there is no manifest.json file in the release.`,
|
||||
noticeTimeout,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const manifestJson = JSON.parse(rawManifest) as PluginManifest;
|
||||
if (!("id" in manifestJson)) {
|
||||
if (reportIssues)
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nThe plugin id attribute is missing from the manifest file`,
|
||||
noticeTimeout,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (!("version" in manifestJson)) {
|
||||
if (reportIssues)
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nThe version attribute is missing from the manifest file`,
|
||||
noticeTimeout,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Version mismatch handling (same as original BRAT)
|
||||
try {
|
||||
const expectedVersion = semverCoerce(release.tag_name, {
|
||||
includePrerelease: true,
|
||||
loose: true,
|
||||
});
|
||||
const manifestVersion = semverCoerce(manifestJson.version, {
|
||||
includePrerelease: true,
|
||||
loose: true,
|
||||
});
|
||||
if (
|
||||
expectedVersion &&
|
||||
manifestVersion &&
|
||||
compareVersions(expectedVersion, manifestVersion) !== 0
|
||||
) {
|
||||
if (reportIssues)
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nVersion mismatch: release tag '${release.tag_name}' vs manifest '${manifestJson.version}'. Using release version.`,
|
||||
noticeTimeout,
|
||||
);
|
||||
manifestJson.version = expectedVersion.version;
|
||||
}
|
||||
} catch {
|
||||
// Ignore comparison errors
|
||||
}
|
||||
|
||||
return manifestJson;
|
||||
} catch (error) {
|
||||
if (error instanceof ProviderRateLimitError) {
|
||||
const msg = `${parsed.host} API rate limit exceeded. Reset in ${error.getMinutesToReset()} minutes.`;
|
||||
if (reportIssues) toastMessage(this.plugin, msg, noticeTimeout);
|
||||
console.error(`BRAT: validateRepository ${error}`);
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${error.message} Consider adding a personal access token in BRAT settings for higher limits.`,
|
||||
20,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (error instanceof ProviderResponseError) {
|
||||
if (reportIssues) {
|
||||
if (error.status === 401) {
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nAuthentication error. Verify that your access token is valid.`,
|
||||
noticeTimeout,
|
||||
);
|
||||
} else {
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nAPI error ${error.status}: ${error.message}`,
|
||||
noticeTimeout,
|
||||
);
|
||||
}
|
||||
}
|
||||
console.error(`BRAT: validateRepository ${error}`);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (reportIssues)
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nUnspecified error: ${error}. Enable debug for more info.`,
|
||||
noticeTimeout,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the release files based on the version number in the manifest
|
||||
*/
|
||||
async getAllReleaseFiles(
|
||||
repositoryPath: string,
|
||||
getManifest: boolean,
|
||||
specifyVersion = "",
|
||||
tokenValue = "",
|
||||
giteaUrl = "",
|
||||
): Promise<ReleaseFiles> {
|
||||
const { provider, parsed } = this.resolveProvider(repositoryPath);
|
||||
|
||||
const repoInfo = await provider.getRepoInfo(parsed, tokenValue);
|
||||
const isPrivate = repoInfo.isPrivate;
|
||||
|
||||
const release = await provider.getRelease(
|
||||
parsed,
|
||||
specifyVersion || undefined,
|
||||
getManifest,
|
||||
tokenValue,
|
||||
);
|
||||
|
||||
if (!release) {
|
||||
return Promise.reject("No release found");
|
||||
}
|
||||
|
||||
const reallyGetManifestOrNot = getManifest || specifyVersion !== "";
|
||||
console.log({ reallyGetManifestOrNot, version: release.tag_name });
|
||||
|
||||
return {
|
||||
mainJs: await provider.getAsset(
|
||||
release,
|
||||
"main.js",
|
||||
isPrivate,
|
||||
tokenValue,
|
||||
),
|
||||
manifest: reallyGetManifestOrNot
|
||||
? await provider.getAsset(
|
||||
release,
|
||||
"manifest.json",
|
||||
isPrivate,
|
||||
tokenValue,
|
||||
)
|
||||
: "",
|
||||
styles: await provider.getAsset(
|
||||
release,
|
||||
"styles.css",
|
||||
isPrivate,
|
||||
tokenValue,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the plugin release files to the local obsidian .plugins folder
|
||||
*/
|
||||
async writeReleaseFilesToPluginFolder(
|
||||
betaPluginId: string,
|
||||
relFiles: ReleaseFiles,
|
||||
): Promise<void> {
|
||||
const pluginTargetFolderPath = `${normalizePath(`${this.plugin.app.vault.configDir}/plugins/${betaPluginId}`)}/`;
|
||||
const { adapter } = this.plugin.app.vault;
|
||||
if (!(await adapter.exists(pluginTargetFolderPath))) {
|
||||
await adapter.mkdir(pluginTargetFolderPath);
|
||||
}
|
||||
await adapter.write(
|
||||
`${pluginTargetFolderPath}main.js`,
|
||||
relFiles.mainJs ?? "",
|
||||
);
|
||||
await adapter.write(
|
||||
`${pluginTargetFolderPath}manifest.json`,
|
||||
relFiles.manifest ?? "",
|
||||
);
|
||||
if (relFiles.styles)
|
||||
await adapter.write(
|
||||
`${pluginTargetFolderPath}styles.css`,
|
||||
relFiles.styles,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Primary function for adding a new beta plugin to Obsidian.
|
||||
* Works with GitHub and Gitea.
|
||||
*/
|
||||
async addPlugin(
|
||||
repositoryPath: string,
|
||||
updatePluginFiles = false,
|
||||
seeIfUpdatedOnly = false,
|
||||
reportIfNotUpdated = false,
|
||||
specifyVersion = "",
|
||||
forceReinstall = false,
|
||||
enableAfterInstall = this.plugin.settings.enableAfterInstall,
|
||||
secretName = "",
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
if (this.plugin.settings.debuggingMode) {
|
||||
console.log(
|
||||
"BRAT: addPlugin",
|
||||
repositoryPath,
|
||||
updatePluginFiles,
|
||||
seeIfUpdatedOnly,
|
||||
reportIfNotUpdated,
|
||||
specifyVersion,
|
||||
forceReinstall,
|
||||
enableAfterInstall,
|
||||
secretName ? "with secret" : "public",
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve provider for this repo
|
||||
const { provider, parsed } = this.resolveProvider(repositoryPath);
|
||||
|
||||
// Retrieve token
|
||||
let tokenValue = "";
|
||||
if (secretName && secretName.trim() !== "") {
|
||||
tokenValue =
|
||||
(await this.plugin.app.secretStorage.getSecret(secretName)) || "";
|
||||
if (!tokenValue) {
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`Secret not found for token name: ${secretName}. Please add it to SecretStorage or clear the token name for this plugin.`,
|
||||
10,
|
||||
);
|
||||
}
|
||||
} else if (this.plugin.settings.globalTokenName) {
|
||||
tokenValue =
|
||||
(await this.plugin.app.secretStorage.getSecret(
|
||||
this.plugin.settings.globalTokenName,
|
||||
)) || "";
|
||||
}
|
||||
|
||||
const giteaUrl = this.getGiteaUrlForRepo(repositoryPath);
|
||||
const noticeTimeout = 10;
|
||||
|
||||
// Attempt to get manifest (check for beta/pre-release first)
|
||||
let primaryManifest = await this.validateRepository(
|
||||
repositoryPath,
|
||||
true,
|
||||
true,
|
||||
specifyVersion,
|
||||
tokenValue,
|
||||
giteaUrl,
|
||||
);
|
||||
const usingBetaManifest: boolean = !!primaryManifest;
|
||||
if (!usingBetaManifest)
|
||||
primaryManifest = await this.validateRepository(
|
||||
repositoryPath,
|
||||
false,
|
||||
true,
|
||||
specifyVersion,
|
||||
tokenValue,
|
||||
giteaUrl,
|
||||
);
|
||||
|
||||
if (primaryManifest === null) {
|
||||
const msg = `${repositoryPath}\nA manifest.json file does not exist in the latest release. This plugin cannot be installed.`;
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, noticeTimeout);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Object.hasOwn(primaryManifest, "version")) {
|
||||
const msg = `${repositoryPath}\nThe manifest.json does not have a version number. Cannot install.`;
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, noticeTimeout);
|
||||
return false;
|
||||
}
|
||||
|
||||
let isIncompatible = false;
|
||||
|
||||
// Check minAppVersion
|
||||
if (Object.hasOwn(primaryManifest, "minAppVersion")) {
|
||||
if (!requireApiVersion(primaryManifest.minAppVersion)) {
|
||||
if (
|
||||
specifyVersion === "" ||
|
||||
specifyVersion === "latest" ||
|
||||
!this.plugin.settings.allowIncompatiblePlugins
|
||||
) {
|
||||
const msg = `Plugin: ${repositoryPath}\n\nRequires Obsidian ${primaryManifest.minAppVersion}, but you have ${apiVersion}. Update Obsidian or contact the developer.`;
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, 30);
|
||||
return false;
|
||||
}
|
||||
|
||||
const confirmResult = await confirm({
|
||||
app: this.plugin.app,
|
||||
message: createFragment((f) => {
|
||||
f.appendText("Plugin: ");
|
||||
f.createEl("code", { text: repositoryPath });
|
||||
f.createEl("br");
|
||||
f.appendText("The manifest requires Obsidian ");
|
||||
f.createEl("code", { text: primaryManifest.minAppVersion });
|
||||
f.appendText(", but you have ");
|
||||
f.createEl("code", { text: apiVersion });
|
||||
f.appendText(". Install at your own risk?");
|
||||
}),
|
||||
});
|
||||
|
||||
if (!confirmResult) return false;
|
||||
isIncompatible = true;
|
||||
}
|
||||
}
|
||||
|
||||
const getRelease = async () => {
|
||||
const rFiles = await this.getAllReleaseFiles(
|
||||
repositoryPath,
|
||||
usingBetaManifest,
|
||||
specifyVersion,
|
||||
tokenValue,
|
||||
giteaUrl,
|
||||
);
|
||||
|
||||
if (usingBetaManifest || rFiles.manifest === "")
|
||||
rFiles.manifest = JSON.stringify(primaryManifest);
|
||||
|
||||
const manifestObj = JSON.parse(
|
||||
rFiles.manifest ?? "",
|
||||
) as PluginManifestEx;
|
||||
|
||||
if (isIncompatible) {
|
||||
manifestObj.brat = {
|
||||
isIncompatible: true,
|
||||
minAppVersionOriginal: manifestObj.minAppVersion,
|
||||
};
|
||||
manifestObj.minAppVersion = apiVersion;
|
||||
}
|
||||
|
||||
if (Platform.isMobile && manifestObj.isDesktopOnly) {
|
||||
if (this.plugin.settings.allowIncompatiblePlugins) {
|
||||
const confirmResult = await confirm({
|
||||
app: this.plugin.app,
|
||||
message: createFragment((f) => {
|
||||
f.appendText("Plugin: ");
|
||||
f.createEl("code", { text: repositoryPath });
|
||||
f.createEl("br");
|
||||
f.appendText("This plugin is desktop-only, but you are on mobile.");
|
||||
f.createEl("br");
|
||||
f.appendText("Install at your own risk?");
|
||||
}),
|
||||
});
|
||||
if (!confirmResult) return null;
|
||||
manifestObj.isDesktopOnly = false;
|
||||
manifestObj.brat ??= {};
|
||||
manifestObj.brat.isDesktopOnlyOriginal = true;
|
||||
manifestObj.brat.isIncompatible = true;
|
||||
isIncompatible = true;
|
||||
} else {
|
||||
const msg = `Plugin: ${repositoryPath}\nCannot install desktop-only plugin on mobile.`;
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, 30);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (isIncompatible) {
|
||||
rFiles.manifest = JSON.stringify(manifestObj);
|
||||
}
|
||||
|
||||
if (rFiles.mainJs === null) {
|
||||
const msg = `${repositoryPath}\nmain.js is missing from the release.`;
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, noticeTimeout);
|
||||
return null;
|
||||
}
|
||||
return rFiles;
|
||||
};
|
||||
|
||||
if (!updatePluginFiles || forceReinstall) {
|
||||
const releaseFiles = await getRelease();
|
||||
if (releaseFiles === null) return false;
|
||||
await this.writeReleaseFilesToPluginFolder(
|
||||
primaryManifest.id,
|
||||
releaseFiles,
|
||||
);
|
||||
addBetaPluginToList(
|
||||
this.plugin,
|
||||
repositoryPath,
|
||||
specifyVersion,
|
||||
isIncompatible,
|
||||
secretName,
|
||||
// Store Gitea URL if this is a Gitea repo
|
||||
parsed.isGitHub ? "" : parsed.rawBaseUrl,
|
||||
);
|
||||
if (enableAfterInstall) {
|
||||
// @ts-expect-error
|
||||
const { plugins } = this.plugin.app;
|
||||
const pluginTargetFolderPath = normalizePath(
|
||||
`${plugins.getPluginFolder()}/${primaryManifest.id}`,
|
||||
);
|
||||
await plugins.loadManifest(pluginTargetFolderPath);
|
||||
await plugins.enablePluginAndSave(primaryManifest.id);
|
||||
}
|
||||
// @ts-expect-error
|
||||
await this.plugin.app.plugins.loadManifests();
|
||||
if (forceReinstall) {
|
||||
await this.reloadPlugin(primaryManifest.id);
|
||||
await this.plugin.log(`${repositoryPath} reinstalled`, true);
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath}\nPlugin reinstalled (version ${primaryManifest.version})`,
|
||||
noticeTimeout,
|
||||
);
|
||||
} else {
|
||||
const versionText =
|
||||
specifyVersion === "" ? "" : ` (version: ${specifyVersion})`;
|
||||
let msg = `${repositoryPath}${versionText}\nPlugin registered with BRAT.`;
|
||||
if (!enableAfterInstall) {
|
||||
msg += " You may need to enable it in Community Plugins.";
|
||||
}
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, noticeTimeout);
|
||||
}
|
||||
} else {
|
||||
// Update existing plugin
|
||||
const pluginTargetFolderPath = `${this.plugin.app.vault.configDir}/plugins/${primaryManifest.id}/`;
|
||||
let localManifestContents = "";
|
||||
try {
|
||||
localManifestContents = await this.plugin.app.vault.adapter.read(
|
||||
`${pluginTargetFolderPath}manifest.json`,
|
||||
);
|
||||
} catch (e) {
|
||||
const err = e as { errno?: number };
|
||||
if (err.errno === -4058 || err.errno === -2) {
|
||||
await this.addPlugin(
|
||||
repositoryPath,
|
||||
false,
|
||||
usingBetaManifest,
|
||||
false,
|
||||
specifyVersion,
|
||||
false,
|
||||
enableAfterInstall,
|
||||
secretName,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
console.log("BRAT - Local Manifest Load", primaryManifest.id, e);
|
||||
}
|
||||
|
||||
if (specifyVersion !== "" && specifyVersion !== "latest") {
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`${repositoryPath} version is frozen, not updating.`,
|
||||
3,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const localManifestJson = JSON.parse(localManifestContents) as PluginManifest;
|
||||
const localVersion = semverCoerce(localManifestJson.version, {
|
||||
includePrerelease: true,
|
||||
loose: true,
|
||||
});
|
||||
const remoteVersion = semverCoerce(primaryManifest.version, {
|
||||
includePrerelease: true,
|
||||
loose: true,
|
||||
});
|
||||
if (
|
||||
localVersion &&
|
||||
remoteVersion &&
|
||||
compareVersions(localVersion, remoteVersion) === -1
|
||||
) {
|
||||
const releaseFiles = await getRelease();
|
||||
if (releaseFiles === null) return false;
|
||||
|
||||
if (seeIfUpdatedOnly) {
|
||||
const msg = `Update available for ${primaryManifest.id}: ${localManifestJson.version} → ${primaryManifest.version}. `;
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, 30);
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.writeReleaseFilesToPluginFolder(
|
||||
primaryManifest.id,
|
||||
releaseFiles,
|
||||
);
|
||||
// @ts-expect-error
|
||||
await this.plugin.app.plugins.loadManifests();
|
||||
await this.reloadPlugin(primaryManifest.id);
|
||||
const msg = `${primaryManifest.id}\nUpdated: ${localManifestJson.version} → ${primaryManifest.version}. `;
|
||||
await this.plugin.log(msg, true);
|
||||
toastMessage(this.plugin, msg, 30);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (reportIfNotUpdated) {
|
||||
toastMessage(this.plugin, `No update for ${repositoryPath}`, 3);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`BRAT: Error adding plugin ${repositoryPath}:`, error);
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
await this.plugin.log(
|
||||
`Error ${updatePluginFiles ? "updating" : "adding"} plugin ${repositoryPath}: ${errorMessage}`,
|
||||
true,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* reloads a plugin
|
||||
*/
|
||||
async reloadPlugin(pluginName: string): Promise<void> {
|
||||
// @ts-expect-error
|
||||
const { plugins } = this.plugin.app;
|
||||
try {
|
||||
await plugins.disablePlugin(pluginName);
|
||||
await plugins.enablePlugin(pluginName);
|
||||
} catch (e) {
|
||||
if (this.plugin.settings.debuggingMode) console.log("reload plugin", e);
|
||||
}
|
||||
}
|
||||
|
||||
async updatePlugin(
|
||||
repositoryPath: string,
|
||||
onlyCheckDontUpdate = false,
|
||||
reportIfNotUpdated = false,
|
||||
forceReinstall = false,
|
||||
secretName = "",
|
||||
): Promise<boolean> {
|
||||
const result = await this.addPlugin(
|
||||
repositoryPath,
|
||||
true,
|
||||
onlyCheckDontUpdate,
|
||||
reportIfNotUpdated,
|
||||
"",
|
||||
forceReinstall,
|
||||
false,
|
||||
secretName,
|
||||
);
|
||||
if (!result && !onlyCheckDontUpdate)
|
||||
toastMessage(this.plugin, `${repositoryPath}\nUpdate failed.`);
|
||||
return result;
|
||||
}
|
||||
|
||||
async checkForPluginUpdatesAndInstallUpdates(
|
||||
showInfo = false,
|
||||
onlyCheckDontUpdate = false,
|
||||
): Promise<void> {
|
||||
if (!(await isConnectedToInternet())) {
|
||||
console.log("BRAT: No internet detected.");
|
||||
return;
|
||||
}
|
||||
let newNotice: Notice | undefined;
|
||||
const msg1 = "Checking for plugin updates STARTED";
|
||||
await this.plugin.log(msg1, true);
|
||||
if (showInfo && this.plugin.settings.notificationsEnabled)
|
||||
newNotice = new Notice(`BRAT\n${msg1}`, 30000);
|
||||
|
||||
const frozenVersions = new Map(
|
||||
this.plugin.settings.pluginSubListFrozenVersion.map((f) => [
|
||||
f.repo,
|
||||
f.version,
|
||||
]),
|
||||
);
|
||||
const repoTokens = new Map(
|
||||
this.plugin.settings.pluginSubListFrozenVersion.map((f) => [
|
||||
f.repo,
|
||||
f.tokenName || "",
|
||||
]),
|
||||
);
|
||||
|
||||
for (const bp of this.plugin.settings.pluginList) {
|
||||
const version = frozenVersions.get(bp);
|
||||
if (version && version !== "latest") continue;
|
||||
await this.updatePlugin(
|
||||
bp,
|
||||
onlyCheckDontUpdate,
|
||||
false,
|
||||
false,
|
||||
repoTokens.get(bp) || "",
|
||||
);
|
||||
}
|
||||
|
||||
const msg2 = "Checking for plugin updates COMPLETED";
|
||||
await this.plugin.log(msg2, true);
|
||||
if (showInfo) {
|
||||
if (newNotice) newNotice.hide();
|
||||
toastMessage(this.plugin, msg2, 10);
|
||||
}
|
||||
}
|
||||
|
||||
deletePlugin(repositoryPath: string): void {
|
||||
const msg = `Removed ${repositoryPath} from BRAT plugin list`;
|
||||
void this.plugin.log(msg, true);
|
||||
this.plugin.settings.pluginList = this.plugin.settings.pluginList.filter(
|
||||
(b) => b !== repositoryPath,
|
||||
);
|
||||
this.plugin.settings.pluginSubListFrozenVersion =
|
||||
this.plugin.settings.pluginSubListFrozenVersion.filter(
|
||||
(b) => b.repo !== repositoryPath,
|
||||
);
|
||||
void this.plugin.saveSettings();
|
||||
}
|
||||
|
||||
getEnabledDisabledPlugins(enabled: boolean): PluginManifest[] {
|
||||
// @ts-expect-error
|
||||
const pl = this.plugin.app.plugins;
|
||||
const manifests: PluginManifest[] = Object.values(pl.manifests);
|
||||
const enabledPlugins: PluginManifest[] = Object.values(pl.plugins).map(
|
||||
// @ts-expect-error
|
||||
(p) => p.manifest,
|
||||
);
|
||||
return enabled
|
||||
? manifests.filter((manifest) =>
|
||||
enabledPlugins.find(
|
||||
(pluginName) => manifest.id === pluginName.id,
|
||||
),
|
||||
)
|
||||
: manifests.filter(
|
||||
(manifest) =>
|
||||
!enabledPlugins.find(
|
||||
(pluginName) => manifest.id === pluginName.id,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
checkIncompatiblePlugins(): void {
|
||||
const incompatiblePluginIds =
|
||||
this.plugin.settings.pluginSubListFrozenVersion
|
||||
.filter((p) => p.isIncompatible)
|
||||
.map((p) => p.repo);
|
||||
if (incompatiblePluginIds.length > 0) {
|
||||
toastMessage(
|
||||
this.plugin,
|
||||
`The following incompatible plugins were forcefully installed and may not work as expected:\n${incompatiblePluginIds.join("\n")}`,
|
||||
30,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user