Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Improve marketplace package update flow https://github.com/siyuan-note/siyuan/issues/16980

Daniel892362d1dba7
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index fc98c55a8d..fb960b2f50 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "تعذر التحقق من تحديثات حزم السوق",
"reasoningEffortNone": "بدون",
"reasoningEffortXHigh": "عالٍ جدًا",
"reasoningEffortMax": "الحد الأقصى",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 104faafab8..9db0fadffb 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Prüfen auf Marktplatz-Paketaktualisierungen fehlgeschlagen",
"reasoningEffortNone": "Keine",
"reasoningEffortXHigh": "Sehr hoch",
"reasoningEffortMax": "Maximum",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 202ef0b2d2..e820190d46 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Failed to check marketplace package updates",
"reasoningEffortNone": "None",
"reasoningEffortXHigh": "Extra high",
"reasoningEffortMax": "Maximum",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 28bc3ce2be..2856e0ae1a 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "No se pudieron comprobar las actualizaciones de paquetes del bazar",
"reasoningEffortNone": "Ninguno",
"reasoningEffortXHigh": "Muy alto",
"reasoningEffortMax": "Máximo",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 7a844e4eb0..088b31cb66 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Échec de la vérification des mises à jour des paquets de la place de marché",
"reasoningEffortNone": "Aucun",
"reasoningEffortXHigh": "Très élevé",
"reasoningEffortMax": "Maximum",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index e387183f41..cea9a86ded 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "בדיקת עדכונים לחבילות השוק נכשלה",
"reasoningEffortNone": "ללא",
"reasoningEffortXHigh": "גבוה מאוד",
"reasoningEffortMax": "מרבי",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index d884480341..1fe2794a34 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "बाज़ार पैकेज अपडेट की जाँच विफल रही",
"reasoningEffortNone": "कोई नहीं",
"reasoningEffortXHigh": "बहुत अधिक",
"reasoningEffortMax": "अधिकतम",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 287f0d83a0..383fcefbf8 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Gagal memeriksa pembaruan paket bazar",
"reasoningEffortNone": "Tidak ada",
"reasoningEffortXHigh": "Sangat tinggi",
"reasoningEffortMax": "Maksimum",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 86970b1010..8080601f25 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Impossibile controllare gli aggiornamenti dei pacchetti del marketplace",
"reasoningEffortNone": "Nessuno",
"reasoningEffortXHigh": "Molto alto",
"reasoningEffortMax": "Massimo",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 55a6c66492..23432c44d7 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "マーケットプレイスパッケージの更新確認に失敗しました",
"reasoningEffortNone": "なし",
"reasoningEffortXHigh": "非常に高い",
"reasoningEffortMax": "最大",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 36bd8b0572..76b58bc646 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "마켓 패키지 업데이트를 확인하지 못했습니다",
"reasoningEffortNone": "없음",
"reasoningEffortXHigh": "매우 높음",
"reasoningEffortMax": "최대",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index c24eb59393..a5319b81fe 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Controleren op updates voor marktplaatspakketten is mislukt",
"reasoningEffortNone": "Geen",
"reasoningEffortXHigh": "Zeer hoog",
"reasoningEffortMax": "Maximum",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 2b5439a410..0c24c99d81 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Nie udało się sprawdzić aktualizacji pakietów marketplace",
"reasoningEffortNone": "Brak",
"reasoningEffortXHigh": "Bardzo wysoki",
"reasoningEffortMax": "Maksymalny",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index f10617ff99..b549f61bb5 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Falha ao verificar atualizações dos pacotes do marketplace",
"reasoningEffortNone": "Nenhum",
"reasoningEffortXHigh": "Muito alto",
"reasoningEffortMax": "Máximo",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 94d1413de1..35c3c68301 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Не удалось проверить обновления пакетов маркетплейса",
"reasoningEffortNone": "Нет",
"reasoningEffortXHigh": "Очень высокая",
"reasoningEffortMax": "Максимальная",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 197066513c..2c9b53fa62 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Nepodarilo sa skontrolovať aktualizácie balíkov z trhoviska",
"reasoningEffortNone": "Žiadne",
"reasoningEffortXHigh": "Veľmi vysoká",
"reasoningEffortMax": "Maximálna",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 2faa600ab5..38ded3c602 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "ตรวจสอบการอัปเดตแพ็กเกจในตลาดไม่สำเร็จ",
"reasoningEffortNone": "ไม่มี",
"reasoningEffortXHigh": "สูงมาก",
"reasoningEffortMax": "สูงสุด",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 39cdf6c0ce..a47b18bb2a 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Pazar paketi güncellemeleri denetlenemedi",
"reasoningEffortNone": "Yok",
"reasoningEffortXHigh": "Çok yüksek",
"reasoningEffortMax": "Maksimum",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index a531fba658..003bc52af6 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "Не вдалося перевірити оновлення пакетів маркетплейсу",
"reasoningEffortNone": "Немає",
"reasoningEffortXHigh": "Дуже висока",
"reasoningEffortMax": "Максимальна",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index a179807adc..d39db8187b 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "检查集市包更新失败",
"reasoningEffortNone": "无",
"reasoningEffortXHigh": "超高",
"reasoningEffortMax": "最大",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index f7a4e24831..24d219124f 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "bazaarCheckUpdateFailed": "檢查集市檔更新失敗",
"reasoningEffortNone": "無",
"reasoningEffortXHigh": "超高",
"reasoningEffortMax": "最大",
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.ts
index ad4bde9f73..a4c20a4a26 100644
--- a/app/src/config/bazaar.ts
+++ b/app/src/config/bazaar.ts
@@ -23,6 +23,7 @@ import {switchSettingPanelSubTab} from "./setting/mount";
export const collectBazaarTabSearchStrings = (): string[] => [
window.siyuan.languages.bazaar,
window.siyuan.languages.downloaded,
+ window.siyuan.languages.update,
window.siyuan.languages.plugin,
window.siyuan.languages.theme,
window.siyuan.languages.icon,
@@ -63,6 +64,8 @@ export const renderReadme = (bazaarType: TBazaarType, from: "downloaded" | "upda
export const bazaar = {
element: undefined as Element,
+ _updateState: "idle" as "idle" | "loading" | "loaded" | "error",
+ _updateRequestID: 0,
genHTML() {
if (!window.siyuan.config.bazaar.trust) {
return `<div class="fn__flex-column" style="margin: 0 48px;">
@@ -124,10 +127,11 @@ export const bazaar = {
</div>
<div class="fn__flex-1">
<div class="config-bazaar__panel" data-type="downloaded" data-init="true">
- <div data-type="downloaded-update"></div>
<div class="fn__flex config-bazaar__title">
<button data-type="myPlugin" class="b3-button">${window.siyuan.languages.plugin}</button>
<div class="fn__space"></div>
+ <button data-type="myUpdate" class="b3-button b3-button--outline">${window.siyuan.languages.update}</button>
+ <div class="fn__space"></div>
<button data-type="myTheme" class="b3-button b3-button--outline">${window.siyuan.languages.theme}</button>
<div class="fn__space"></div>
<button data-type="myIcon" class="b3-button b3-button--outline">${window.siyuan.languages.icon}</button>
@@ -136,11 +140,11 @@ export const bazaar = {
<div class="fn__space"></div>
<button data-type="myWidget" class="b3-button b3-button--outline">${window.siyuan.languages.widget}</button>
<div class="fn__space"></div>
- <input class="b3-text-field fn__size200" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">
- <div class="fn__space"></div>
+ <input data-type="downloaded-filter" class="b3-text-field fn__size200" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">
+ <div data-type="downloaded-filter" class="fn__space"></div>
<div class="fn__flex-1"></div>
- <svg class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>
- <div class="fn__space"></div>
+ <svg data-type="downloaded-sort" class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>
+ <div data-type="downloaded-sort" class="fn__space"></div>
<select class="b3-select" data-type="downloaded-sort">
<option ${localSort.downloadedPlugin === "0" ? "selected" : ""} value="0">${window.siyuan.languages.sortDefault}</option>
<option ${localSort.downloadedPlugin === "1" ? "selected" : ""} value="1">${window.siyuan.languages.sortByInstallTimeDesc}</option>
@@ -150,7 +154,9 @@ export const bazaar = {
<option ${localSort.downloadedPlugin === "5" ? "selected" : ""} data-plugin-only="true" value="5">${window.siyuan.languages.sortByEnabledFirst}</option>
<option ${localSort.downloadedPlugin === "6" ? "selected" : ""} data-plugin-only="true" value="6">${window.siyuan.languages.sortByDisabledFirst}</option>
</select>
- <div class="fn__space"></div>
+ <div data-type="downloaded-sort" class="fn__space"></div>
+ <button class="b3-button fn__none" data-type="install-all">${window.siyuan.languages.updateAll}</button>
+ <div data-type="install-all" class="fn__space fn__none"></div>
<input ${window.siyuan.config.bazaar.petalDisabled ? "" : " checked"} data-type="plugins-enable" type="checkbox" class="b3-switch fn__flex-center" style="margin-right: 8px">
<div class="counter counter--bg fn__none fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>
</div>
@@ -291,7 +297,7 @@ export const bazaar = {
},
_genCardHTML(item: IBazaarItem, bazaarType: TBazaarType) {
const showSwitch = item.installed && !item.current && ["icons", "themes"].includes(bazaarType);
- return `<div data-repourl="${escapeAttr(item.repoURL)}" class="b3-card${item.current ? " b3-card--current" : ""}">
+ return `<div data-name="${escapeAttr(item.name)}" data-package-type="${bazaarType}" data-package-source="bazaar" class="b3-card${item.current ? " b3-card--current" : ""}">
<div class="b3-card__img">
<img src="${item.iconURL}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/>
</div>
@@ -346,71 +352,143 @@ export const bazaar = {
}
return window.siyuan.languages.bazaarNeedVersion.replace("${x}", item.updateRequiredMinAppVer || "");
},
- _genUpdateButtonHTML(item: IBazaarItem) {
- if (!item.outdated) {
+ _genUpdateButtonHTML(item?: IBazaarItem, reserveSpace = false) {
+ if (!item?.outdated && !reserveSpace) {
return "";
}
- const ariaLabel = this._genUpdateButtonAriaLabel(item);
- return `<span data-position="north" data-type="install-t" ${item.disallowUpdate ? "disabled" : ""} aria-label="${ariaLabel}" class="ariaLabel block__icon block__icon--show">
+ const ariaLabel = item ? this._genUpdateButtonAriaLabel(item) : window.siyuan.languages.update;
+ return `<span data-position="north" data-type="install-t" ${item?.disallowUpdate ? "disabled" : ""} aria-label="${ariaLabel}" class="ariaLabel block__icon block__icon--show${item?.outdated ? "" : " fn__hidden"}">
<svg class="ft__primary"><use xlink:href="#iconRefresh"></use></svg>
</span>`;
},
- _genReadmeUpdateButtonHTML(item: IBazaarItem) {
- if (!item.outdated) {
+ _genReadmeUpdateButtonHTML(item?: IBazaarItem, reserveSpace = false) {
+ if (!item?.outdated && !reserveSpace) {
return "";
}
- const ariaLabel = this._genUpdateButtonAriaLabel(item);
- return `<div>
- <button ${item.disallowUpdate ? `disabled aria-label="${ariaLabel}" data-position="north"` : ""} class="b3-button ariaLabel" style="width: 168px" data-type="install-t">${window.siyuan.languages.update}</button>
+ const ariaLabel = item ? this._genUpdateButtonAriaLabel(item) : window.siyuan.languages.update;
+ return `<div data-type="readme-update-slot" class="${item?.outdated ? "" : "fn__hidden"}">
+ <button ${item?.disallowUpdate ? `disabled aria-label="${ariaLabel}" data-position="north"` : ""} class="b3-button ariaLabel" style="width: 168px" data-type="install-t">${window.siyuan.languages.update}</button>
</div>`;
},
- _genUpdateItemHTML(item: IBazaarItem) {
- return `<div class="b3-card" data-repourl="${escapeAttr(item.repoURL)}">
- <div class="b3-card__img"><img src="${item.iconURL}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/></div>
+ _genUpdateItemHTML(item: IUpdatedBazaarItem, bazaarType: TBazaarType) {
+ const installed = item.installed;
+ const available = item.available;
+ return `<div class="b3-card" data-name="${escapeAttr(installed.name)}" data-package-type="${bazaarType}" data-package-source="updated">
+ <div class="b3-card__img"><img src="${installed.iconURL}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/></div>
<div class="fn__flex-1 fn__flex-column">
<div class="b3-card__info b3-card__info--left fn__flex-1">
- ${escapeHtml(item.preferredName)}
- <div class="b3-card__desc" title="${escapeAttr(item.preferredDesc)}">${escapeHtml(item.preferredDesc)}</div>
+ ${escapeHtml(installed.preferredName)}
+ <div class="b3-card__desc" title="${escapeAttr(installed.preferredDesc)}">${escapeHtml(installed.preferredDesc)}</div>
</div>
</div>
<div class="b3-card__actions b3-card__actions--right">
- ${bazaar._genIncompatibleChipHTML(item, "bazaar")}
- ${bazaar._genFundingHTML(item.preferredFunding)}
+ ${bazaar._genIncompatibleChipHTML(available, "bazaar")}
+ ${bazaar._genFundingHTML(installed.preferredFunding)}
<span data-position="north" class="ariaLabel block__icon block__icon--show${isBrowser() ? " fn__none" : ""}" data-type="open" aria-label="${window.siyuan.languages.showInFolder}">
<svg><use xlink:href="#iconFolder"></use></svg>
</span>
- ${bazaar._genUpdateButtonHTML(item)}
+ ${bazaar._genUpdateButtonHTML(available)}
</div>
</div>`;
},
- _getUpdate() {
+ _getUpdatedItems(): Array<{type: TBazaarType, item: IUpdatedBazaarItem}> {
+ const items: Array<{type: TBazaarType, item: IUpdatedBazaarItem}> = [];
+ (["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]).forEach((type) => {
+ bazaar._data.update[type].forEach((item) => items.push({type, item}));
+ });
+ return items;
+ },
+ _getUpdatedItem(type: TBazaarType, name: string): IUpdatedBazaarItem | undefined {
+ return bazaar._data.update[type].find((item) => item.installed.name === name);
+ },
+ _isUpdatePanelActive() {
+ return !bazaar.element.querySelector('[data-type="myUpdate"]')?.classList.contains("b3-button--outline");
+ },
+ _checkUpdate(force = false) {
+ if (!force && ["loading", "loaded"].includes(this._updateState)) {
+ return;
+ }
+ this._updateState = "loading";
+ const requestID = ++this._updateRequestID;
+ if (this._isUpdatePanelActive()) {
+ this._renderUpdatePanel();
+ }
fetchPost("/api/bazaar/getUpdatedPackage", {frontend: getFrontend()}, (response) => {
- this._data.update = response.data;
- const items = [
- ...response.data.plugins,
- ...response.data.themes,
- ...response.data.icons,
- ...response.data.templates,
- ...response.data.widgets,
- ];
- const updateElement = this.element.querySelector('[data-type="downloaded-update"]');
- if (!items.length) {
- updateElement.innerHTML = "";
+ if (requestID !== this._updateRequestID || !this.element?.isConnected) {
return;
}
- updateElement.innerHTML = `<div class="fn__flex config-bazaar__title">
- <div class="fn__flex-1"></div>
- <button class="b3-button" data-type="install-all">${window.siyuan.languages.updateAll}</button>
- <span class="fn__space"></span>
- <div class="counter counter--bg fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}">${items.length}</div>
-</div>
-<div class="config-bazaar__content b3-cards b3-cards--nowrap">${items.map((item: IBazaarItem) => this._genUpdateItemHTML(item)).join("")}</div>`;
+ if (response.code !== 0 || !response.data) {
+ this._updateState = "error";
+ if (this._isUpdatePanelActive()) {
+ this._renderUpdatePanel();
+ }
+ return;
+ }
+ this._data.update = response.data;
+ this._updateState = "loaded";
+ this._syncDownloadedUpdateButtons();
+ if (this._isUpdatePanelActive()) {
+ this._renderUpdatePanel();
+ }
});
},
- _genMyHTML(bazaarType: TBazaarType, app: App, updateUpdate = true, preserveOrder = false) {
- if (updateUpdate) {
- this._getUpdate();
+ _renderUpdatePanel() {
+ const contentElement = bazaar.element.querySelector("#configBazaarDownloaded");
+ const counterElement = contentElement.previousElementSibling.querySelector(".counter");
+ const installAllElement = contentElement.previousElementSibling.querySelector('[data-type="install-all"].b3-button');
+ const installAllSpaceElement = contentElement.previousElementSibling.querySelector('[data-type="install-all"].fn__space');
+ installAllElement?.classList.add("fn__none");
+ installAllSpaceElement?.classList.add("fn__none");
+ if (this._updateState === "loading" || this._updateState === "idle") {
+ counterElement.classList.add("fn__none");
+ contentElement.innerHTML = "<div class=\"fn__flex-center\" style=\"height: 96px\"><img src=\"/stage/loading-pure.svg\"></div>";
+ return;
+ }
+ if (this._updateState === "error") {
+ counterElement.classList.add("fn__none");
+ contentElement.innerHTML = `<div class="fn__flex-center" style="height: 96px">
+ <span>${window.siyuan.languages.bazaarCheckUpdateFailed}</span>
+ <span class="fn__space"></span>
+ <button class="b3-button" data-type="retry-update">${window.siyuan.languages.retry}</button>
+</div>`;
+ return;
+ }
+ const items: Array<{type: TBazaarType, item: IUpdatedBazaarItem}> = this._getUpdatedItems();
+ if (items.length === 0) {
+ counterElement.classList.add("fn__none");
+ contentElement.innerHTML = `<ul class="b3-list b3-list--background"><li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li></ul>`;
+ return;
}
+ counterElement.classList.remove("fn__none");
+ counterElement.textContent = items.length.toString();
+ installAllElement?.classList.remove("fn__none");
+ installAllSpaceElement?.classList.remove("fn__none");
+ contentElement.innerHTML = items.map(({type, item}) => this._genUpdateItemHTML(item, type)).join("");
+ },
+ _syncDownloadedUpdateButtons() {
+ bazaar.element.querySelectorAll("#configBazaarDownloaded .b3-card[data-package-source='downloaded']").forEach((card) => {
+ const type = card.getAttribute("data-package-type") as TBazaarType;
+ const name = card.getAttribute("data-name");
+ const slot = card.querySelector('[data-type="install-t"]');
+ if (!slot || !type || !name) {
+ return;
+ }
+ const available = bazaar._getUpdatedItem(type, name)?.available;
+ slot.outerHTML = bazaar._genUpdateButtonHTML(available, true);
+ });
+ const sideElement = bazaar.element.querySelector("#configBazaarReadme.config__view--show .item__side");
+ if (sideElement?.getAttribute("data-from") === "downloaded") {
+ const type = sideElement.getAttribute("data-package-type") as TBazaarType;
+ const name = sideElement.getAttribute("data-name");
+ const slot = sideElement.querySelector('[data-type="readme-update-slot"]');
+ const available = type && name ? bazaar._getUpdatedItem(type, name)?.available : undefined;
+ if (slot) {
+ slot.outerHTML = bazaar._genReadmeUpdateButtonHTML(available, true);
+ sideElement.setAttribute("data-progress-id", available?.repoURL || sideElement.getAttribute("data-repourl") || "");
+ }
+ }
+ },
+ _genMyHTML(bazaarType: TBazaarType, app: App, preserveOrder = false) {
const contentElement = bazaar.element.querySelector("#configBazaarDownloaded");
const myType = bazaar._type2myType(bazaarType);
const typeBtn = contentElement.previousElementSibling.querySelector(`[data-type="${myType}"]`) as HTMLElement;
@@ -418,6 +496,7 @@ export const bazaar = {
typeBtn?.classList.contains("b3-button--outline")) {
return;
}
+ bazaar._updateDownloadedToolbar(bazaarType);
contentElement.setAttribute("data-loading", "true");
const installedAPI: Record<TBazaarType, string> = {
plugins: "/api/bazaar/getInstalledPlugin",
@@ -437,7 +516,7 @@ export const bazaar = {
keyword: (contentElement.previousElementSibling.querySelector(".b3-text-field") as HTMLInputElement)?.value || "",
}, response => {
contentElement.removeAttribute("data-loading");
- const activeBtn = contentElement.previousElementSibling.querySelector(".b3-button:not(.b3-button--outline)") as HTMLElement;
+ const activeBtn = contentElement.previousElementSibling.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)') as HTMLElement;
if (activeBtn?.getAttribute("data-type") !== myType) {
return;
}
@@ -460,7 +539,8 @@ export const bazaar = {
// @ts-ignore
hasSetting = plugin && (plugin.setting || plugin.__proto__.hasOwnProperty("openSetting"));
}
- return `<div data-repourl="${escapeAttr(bazaarItem.repoURL)}" class="b3-card${bazaarItem.current ? " b3-card--current" : ""}">
+ const available = bazaar._getUpdatedItem(bazaarType, bazaarItem.name)?.available;
+ return `<div data-name="${escapeAttr(bazaarItem.name)}" data-package-type="${bazaarType}" data-package-source="downloaded" class="b3-card${bazaarItem.current ? " b3-card--current" : ""}">
<div class="b3-card__img"><img src="${bazaarItem.iconURL}" loading="lazy" onerror="this.src='/stage/images/icon.png'"/></div>
<div class="fn__flex-1 fn__flex-column">
<div class="b3-card__info b3-card__info--left fn__flex-1">
@@ -469,6 +549,7 @@ export const bazaar = {
</div>
</div>
<div class="b3-card__actions b3-card__actions--right">
+ ${bazaar._genUpdateButtonHTML(available, true)}
${bazaar._genIncompatibleChipHTML(bazaarItem, "installed")}
${bazaar._genFundingHTML(bazaarItem.preferredFunding)}
${hasSetting ? `<span data-position="north" class="ariaLabel block__icon block__icon--show${window.siyuan.config.bazaar.petalDisabled ? " fn__none" : ""}" data-type="setting" aria-label="${window.siyuan.languages.config}">
@@ -483,7 +564,6 @@ export const bazaar = {
<span data-position="north" class="ariaLabel block__icon block__icon--show${showSwitch ? "" : " fn__none"}" data-type="switch" aria-label="${window.siyuan.languages.use}">
<svg><use xlink:href="#iconSelect"></use></svg>
</span>
- ${bazaar._genUpdateButtonHTML(bazaarItem)}
<span class="fn__space${bazaarType === "plugins" ? "" : " fn__none"}"></span>
<span class="fn__space${bazaarType === "plugins" ? "" : " fn__none"}"></span>
<input ${((bazaarItem.disallowInstall && !bazaarItem.enabled) || bazaarItem.installedIncompatible) ? "disabled" : ""}
@@ -499,19 +579,14 @@ type="checkbox">
}
bazaar._data.downloadedDefault = response.data.packages;
bazaar._data.downloaded = packages;
- const checkElement = contentElement.parentElement.querySelector(".b3-switch");
- if (bazaarType === "plugins") {
- checkElement.classList.remove("fn__none");
- } else {
- checkElement.classList.add("fn__none");
- }
contentElement.innerHTML = html ? html : `<ul class="b3-list b3-list--background"><li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li></ul>`;
const sideElement = bazaar.element.querySelector("#configBazaarReadme.config__view--show .item__side");
// 仅刷新「已下载」详情,避免通过 URI 打开的在线详情被本地数据覆盖
- if (sideElement?.getAttribute("data-from") === "downloaded") {
- const repoURL = sideElement.getAttribute("data-repourl");
+ if (sideElement?.getAttribute("data-from") === "downloaded" &&
+ sideElement.getAttribute("data-package-type") === bazaarType) {
+ const packageName = sideElement.getAttribute("data-name");
bazaar._data.downloaded.find((i) => {
- if (i.repoURL === repoURL) {
+ if (i.name === packageName) {
bazaar._renderReadme(bazaarType, "downloaded", i);
return true;
}
@@ -528,16 +603,16 @@ type="checkbox">
downloadedDefault: [] as IBazaarItem[],
downloaded: [] as IBazaarItem[],
update: {
- themes: [] as IBazaarItem[],
- templates: [] as IBazaarItem[],
- icons: [] as IBazaarItem[],
- widgets: [] as IBazaarItem[],
- plugins: [] as IBazaarItem[],
+ themes: [] as IUpdatedBazaarItem[],
+ templates: [] as IUpdatedBazaarItem[],
+ icons: [] as IUpdatedBazaarItem[],
+ widgets: [] as IUpdatedBazaarItem[],
+ plugins: [] as IUpdatedBazaarItem[],
}
},
_upsertReadmeData(bazaarType: TBazaarType, from: "downloaded" | "updated" | "bazaar", data: IBazaarItem) {
const upsert = (list: IBazaarItem[]) => {
- const index = list.findIndex((item) => item.repoURL === data.repoURL);
+ const index = list.findIndex((item) => item.name === data.name);
if (index >= 0) {
list[index] = data;
} else {
@@ -547,7 +622,10 @@ type="checkbox">
if (from === "downloaded") {
upsert(bazaar._data.downloaded);
} else if (from === "updated") {
- upsert(bazaar._data.update[bazaarType]);
+ const updated = bazaar._data.update[bazaarType].find((item) => item.installed.name === data.name);
+ if (updated) {
+ updated.available = data;
+ }
} else {
upsert(bazaar._data[bazaarType]);
}
@@ -568,7 +646,8 @@ type="checkbox">
}
bazaar._upsertReadmeData(bazaarType, from, data);
const isDownload = from === "downloaded";
- readmeElement.innerHTML = ` <div class="item__side" data-from="${from}" data-package-type="${bazaarType}" data-repourl="${escapeAttr(data.repoURL)}">
+ const updateData = isDownload ? bazaar._getUpdatedItem(bazaarType, data.name)?.available : data;
+ readmeElement.innerHTML = ` <div class="item__side" data-from="${from}" data-name="${escapeAttr(data.name)}" data-package-type="${bazaarType}" data-repourl="${escapeAttr(data.repoURL)}" data-progress-id="${escapeAttr(updateData?.repoURL || data.repoURL)}">
<div class="block__icons">
<div class="block__logo fn__pointer fn__flex-1" data-type="goBack">
<svg class="block__logoicon"><use xlink:href="#iconLeft"></use></svg>
@@ -602,13 +681,13 @@ type="checkbox">
<div class="fn__hr${isDownload ? " fn__none" : ""}"></div>
<div class="ft__on-surface ft__smaller${isDownload ? " fn__none" : ""}" style="line-height: 20px;">${window.siyuan.languages.pkgSize}<br>${data.hSize}</div>
<div class="fn__hr"></div>
- <div class="ft__on-surface ft__smaller" style="line-height: 20px;">${window.siyuan.languages.installSize}<br>${data.hInstallSize}</div>
+ <div class="ft__on-surface ft__smaller" style="line-height: 20px;">${window.siyuan.languages.installSize}<br><span data-type="installed-size">${isDownload ? window.siyuan.languages.loading : data.hInstallSize}</span></div>
<div class="fn__hr--b"></div>
<div class="fn__hr--b"></div>
<div${data.installed ? ' class="fn__none"' : ""}>
<button ${data.disallowInstall ? `disabled aria-label="${bazaar._genInstallButtonAriaLabel(data)}" data-position="north"` : ""} class="b3-button ariaLabel" style="width: 168px" data-type="install">${window.siyuan.languages.download}</button>
</div>
- ${bazaar._genReadmeUpdateButtonHTML(data)}
+ ${bazaar._genReadmeUpdateButtonHTML(updateData, isDownload)}
<div class="fn__hr--b"></div>
<div>
<a href="${data.repoURL}/issues" target="_blank" title="Feedback via GitHub Issues" class="b3-button b3-button--success" style="width: 168px" data-type="feedback">${window.siyuan.languages.feedback}</a>
@@ -657,6 +736,21 @@ type="checkbox">
const mdElement = readmeElement.querySelector(".item__readme");
mdElement.innerHTML = window.DOMPurify.sanitize(data.preferredReadme || "", {FORBID_TAGS: ["iframe", "frame", "frameset"]});
highlightRender(mdElement);
+ fetchPost("/api/bazaar/getInstalledPackageSize", {
+ packageType: bazaarType,
+ packageName: data.name,
+ }, response => {
+ const sideElement = readmeElement.querySelector(".item__side");
+ if (sideElement?.getAttribute("data-from") !== "downloaded" ||
+ sideElement.getAttribute("data-package-type") !== bazaarType ||
+ sideElement.getAttribute("data-name") !== data.name) {
+ return;
+ }
+ const sizeElement = sideElement.querySelector('[data-type="installed-size"]');
+ if (sizeElement) {
+ sizeElement.textContent = response.code === 0 && response.data?.hInstallSize ? response.data.hInstallSize : "-";
+ }
+ });
} else {
fetchPost("/api/bazaar/getBazaarPackageREADME", {
repoURL: data.repoURL,
@@ -701,6 +795,18 @@ type="checkbox">
option.hidden = type !== "plugins";
});
},
+ _updateDownloadedToolbar(type: TBazaarType | "update") {
+ const titleElement = bazaar.element.querySelector('.config-bazaar__panel[data-type="downloaded"] .config-bazaar__title');
+ const isUpdate = type === "update";
+ titleElement?.querySelectorAll('[data-type="downloaded-filter"], [data-type="downloaded-sort"]').forEach((element) => {
+ element.classList.toggle("fn__none", isUpdate);
+ });
+ titleElement?.querySelector('[data-type="plugins-enable"]')?.classList.toggle("fn__none", type !== "plugins");
+ if (!isUpdate) {
+ titleElement?.querySelector('[data-type="install-all"].b3-button')?.classList.add("fn__none");
+ titleElement?.querySelector('[data-type="install-all"].fn__space')?.classList.add("fn__none");
+ }
+ },
_preserveDownloadedOrder(packages: IBazaarItem[]) {
const positions = new Map(bazaar._data.downloaded.map((item, index) => [item.name, index]));
return packages.map((item, index) => ({item, index})).sort((a, b) => {
@@ -762,12 +868,12 @@ type="checkbox">
_reorderDownloadedCards(packages: IBazaarItem[]) {
const contentElement = bazaar.element.querySelector("#configBazaarDownloaded");
const cards = new Map(Array.from(contentElement.children).filter((item) => item.classList.contains("b3-card")).map((card) => [
- card.getAttribute("data-repourl"),
+ card.getAttribute("data-name"),
card,
]));
const fragment = document.createDocumentFragment();
packages.forEach((item) => {
- const card = cards.get(item.repoURL);
+ const card = cards.get(item.name);
if (card) {
fragment.append(card);
}
@@ -835,14 +941,20 @@ type="checkbox">
bazaar._initBazaarPanel(app, bazaarType, panel as HTMLElement);
}
});
- if (from === "downloaded") {
- const myType = bazaar._type2myType(bazaarType);
+ if (from !== "bazaar") {
+ const myType = from === "updated" ? "myUpdate" : bazaar._type2myType(bazaarType);
const titleBar = bazaar.element.querySelector('.config-bazaar__panel[data-type="downloaded"] .config-bazaar__title');
- titleBar?.querySelectorAll(".b3-button").forEach((btn) => {
+ titleBar?.querySelectorAll('.b3-button[data-type^="my"]').forEach((btn) => {
btn.classList.toggle("b3-button--outline", btn.getAttribute("data-type") !== myType);
});
bazaar.element.querySelector("#configBazaarDownloaded")?.removeAttribute("data-loading");
- bazaar._genMyHTML(bazaarType, app, false);
+ if (from === "updated") {
+ bazaar._updateDownloadedToolbar("update");
+ bazaar._renderUpdatePanel();
+ bazaar._checkUpdate();
+ } else {
+ bazaar._genMyHTML(bazaarType, app);
+ }
}
},
bindEvent(app: App) {
@@ -859,55 +971,32 @@ type="checkbox">
});
return;
}
+ this._updateState = "idle";
+ this._updateRequestID++;
+ (["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]).forEach((type) => {
+ this._data.update[type] = [];
+ });
this._genMyHTML("plugins", app);
+ this._checkUpdate(true);
bazaar.element.firstElementChild.addEventListener("click", (event) => {
let target = event.target as HTMLElement;
- const repoElement = hasClosestByAttribute(target, "data-repourl", null);
+ const packageElement = hasClosestByAttribute(target, "data-name", null);
let pkgType: TBazaarType | undefined;
let pkgItem: IBazaarItem;
- if (repoElement) {
- const repo = repoElement.getAttribute("data-repourl");
- if (repoElement.classList.contains("item__side")) {
- const sideForm = repoElement.getAttribute("data-from");
- const sidePackageType = repoElement.getAttribute("data-package-type") as TBazaarType;
- if (sidePackageType && sideForm === "downloaded") {
- pkgType = sidePackageType;
- pkgItem = bazaar._data.downloaded.find((i) => i.repoURL === repo);
- } else if (sidePackageType && sideForm === "updated") {
- pkgType = sidePackageType;
- pkgItem = bazaar._data.update[sidePackageType]?.find((i) => i.repoURL === repo);
- } else if (sidePackageType && sideForm === "bazaar") {
- pkgType = sidePackageType;
- pkgItem = bazaar._data[sidePackageType]?.find((i) => i.repoURL === repo);
- }
- } else if (hasClosestByAttribute(repoElement, "data-type", "downloaded-update")) {
- for (const bazaarType of ["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]) {
- const item = bazaar._data.update[bazaarType]?.find((i) => i.repoURL === repo);
- if (item) {
- pkgType = bazaarType;
- pkgItem = item;
- break;
- }
- }
- } else if (hasClosestByAttribute(repoElement, "id", "configBazaarDownloaded")) {
- const activeBtn = bazaar.element.querySelector("#configBazaarDownloaded")?.previousElementSibling?.querySelector(".b3-button:not(.b3-button--outline)") as HTMLElement;
- if (activeBtn?.getAttribute("data-type")) {
- const activeBazaarType = bazaar._myType2Type(activeBtn.getAttribute("data-type"));
- const item = bazaar._data.downloaded.find((i) => i.repoURL === repo);
- if (item) {
- pkgType = activeBazaarType;
- pkgItem = item;
- }
- }
- } else {
- for (const bazaarType of ["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]) {
- const item = bazaar._data[bazaarType]?.find((i) => i.repoURL === repo);
- if (item) {
- pkgType = bazaarType;
- pkgItem = item;
- break;
- }
- }
+ let updatedItem: IUpdatedBazaarItem;
+ let packageSource: "downloaded" | "updated" | "bazaar";
+ if (packageElement) {
+ const packageName = packageElement.getAttribute("data-name");
+ pkgType = packageElement.getAttribute("data-package-type") as TBazaarType;
+ packageSource = (packageElement.getAttribute("data-package-source") ||
+ packageElement.getAttribute("data-from")) as "downloaded" | "updated" | "bazaar";
+ if (packageName && pkgType && packageSource === "downloaded") {
+ pkgItem = bazaar._data.downloaded.find((item) => item.name === packageName);
+ } else if (packageName && pkgType && packageSource === "updated") {
+ updatedItem = bazaar._getUpdatedItem(pkgType, packageName);
+ pkgItem = updatedItem?.available;
+ } else if (packageName && pkgType && packageSource === "bazaar") {
+ pkgItem = bazaar._data[pkgType]?.find((item) => item.name === packageName);
}
}
while (target && !target.isEqualNode(bazaar.element)) {
@@ -935,20 +1024,29 @@ type="checkbox">
event.preventDefault();
event.stopPropagation();
break;
- } else if (["myTheme", "myTemplate", "myIcon", "myWidget", "myPlugin"].includes(type)) {
+ } else if (["myTheme", "myTemplate", "myIcon", "myWidget", "myPlugin", "myUpdate"].includes(type)) {
if (target.classList.contains("b3-button--outline") &&
!bazaar.element.querySelector("#configBazaarDownloaded").getAttribute("data-loading")) {
- target.parentElement.childNodes.forEach((item: HTMLElement) => {
- if (item.nodeType !== 3 && item.classList.contains("b3-button")) {
- item.classList.add("b3-button--outline");
- }
+ target.parentElement.querySelectorAll('.b3-button[data-type^="my"]').forEach((item: HTMLElement) => {
+ item.classList.add("b3-button--outline");
});
target.classList.remove("b3-button--outline");
- this._genMyHTML(bazaar._myType2Type(type), app, false);
+ if (type === "myUpdate") {
+ bazaar._updateDownloadedToolbar("update");
+ bazaar._renderUpdatePanel();
+ bazaar._checkUpdate();
+ } else {
+ this._genMyHTML(bazaar._myType2Type(type), app);
+ }
}
event.preventDefault();
event.stopPropagation();
break;
+ } else if (type === "retry-update") {
+ bazaar._checkUpdate(true);
+ event.preventDefault();
+ event.stopPropagation();
+ break;
} else if (type === "goBack") {
bazaar.element.querySelector("#configBazaarReadme").classList.remove("config__view--show");
event.preventDefault();
@@ -1000,15 +1098,13 @@ type="checkbox">
break;
} else if (type === "install-all") {
confirmDialog("⬆️ " + window.siyuan.languages.updateAll, window.siyuan.languages.confirmUpdateAll, () => {
- fetchPost("/api/bazaar/batchUpdatePackage", {frontend: getFrontend()}, () => {
- let activeBazaarType: TBazaarType = "plugins";
- const activeBtn = bazaar.element.querySelector("#configBazaarDownloaded")?.previousElementSibling?.querySelector(".b3-button:not(.b3-button--outline)") as HTMLElement;
- if (activeBtn?.getAttribute("data-type")) {
- activeBazaarType = bazaar._myType2Type(activeBtn.getAttribute("data-type"));
- }
- if (activeBazaarType) {
- bazaar._genMyHTML(activeBazaarType, app);
+ fetchPost("/api/bazaar/batchUpdatePackage", {frontend: getFrontend()}, (response) => {
+ if (response.code !== 0) {
+ showMessage(response.msg);
+ return;
}
+ bazaar.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");
+ bazaar._checkUpdate(true);
});
});
event.preventDefault();
@@ -1019,28 +1115,26 @@ type="checkbox">
event.stopPropagation();
break;
} else if (type === "install-t") {
- if (!target.classList.contains("b3-button--progress") && !target.hasAttribute("disabled") && pkgItem && pkgType) {
+ const packageName = updatedItem?.installed.name || pkgItem?.name;
+ if (!target.classList.contains("b3-button--progress") && !target.hasAttribute("disabled") && packageName && pkgType) {
confirmDialog("⬆️ " + window.siyuan.languages.update, window.siyuan.languages.confirmUpdate, () => {
- const installAPI: Record<TBazaarType, string> = {
- plugins: "/api/bazaar/installBazaarPlugin",
- themes: "/api/bazaar/installBazaarTheme",
- icons: "/api/bazaar/installBazaarIcon",
- templates: "/api/bazaar/installBazaarTemplate",
- widgets: "/api/bazaar/installBazaarWidget",
- };
if (!target.classList.contains("b3-button")) {
target.parentElement.insertAdjacentHTML("afterend", '<img data-type="img-loading" style="position: absolute;top: 0;left: 0;height: 100%;width: 100%;padding: 16px;box-sizing: border-box;" src="/stage/loading-pure.svg">');
}
- fetchPost(installAPI[pkgType], {
- keyword: (bazaar.element.querySelector(`.config-bazaar__panel[data-type="${bazaar._type2tabType(pkgType)}"] .b3-text-field`) as HTMLInputElement).value,
- repoURL: pkgItem.repoURL,
- packageName: pkgItem.name,
- repoHash: pkgItem.repoHash,
- mode: pkgItem.modes?.toString() === "dark" ? 1 : 0,
+ fetchPost("/api/bazaar/updateBazaarPackage", {
+ packageType: pkgType,
+ packageName,
frontend: getFrontend()
}, response => {
+ if (response.code !== 0) {
+ showMessage(response.msg);
+ target.parentElement.parentElement.querySelector("img[data-type='img-loading']")?.remove();
+ return;
+ }
+ bazaar.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");
this._genMyHTML(pkgType, app);
bazaar._onBazaar(response, pkgType);
+ bazaar._checkUpdate(true);
});
});
}
@@ -1071,6 +1165,7 @@ type="checkbox">
}, response => {
this._genMyHTML(pkgType, app);
bazaar._onBazaar(response, pkgType);
+ bazaar._checkUpdate(true);
});
});
}
@@ -1133,8 +1228,8 @@ type="checkbox">
if (window.siyuan.config.bazaar.petalDisabled) {
bazaar.element.querySelectorAll("#configBazaarDownloaded .b3-card").forEach(item => {
item.querySelector('[data-type="setting"]')?.classList.add("fn__none");
- const repoURL = item.getAttribute("data-repourl");
- const pkg = bazaar._data.downloaded.find((p: IBazaarItem) => p.repoURL === repoURL);
+ const packageName = item.getAttribute("data-name");
+ const pkg = bazaar._data.downloaded.find((p: IBazaarItem) => p.name === packageName);
if (pkg) {
uninstall(app, pkg.name, true);
}
@@ -1170,7 +1265,7 @@ type="checkbox">
return;
}
loadPlugin(app, response.data).then(() => {
- this._genMyHTML("plugins", app, false, true);
+ this._genMyHTML("plugins", app, true);
});
} else {
uninstall(app, pkgItem.name, true);
@@ -1187,8 +1282,7 @@ type="checkbox">
break;
} else if (target.classList.contains("b3-card")) {
if (!hasClosestByClassName(event.target as HTMLElement, "b3-card__actions--right") && pkgItem && pkgType) {
- bazaar._renderReadme(pkgType,
- target.closest('[data-type="downloaded-update"]') ? "updated" : (target.parentElement.id === "configBazaarDownloaded" ? "downloaded" : "bazaar"), pkgItem);
+ bazaar._renderReadme(pkgType, packageSource, pkgItem);
}
event.preventDefault();
event.stopPropagation();
@@ -1257,7 +1351,10 @@ type="checkbox">
bazaar._data.plugins = response.data.packages;
});
} else if (type === "downloaded") {
- this._genMyHTML(bazaar._myType2Type(inputElement.parentElement.querySelector(".b3-button:not(.b3-button--outline)").getAttribute("data-type")), app);
+ const activeType = inputElement.parentElement.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)')?.getAttribute("data-type");
+ if (activeType && activeType !== "myUpdate") {
+ this._genMyHTML(bazaar._myType2Type(activeType), app);
+ }
}
event.preventDefault();
return;
@@ -1268,7 +1365,10 @@ type="checkbox">
bazaar.element.querySelectorAll(".b3-select").forEach((selectElement: HTMLSelectElement) => {
selectElement.addEventListener("change", () => {
if (selectElement.getAttribute("data-type") === "downloaded-sort") {
- const activeBtn = bazaar.element.querySelector("#configBazaarDownloaded")?.previousElementSibling?.querySelector(".b3-button:not(.b3-button--outline)") as HTMLElement;
+ const activeBtn = bazaar.element.querySelector("#configBazaarDownloaded")?.previousElementSibling?.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)') as HTMLElement;
+ if (activeBtn?.getAttribute("data-type") === "myUpdate") {
+ return;
+ }
const bazaarType = bazaar._myType2Type(activeBtn.getAttribute("data-type"));
window.siyuan.storage[Constants.LOCAL_BAZAAR][bazaar._getDownloadedSortStorageKey(bazaarType)] = selectElement.value;
setStorageVal(Constants.LOCAL_BAZAAR, window.siyuan.storage[Constants.LOCAL_BAZAAR]);
diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.ts
index cf195da4a2..769a28952e 100644
--- a/app/src/dialog/processSystem.ts
+++ b/app/src/dialog/processSystem.ts
@@ -429,7 +429,7 @@ export const downloadProgress = (data: { id: string, percent: number }) => {
if (!bazaarSideElement) {
return;
}
- if (data.id !== bazaarSideElement.getAttribute("data-repourl")) {
+ if (data.id !== (bazaarSideElement.getAttribute("data-progress-id") || bazaarSideElement.getAttribute("data-repourl"))) {
return;
}
const installBtnElement = bazaarSideElement.querySelector('[data-type="install"]') as HTMLElement;
diff --git a/kernel/api/bazaar.go b/kernel/api/bazaar.go
index b266a698bc..fb2ac8d606 100644
--- a/kernel/api/bazaar.go
+++ b/kernel/api/bazaar.go
@@ -47,7 +47,10 @@ func batchUpdatePackage(c *gin.Context) {
return
}
- model.BatchUpdatePackages(frontend)
+ if err := model.BatchUpdatePackages(frontend); err != nil {
+ ret.Code = 1
+ ret.Msg = err.Error()
+ }
}
func getUpdatedPackage(c *gin.Context) {
@@ -64,7 +67,12 @@ func getUpdatedPackage(c *gin.Context) {
return
}
- plugins, widgets, icons, themes, templates := model.GetUpdatedPackages(frontend)
+ plugins, widgets, icons, themes, templates, err := model.GetUpdatedPackages(frontend)
+ if err != nil {
+ ret.Code = 1
+ ret.Msg = err.Error()
+ return
+ }
ret.Data = map[string]any{
"plugins": plugins,
"widgets": widgets,
@@ -74,6 +82,72 @@ func getUpdatedPackage(c *gin.Context) {
}
}
+func updateBazaarPackage(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var pkgType, packageName, frontend string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("packageType", &pkgType, true, true),
+ util.BindJsonArg("packageName", &packageName, true, true),
+ util.BindJsonArg("frontend", &frontend, true, true),
+ ) {
+ return
+ }
+ if !validPackageTypes[pkgType] {
+ ret.Code = 1
+ ret.Msg = "Invalid package type"
+ return
+ }
+ if err := model.UpdateBazaarPackage(pkgType, packageName, frontend); err != nil {
+ ret.Code = 1
+ ret.Msg = err.Error()
+ return
+ }
+ util.PushMsg(model.Conf.Language(69), 3000)
+ ret.Data = map[string]any{
+ "packages": model.GetBazaarPackages(pkgType, frontend, ""),
+ }
+}
+
+func getInstalledPackageSize(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var pkgType, packageName string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("packageType", &pkgType, true, true),
+ util.BindJsonArg("packageName", &packageName, true, true),
+ ) {
+ return
+ }
+ if !validPackageTypes[pkgType] {
+ ret.Code = 1
+ ret.Msg = "Invalid package type"
+ return
+ }
+ size, hSize, err := model.GetInstalledPackageSize(pkgType, packageName)
+ if err != nil {
+ ret.Code = 1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = map[string]any{
+ "installSize": size,
+ "hInstallSize": hSize,
+ }
+}
+
func getBazaarPackageREADME(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/bazaar/bazaar.go b/kernel/bazaar/bazaar.go
index de2136c7fa..cbf5747b62 100644
--- a/kernel/bazaar/bazaar.go
+++ b/kernel/bazaar/bazaar.go
@@ -17,6 +17,7 @@
package bazaar
import (
+ "errors"
"strings"
"time"
@@ -27,10 +28,19 @@ import (
// GetBazaarPackages 返回指定类型的在线集市包列表(plugins 类型需要传递 frontend 参数)。
func GetBazaarPackages(pkgType string, frontend string) (packages []*Package) {
- result := getStageAndBazaar(pkgType)
+ packages, _ = getBazaarPackages(pkgType, frontend, true)
+ return
+}
+func getBazaarPackages(pkgType, frontend string, showError bool) (packages []*Package, err error) {
+ result := getStageAndBazaar(pkgType, showError)
if !result.Online || nil != result.StageErr || nil == result.StageIndex {
- return make([]*Package, 0)
+ if nil != result.StageErr {
+ err = result.StageErr
+ } else {
+ err = errors.New("bazaar is offline")
+ }
+ return make([]*Package, 0), err
}
packages = make([]*Package, 0, len(result.StageIndex.Repos))
@@ -45,15 +55,18 @@ func GetBazaarPackages(pkgType string, frontend string) (packages []*Package) {
}
// GetBazaarPackagesMap 返回按包名索引的在线集市包映射(plugins 类型需要传递 frontend 参数)。
-func GetBazaarPackagesMap(pkgType, frontend string) map[string]*Package {
- packages := GetBazaarPackages(pkgType, frontend)
- packagesMap := make(map[string]*Package, len(packages))
+func GetBazaarPackagesMap(pkgType, frontend string) (packagesMap map[string]*Package, err error) {
+ packages, err := getBazaarPackages(pkgType, frontend, false)
+ if err != nil {
+ return map[string]*Package{}, err
+ }
+ packagesMap = make(map[string]*Package, len(packages))
for _, pkg := range packages {
if "" != pkg.Name {
packagesMap[pkg.Name] = pkg
}
}
- return packagesMap
+ return
}
// buildBazaarPackageWithMetadata 从 StageRepo 构建带有在线元数据的集市包。
@@ -104,10 +117,6 @@ func buildBazaarPackageWithMetadata(repo *StageRepo, bazaarStats map[string]*baz
if stats := bazaarStats[repoURLHash[0]]; nil != stats { // 通过 bazaarStats[owner/repo] 获取单个包的统计数据
pkg.Downloads = stats.Downloads
}
- // TODO 分离本地安装大小和在线 stage 数据的安装大小,不保存到 installSizeCache
- bazaarMemMu.Lock()
- installSizeCache[pkg.RepoURL] = pkg.InstallSize
- bazaarMemMu.Unlock()
return &pkg
}
diff --git a/kernel/bazaar/install.go b/kernel/bazaar/install.go
index 3410fb8157..65a3276719 100644
--- a/kernel/bazaar/install.go
+++ b/kernel/bazaar/install.go
@@ -98,6 +98,7 @@ func InstallPackage(repoURL, repoHash, installPath, systemID, pkgType, packageNa
if err = installPackage(data, installPath); err != nil {
return err
}
+ RemoveInstalledPackageSizeCache(pkgType, packageName)
// 记录首次安装时间或最近更新时间
now := time.Now()
diff --git a/kernel/bazaar/installed.go b/kernel/bazaar/installed.go
index 8518ec4973..d5fc2ccd11 100644
--- a/kernel/bazaar/installed.go
+++ b/kernel/bazaar/installed.go
@@ -31,6 +31,18 @@ import (
"golang.org/x/sync/singleflight"
)
+type installSizeCacheEntry struct {
+ size int64
+ expiresAt time.Time
+}
+
+var (
+ installSizeCacheMu sync.RWMutex
+ installSizeCache = make(map[string]installSizeCacheEntry)
+ installSizeVersion = make(map[string]uint64)
+ installSizeFlight singleflight.Group
+)
+
// ReadInstalledPackageDirs 读取本地集市包的目录列表
func ReadInstalledPackageDirs(basePath string) ([]os.DirEntry, error) {
if !util.IsPathRegularDirOrSymlinkDir(basePath) {
@@ -52,7 +64,7 @@ func ReadInstalledPackageDirs(basePath string) ([]os.DirEntry, error) {
}
// SetInstalledPackageMetadata 设置本地集市包的通用元数据
-func SetInstalledPackageMetadata(pkg *Package, installPath, baseURLPath, pkgType, frontend string, bazaarPackagesMap map[string]*Package) bool {
+func SetInstalledPackageMetadata(pkg *Package, installPath, baseURLPath, pkgType string) bool {
// 展示信息
pkg.IconURL = baseURLPath + "icon.png"
pkg.PreviewURL = baseURLPath + "preview.png"
@@ -61,56 +73,65 @@ func SetInstalledPackageMetadata(pkg *Package, installPath, baseURLPath, pkgType
pkg.PreferredReadme = getInstalledPackageREADME(installPath, baseURLPath, pkg.Readme)
pkg.PreferredFunding = getPreferredFunding(pkg.Funding)
- // 更新信息
+ // 安装状态
pkg.Installed = true
pkg.DisallowInstall = isBelowRequiredAppVersion(pkg)
- if bazaarPkg := bazaarPackagesMap[pkg.Name]; nil != bazaarPkg {
- pkg.RepoURL = bazaarPkg.RepoURL // 更新链接使用在线数据,避免本地元数据的链接错误
- pkg.UpdateRequiredMinAppVer = bazaarPkg.MinAppVersion
-
- if 0 > semver.Compare("v"+pkg.Version, "v"+bazaarPkg.Version) {
- pkg.RepoHash = bazaarPkg.RepoHash
- pkg.Outdated = true
- disallowUpdate := isBelowRequiredAppVersion(bazaarPkg)
- if "plugins" == pkgType {
- disallowUpdate = disallowUpdate || IsIncompatiblePlugin(bazaarPkg, frontend)
- }
- pkg.DisallowUpdate = disallowUpdate
- pkg.Updated = bazaarPkg.Updated
- pkg.HUpdated = bazaarPkg.HUpdated
- pkg.Size = bazaarPkg.Size
- pkg.HSize = bazaarPkg.HSize
- pkg.Stars = bazaarPkg.Stars
- pkg.OpenIssues = bazaarPkg.OpenIssues
- pkg.Downloads = bazaarPkg.Downloads
- }
- } else {
- pkg.RepoURL = pkg.URL
- }
+ pkg.RepoURL = pkg.URL
// 安装信息
pkg.InstallTime, pkg.UpdateTime = getPackageTimes(pkgType, pkg.Name, installPath)
pkg.HInstallDate = time.UnixMilli(pkg.InstallTime).Format("2006-01-02")
- // TODO 本地安装大小的缓存改成 1 分钟有效,打开集市包 README 的时候才遍历集市包文件夹进行统计,异步返回结果到前端显示 https://github.com/siyuan-note/siyuan/issues/16983
- // 目前优先使用在线 stage 数据:不耗时,但可能不准确,比如本地旧版本与云端最新版本的安装大小可能不一致;其次使用本地目录大小:耗时,但准确
- // 需要分离本地安装大小和在线 stage 数据的安装大小
- bazaarMemMu.RLock()
- cachedSize, hit := installSizeCache[pkg.RepoURL]
- bazaarMemMu.RUnlock()
- if hit {
- pkg.InstallSize = cachedSize
- } else {
- size, _ := util.SizeOfDirectory(installPath)
- pkg.InstallSize = size
- bazaarMemMu.Lock()
- installSizeCache[pkg.RepoURL] = size
- bazaarMemMu.Unlock()
- }
- pkg.HInstallSize = humanize.BytesCustomCeil(uint64(pkg.InstallSize), 2)
return true
}
+// GetInstalledPackageSize 获取本地集市包的安装大小,结果缓存一分钟
+func GetInstalledPackageSize(pkgType, packageName, installPath string) (size int64, hSize string, err error) {
+ cacheKey := pkgType + ":" + packageName
+ now := time.Now()
+ installSizeCacheMu.RLock()
+ cached, hit := installSizeCache[cacheKey]
+ version := installSizeVersion[cacheKey]
+ installSizeCacheMu.RUnlock()
+ if hit && now.Before(cached.expiresAt) {
+ size = cached.size
+ hSize = humanize.BytesCustomCeil(uint64(size), 2)
+ return
+ }
+
+ v, err, _ := installSizeFlight.Do(cacheKey, func() (any, error) {
+ ret, sizeErr := util.SizeOfDirectory(installPath)
+ if sizeErr != nil {
+ return int64(0), sizeErr
+ }
+ installSizeCacheMu.Lock()
+ if installSizeVersion[cacheKey] == version {
+ installSizeCache[cacheKey] = installSizeCacheEntry{
+ size: ret,
+ expiresAt: time.Now().Add(time.Minute),
+ }
+ }
+ installSizeCacheMu.Unlock()
+ return ret, nil
+ })
+ if err != nil {
+ return
+ }
+ size = v.(int64)
+ hSize = humanize.BytesCustomCeil(uint64(size), 2)
+ return
+}
+
+// RemoveInstalledPackageSizeCache 删除本地集市包的安装大小缓存
+func RemoveInstalledPackageSizeCache(pkgType, packageName string) {
+ cacheKey := pkgType + ":" + packageName
+ installSizeCacheMu.Lock()
+ delete(installSizeCache, cacheKey)
+ installSizeVersion[cacheKey]++
+ installSizeCacheMu.Unlock()
+ installSizeFlight.Forget(cacheKey)
+}
+
// Add marketplace package config item `minAppVersion` https://github.com/siyuan-note/siyuan/issues/8330
func isBelowRequiredAppVersion(pkg *Package) bool {
// 如果包没有指定 minAppVersion,则允许安装
diff --git a/kernel/bazaar/installed_test.go b/kernel/bazaar/installed_test.go
index 2403921171..59e9ac0889 100644
--- a/kernel/bazaar/installed_test.go
+++ b/kernel/bazaar/installed_test.go
@@ -17,6 +17,8 @@
package bazaar
import (
+ "os"
+ "path/filepath"
"testing"
"time"
@@ -68,3 +70,45 @@ func TestRecordPackageOperationTime(t *testing.T) {
t.Fatalf("update time was not cleared after reinstall: %d", info.UpdateTime)
}
}
+
+func TestInstalledPackageSizeCacheAndInvalidation(t *testing.T) {
+ installPath := t.TempDir()
+ if err := os.WriteFile(filepath.Join(installPath, "first"), []byte("first"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ const pkgType = "plugins"
+ const packageName = "size-cache-test"
+ RemoveInstalledPackageSizeCache(pkgType, packageName)
+ t.Cleanup(func() {
+ RemoveInstalledPackageSizeCache(pkgType, packageName)
+ })
+
+ firstSize, firstHSize, err := GetInstalledPackageSize(pkgType, packageName, installPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if firstSize < 1 || firstHSize == "" {
+ t.Fatalf("expected a formatted non-zero size, got %d and %q", firstSize, firstHSize)
+ }
+
+ if err = os.WriteFile(filepath.Join(installPath, "second"), []byte("second file"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ cachedSize, _, err := GetInstalledPackageSize(pkgType, packageName, installPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cachedSize != firstSize {
+ t.Fatalf("expected cached size %d, got %d", firstSize, cachedSize)
+ }
+
+ RemoveInstalledPackageSizeCache(pkgType, packageName)
+ refreshedSize, _, err := GetInstalledPackageSize(pkgType, packageName, installPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if refreshedSize <= firstSize {
+ t.Fatalf("expected refreshed size greater than %d, got %d", firstSize, refreshedSize)
+ }
+}
diff --git a/kernel/bazaar/stage.go b/kernel/bazaar/stage.go
index 27f76fab93..1f3b06148a 100644
--- a/kernel/bazaar/stage.go
+++ b/kernel/bazaar/stage.go
@@ -33,7 +33,6 @@ var (
bazaarCacheRhyHash string // bazaar hash,发生变更时清空以下缓存
stageIndexCache = make(map[string]*StageIndex) // pkgType -> 集市包索引
bazaarStatsCache = make(map[string]*bazaarStats) // 集市统计数据
- installSizeCache = make(map[string]int64) // repoURL -> 安装大小
)
func applyRhyBazaarHash(ctx context.Context) {
@@ -46,7 +45,6 @@ func applyRhyBazaarHash(ctx context.Context) {
if bazaarCacheRhyHash != "" && bazaarHash != bazaarCacheRhyHash {
clear(stageIndexCache)
clear(bazaarStatsCache)
- clear(installSizeCache)
logging.LogInfof("rhy bazaar hash changed, clearing bazaar caches")
}
bazaarCacheRhyHash = bazaarHash
@@ -64,7 +62,7 @@ var onlineCheckFlight singleflight.Group
var bazaarStatsFlight singleflight.Group
// getStageAndBazaar 获取 stage 索引和 bazaar 索引,相同 pkgType 的并发调用会合并为一次实际请求 (single-flight)
-func getStageAndBazaar(pkgType string) (result StageBazaarResult) {
+func getStageAndBazaar(pkgType string, showError bool) (result StageBazaarResult) {
key := "stageBazaar:" + pkgType
v, err, _ := stageBazaarFlight.Do(key, func() (any, error) {
return getStageAndBazaar0(pkgType), nil
@@ -73,6 +71,9 @@ func getStageAndBazaar(pkgType string) (result StageBazaarResult) {
return
}
result = v.(StageBazaarResult)
+ if showError && !result.Online {
+ util.PushErrMsg(util.Langs[util.Lang][24], 5000)
+ }
return
}
@@ -142,9 +143,6 @@ func isBazaarOnline() bool {
func isBazaarOnline0() (ret bool) {
// Improve marketplace loading when offline https://github.com/siyuan-note/siyuan/issues/12050
ret = util.IsOnline(util.BazaarOSSServer+"/204", true, 3000)
- if !ret {
- util.PushErrMsg(util.Langs[util.Lang][24], 5000)
- }
return
}
diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.go
index 3a5d53af28..442e506547 100644
--- a/kernel/model/bazaar.go
+++ b/kernel/model/bazaar.go
@@ -39,6 +39,12 @@ type installedPackageInfo struct {
DirName string
}
+// UpdatedPackage 描述本地已安装包及其在线可用更新
+type UpdatedPackage struct {
+ Installed *bazaar.Package `json:"installed"`
+ Available *bazaar.Package `json:"available"`
+}
+
func getPackageInstallPath(pkgType, packageName string) (string, string, error) {
switch pkgType {
case "plugins":
@@ -69,9 +75,10 @@ type batchInstallItem struct {
}
// updatePackages 更新一组集市包;同类型批量更新时,安装后处理只执行一次
-func updatePackages(packages []*bazaar.Package, pkgType string, successCount *int, planned int) {
+func updatePackages(packages []*UpdatedPackage, pkgType string, successCount *int, planned int) {
items := make([]batchInstallItem, 0, len(packages))
- for _, pkg := range packages {
+ for _, updated := range packages {
+ pkg := updated.Available
meta, err := installBazaarPackage(pkgType, pkg.RepoURL, pkg.RepoHash, pkg.Name)
if err != nil {
logging.LogErrorf("update %s [%s] failed: %s", pkgType, pkg.Name, err)
@@ -86,19 +93,22 @@ func updatePackages(packages []*bazaar.Package, pkgType string, successCount *in
}
// filterUpdatableBazaarPackages 过滤出允许更新的集市包
-func filterUpdatableBazaarPackages(packages []*bazaar.Package) []*bazaar.Package {
- updatable := make([]*bazaar.Package, 0, len(packages))
- for _, pkg := range packages {
- if !pkg.DisallowUpdate {
- updatable = append(updatable, pkg)
+func filterUpdatableBazaarPackages(packages []*UpdatedPackage) []*UpdatedPackage {
+ updatable := make([]*UpdatedPackage, 0, len(packages))
+ for _, updated := range packages {
+ if updated.Available != nil && !updated.Available.DisallowUpdate {
+ updatable = append(updatable, updated)
}
}
return updatable
}
// BatchUpdatePackages 更新所有集市包
-func BatchUpdatePackages(frontend string) {
- plugins, widgets, icons, themes, templates := GetUpdatedPackages(frontend)
+func BatchUpdatePackages(frontend string) error {
+ plugins, widgets, icons, themes, templates, err := GetUpdatedPackages(frontend)
+ if err != nil {
+ return err
+ }
plugins = filterUpdatableBazaarPackages(plugins)
widgets = filterUpdatableBazaarPackages(widgets)
icons = filterUpdatableBazaarPackages(icons)
@@ -107,7 +117,7 @@ func BatchUpdatePackages(frontend string) {
planned := len(plugins) + len(widgets) + len(icons) + len(themes) + len(templates)
if 1 > planned {
- return
+ return nil
}
defer util.PushClearProgress()
@@ -121,43 +131,68 @@ func BatchUpdatePackages(frontend string) {
if 0 < successCount {
util.PushMsg(fmt.Sprintf(Conf.language(237), successCount), 5000)
}
+ return nil
}
// GetUpdatedPackages 获取所有类型集市包的更新列表
//
// - frontend 仅用于插件环境兼容性判断
-func GetUpdatedPackages(frontend string) (plugins, widgets, icons, themes, templates []*bazaar.Package) {
+func GetUpdatedPackages(frontend string) (plugins, widgets, icons, themes, templates []*UpdatedPackage, err error) {
wg := &sync.WaitGroup{}
+ errs := make([]error, 5)
wg.Go(func() {
- plugins = getUpdatedPackages("plugins", frontend)
+ plugins, errs[0] = getUpdatedPackages("plugins", frontend)
})
wg.Go(func() {
- themes = getUpdatedPackages("themes", "")
+ themes, errs[1] = getUpdatedPackages("themes", "")
})
wg.Go(func() {
- icons = getUpdatedPackages("icons", "")
+ icons, errs[2] = getUpdatedPackages("icons", "")
})
wg.Go(func() {
- templates = getUpdatedPackages("templates", "")
+ templates, errs[3] = getUpdatedPackages("templates", "")
})
wg.Go(func() {
- widgets = getUpdatedPackages("widgets", "")
+ widgets, errs[4] = getUpdatedPackages("widgets", "")
})
wg.Wait()
+ err = errors.Join(errs...)
return
}
// getUpdatedPackages 获取单个类型集市包的更新列表
-func getUpdatedPackages(pkgType, frontend string) (updatedPackages []*bazaar.Package) {
+func getUpdatedPackages(pkgType, frontend string) (updatedPackages []*UpdatedPackage, err error) {
installedPackages := GetInstalledPackages(pkgType, frontend, "")
- updatedPackages = []*bazaar.Package{} // 确保返回空切片而非 nil
- for _, pkg := range installedPackages {
- if !pkg.Outdated {
+ updatedPackages = []*UpdatedPackage{}
+ if len(installedPackages) == 0 {
+ return
+ }
+
+ bazaarPackagesMap, err := bazaar.GetBazaarPackagesMap(pkgType, frontend)
+ if err != nil {
+ return
+ }
+ updatedPackages = buildUpdatedPackages(installedPackages, bazaarPackagesMap)
+ return
+}
+
+func buildUpdatedPackages(installedPackages []*bazaar.Package, bazaarPackagesMap map[string]*bazaar.Package) (updatedPackages []*UpdatedPackage) {
+ updatedPackages = []*UpdatedPackage{}
+ for _, installed := range installedPackages {
+ online := bazaarPackagesMap[installed.Name]
+ if online == nil || 0 <= semver.Compare("v"+installed.Version, "v"+online.Version) {
continue
}
- updatedPackages = append(updatedPackages, pkg)
+ available := *online
+ available.Installed = true
+ available.Outdated = true
+ available.Current = installed.Current
+ updatedPackages = append(updatedPackages, &UpdatedPackage{
+ Installed: installed,
+ Available: &available,
+ })
}
return
}
@@ -250,14 +285,12 @@ func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages
return
}
- bazaarPackagesMap := bazaar.GetBazaarPackagesMap(pkgType, frontend)
-
for _, info := range installedInfos {
pkg := info.Pkg
installPath := filepath.Join(basePath, info.DirName)
baseURLPath := baseURLPathPrefix + info.DirName + "/"
// 设置本地集市包的通用元数据
- if !bazaar.SetInstalledPackageMetadata(pkg, installPath, baseURLPath, pkgType, frontend, bazaarPackagesMap) {
+ if !bazaar.SetInstalledPackageMetadata(pkg, installPath, baseURLPath, pkgType) {
continue
}
installedPackages = append(installedPackages, pkg)
@@ -275,11 +308,6 @@ func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages
case "plugins":
installedIncompatible := bazaar.IsIncompatiblePlugin(pkg, frontend)
pkg.InstalledIncompatible = &installedIncompatible
- var bazaarIncompatible bool
- if onlinePkg := bazaarPackagesMap[pkg.Name]; nil != onlinePkg {
- bazaarIncompatible = bazaar.IsIncompatiblePlugin(onlinePkg, frontend)
- }
- pkg.BazaarIncompatible = &bazaarIncompatible
petal := getPetalByName(pkg.Name, petals)
if nil != petal {
enabled := petal.Enabled
@@ -294,6 +322,23 @@ func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages
return
}
+// GetInstalledPackageSize 获取本地集市包的安装大小
+func GetInstalledPackageSize(pkgType, packageName string) (size int64, hSize string, err error) {
+ installedInfos, basePath, _, err := GetInstalledPackageInfos(pkgType)
+ if err != nil {
+ return
+ }
+ for _, info := range installedInfos {
+ if info.Pkg.Name != packageName {
+ continue
+ }
+ installPath := filepath.Join(basePath, info.DirName)
+ return bazaar.GetInstalledPackageSize(pkgType, packageName, installPath)
+ }
+ err = errors.New("installed package not found")
+ return
+}
+
// GetBazaarPackages 获取在线集市包列表
func GetBazaarPackages(pkgType, frontend, keyword string) (bazaarPackages []*bazaar.Package) {
bazaarPackages = bazaar.GetBazaarPackages(pkgType, frontend)
@@ -414,6 +459,27 @@ func InstallBazaarPackage(pkgType, repoURL, repoHash, packageName string, themeM
return nil
}
+// UpdateBazaarPackage 使用在线集市数据更新本地集市包
+func UpdateBazaarPackage(pkgType, packageName, frontend string) error {
+ if _, _, err := getPackageInstallPath(pkgType, packageName); err != nil {
+ return err
+ }
+ updatedPackages, err := getUpdatedPackages(pkgType, frontend)
+ if err != nil {
+ return err
+ }
+ for _, updated := range updatedPackages {
+ if updated.Installed == nil || updated.Available == nil || updated.Installed.Name != packageName {
+ continue
+ }
+ if updated.Available.DisallowUpdate {
+ return errors.New("marketplace package update is not allowed")
+ }
+ return InstallBazaarPackage(pkgType, updated.Available.RepoURL, updated.Available.RepoHash, packageName, 0)
+ }
+ return errors.New("marketplace package update not found")
+}
+
func UninstallPackage(pkgType, packageName string) error {
installPath, _, err := getPackageInstallPath(pkgType, packageName)
if err != nil {
@@ -427,6 +493,7 @@ func UninstallPackage(pkgType, packageName string) error {
// 删除集市包的持久化信息
bazaar.RemovePackageInfo(pkgType, packageName)
+ bazaar.RemoveInstalledPackageSizeCache(pkgType, packageName)
switch pkgType {
case "plugins":
diff --git a/kernel/model/bazaar_test.go b/kernel/model/bazaar_test.go
new file mode 100644
index 0000000000..3a5350aaca
--- /dev/null
+++ b/kernel/model/bazaar_test.go
@@ -0,0 +1,90 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/bazaar"
+)
+
+func TestBuildUpdatedPackagesKeepsInstalledAndAvailableMetadataSeparate(t *testing.T) {
+ installed := &bazaar.Package{
+ Name: "example",
+ Version: "1.0.0",
+ URL: "https://github.com/old-owner/example",
+ RepoURL: "https://github.com/old-owner/example",
+ PreferredName: "Installed name",
+ IconURL: "/plugins/example/icon.png",
+ Current: true,
+ }
+ online := &bazaar.Package{
+ Name: "example",
+ Version: "2.0.0",
+ RepoURL: "https://github.com/new-owner/example",
+ RepoHash: "new-hash",
+ PreferredName: "Available name",
+ IconURL: "https://example.com/icon.png",
+ DisallowUpdate: true,
+ }
+
+ updated := buildUpdatedPackages(
+ []*bazaar.Package{installed},
+ map[string]*bazaar.Package{"example": online},
+ )
+
+ if len(updated) != 1 {
+ t.Fatalf("expected one updated package, got %d", len(updated))
+ }
+ if updated[0].Installed != installed {
+ t.Fatal("expected the installed package to remain unchanged")
+ }
+ if updated[0].Installed.RepoURL != "https://github.com/old-owner/example" {
+ t.Fatalf("expected installed repo URL, got %q", updated[0].Installed.RepoURL)
+ }
+ if updated[0].Available == online {
+ t.Fatal("expected a copy of the available package")
+ }
+ if updated[0].Available.RepoURL != "https://github.com/new-owner/example" ||
+ updated[0].Available.RepoHash != "new-hash" {
+ t.Fatalf("expected online download metadata, got %q@%q", updated[0].Available.RepoURL, updated[0].Available.RepoHash)
+ }
+ if !updated[0].Available.DisallowUpdate {
+ t.Fatal("expected the available package update restriction to remain unchanged")
+ }
+ if !updated[0].Available.Installed || !updated[0].Available.Outdated || !updated[0].Available.Current {
+ t.Fatal("expected available package state to describe an installed update")
+ }
+ if online.Installed || online.Outdated || online.Current {
+ t.Fatal("expected the online package cache entry to remain unchanged")
+ }
+}
+
+func TestBuildUpdatedPackagesIgnoresMissingAndCurrentPackages(t *testing.T) {
+ installedPackages := []*bazaar.Package{
+ {Name: "current", Version: "2.0.0"},
+ {Name: "missing", Version: "1.0.0"},
+ }
+ bazaarPackagesMap := map[string]*bazaar.Package{
+ "current": &bazaar.Package{Name: "current", Version: "2.0.0"},
+ }
+
+ updated := buildUpdatedPackages(installedPackages, bazaarPackagesMap)
+ if len(updated) != 0 {
+ t.Fatalf("expected no updated packages, got %d", len(updated))
+ }
+}