Fork fixes: - Global token is GitHub-only; never sent to Gitea/Forgejo hosts - Gitea: download assets via browser_download_url (+token) so private repos work - Gitea URL parsing keeps port and sub-path installs, strips browser sub-pages - GitHub detected by hostname, not substring - Gitea releases: follow pagination (X-Total-Count), skip drafts - Gitea token validation against the repo; 404 is no longer "valid" - Settings tab and migration log use this plugin's own id/folder - Check-only mode no longer reinstalls/enables a missing plugin folder - reloadPlugin reports load failures (enablePlugin resolves false) - Repository / release-notes links work for both providers Ported from upstream BRAT 2.2.0: - Release sort: semver tags first, date fallback - Null-safe version comparison, JSON shape guards - Drop obsidian-daily-notes-interface (read daily note format directly) - Notice.messageEl, CSS without !important, console.debug/error
795 lines
23 KiB
TypeScript
795 lines
23 KiB
TypeScript
import type { PluginManifest } from "obsidian";
|
|
import {
|
|
apiVersion,
|
|
Notice,
|
|
normalizePath,
|
|
Platform,
|
|
requireApiVersion,
|
|
} from "obsidian";
|
|
import { compare as compareVersions, coerce as semverCoerce } from "semver";
|
|
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";
|
|
|
|
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);
|
|
}
|
|
|
|
/**
|
|
* Token to send for a repository: its own secret if one is set, otherwise
|
|
* the global token, which is a GitHub token and is never sent to other hosts.
|
|
*/
|
|
resolveToken(parsed: ParsedRepo, secretName = ""): string {
|
|
const { secretStorage } = this.plugin.app;
|
|
if (secretName.trim() !== "") {
|
|
return secretStorage.getSecret(secretName) ?? "";
|
|
}
|
|
const { globalTokenName } = this.plugin.settings;
|
|
if (parsed.isGitHub && globalTokenName) {
|
|
return secretStorage.getSecret(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 = "",
|
|
): 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;
|
|
}
|
|
|
|
// Improve robustness: if semver coercion fails, compare raw versions.
|
|
const expectedVersion = semverCoerce(release.tag_name, {
|
|
includePrerelease: true,
|
|
loose: true,
|
|
});
|
|
const manifestVersion = semverCoerce(manifestJson.version, {
|
|
includePrerelease: true,
|
|
loose: true,
|
|
});
|
|
const hasVersionMismatch =
|
|
expectedVersion && manifestVersion
|
|
? compareVersions(expectedVersion.version, manifestVersion.version) !== 0
|
|
: expectedVersion !== null && manifestJson.version !== release.tag_name;
|
|
|
|
if (hasVersionMismatch && expectedVersion) {
|
|
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;
|
|
}
|
|
|
|
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: ${String(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 = "",
|
|
): 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) {
|
|
throw new Error("No release found");
|
|
}
|
|
|
|
const reallyGetManifestOrNot = getManifest || specifyVersion !== "";
|
|
if (this.plugin.settings.debuggingMode)
|
|
console.debug({ 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.debug(
|
|
"BRAT: addPlugin",
|
|
repositoryPath,
|
|
updatePluginFiles,
|
|
seeIfUpdatedOnly,
|
|
reportIfNotUpdated,
|
|
specifyVersion,
|
|
forceReinstall,
|
|
enableAfterInstall,
|
|
secretName ? "with secret" : "public",
|
|
);
|
|
}
|
|
|
|
const { parsed } = this.resolveProvider(repositoryPath);
|
|
|
|
// Retrieve token
|
|
const tokenValue = this.resolveToken(parsed, secretName);
|
|
if (secretName.trim() !== "" && !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,
|
|
);
|
|
}
|
|
|
|
const noticeTimeout = 10;
|
|
|
|
// Attempt to get manifest (check for beta/pre-release first)
|
|
let primaryManifest = await this.validateRepository(
|
|
repositoryPath,
|
|
true,
|
|
true,
|
|
specifyVersion,
|
|
tokenValue,
|
|
);
|
|
const usingBetaManifest: boolean = !!primaryManifest;
|
|
if (!usingBetaManifest)
|
|
primaryManifest = await this.validateRepository(
|
|
repositoryPath,
|
|
false,
|
|
true,
|
|
specifyVersion,
|
|
tokenValue,
|
|
);
|
|
|
|
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,
|
|
);
|
|
|
|
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,
|
|
);
|
|
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}/`;
|
|
const localManifestPath = `${pluginTargetFolderPath}manifest.json`;
|
|
const vaultAdapter = this.plugin.app.vault.adapter;
|
|
if (!(await vaultAdapter.exists(localManifestPath))) {
|
|
// Plugin folder is empty/missing (deleted by sync, by hand, ...).
|
|
if (seeIfUpdatedOnly) {
|
|
const msg = `${repositoryPath}\nPlugin folder is missing; run "Check for updates and update" to reinstall it.`;
|
|
await this.plugin.log(msg, true);
|
|
toastMessage(this.plugin, msg, 30);
|
|
return false;
|
|
}
|
|
// Reinstall it. updatePlugin() hard-codes enableAfterInstall=false
|
|
// for plain updates, which here would leave the plugin installed
|
|
// but disabled, so use the user's setting instead.
|
|
return await this.addPlugin(
|
|
repositoryPath,
|
|
false,
|
|
false,
|
|
false,
|
|
specifyVersion,
|
|
false,
|
|
this.plugin.settings.enableAfterInstall,
|
|
secretName,
|
|
);
|
|
}
|
|
const localManifestContents =
|
|
await vaultAdapter.read(localManifestPath);
|
|
|
|
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,
|
|
});
|
|
const hasNewerRemote =
|
|
localVersion && remoteVersion
|
|
? compareVersions(localVersion.version, remoteVersion.version) === -1
|
|
: localManifestJson.version !== primaryManifest.version;
|
|
if (hasNewerRemote) {
|
|
const releaseNotesUrl = `${parsed.webUrl}/releases/tag/${primaryManifest.version}`;
|
|
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, () => {
|
|
window.open(releaseNotesUrl);
|
|
});
|
|
return false;
|
|
}
|
|
|
|
await this.writeReleaseFilesToPluginFolder(
|
|
primaryManifest.id,
|
|
releaseFiles,
|
|
);
|
|
// @ts-expect-error
|
|
await this.plugin.app.plugins.loadManifests();
|
|
const reloaded = await this.reloadPlugin(primaryManifest.id);
|
|
const msg = reloaded
|
|
? `${primaryManifest.id}\nUpdated: ${localManifestJson.version} → ${primaryManifest.version}. `
|
|
: `${primaryManifest.id}\nUpdated files to ${primaryManifest.version}, but the plugin failed to load (see the developer console). Re-enable it in Community Plugins.`;
|
|
await this.plugin.log(msg, true);
|
|
toastMessage(this.plugin, msg, reloaded ? 30 : 0, () => {
|
|
window.open(releaseNotesUrl);
|
|
});
|
|
return reloaded;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* Disables then re-enables a plugin so its new files are loaded.
|
|
*
|
|
* Obsidian's enablePlugin() resolves to false when the plugin fails to
|
|
* load (its onload throws) instead of throwing. enablePluginAndSave() then
|
|
* reports true for the same broken plugin, so its result can't prove a
|
|
* reload: it only keeps the plugin in the saved enabled list, so it is
|
|
* retried at the next start. Any failure returns false.
|
|
*/
|
|
async reloadPlugin(pluginName: string): Promise<boolean> {
|
|
// @ts-expect-error
|
|
const { plugins } = this.plugin.app;
|
|
let failure: string;
|
|
try {
|
|
await plugins.disablePlugin(pluginName);
|
|
if ((await plugins.enablePlugin(pluginName)) === true) return true;
|
|
failure = "the plugin failed to load";
|
|
} catch (e) {
|
|
failure = e instanceof Error ? e.message : String(e);
|
|
console.error(`BRAT: Failed to reload plugin ${pluginName}`, e);
|
|
}
|
|
await this.plugin.log(
|
|
`Failed to reload ${pluginName} after update: ${failure}`,
|
|
true,
|
|
);
|
|
try {
|
|
await plugins.enablePluginAndSave(pluginName);
|
|
} catch (e2) {
|
|
console.error(`BRAT: Could not keep ${pluginName} enabled`, e2);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
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.debug("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,
|
|
);
|
|
}
|
|
}
|
|
} |