Skip to content

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

:sparkles: Support Stable, Beta, and Alpha update channels https://github.com/siyuan-note/siyuan/issues/18366

Daniel75f98bcca208
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml
index 792afb861f..b6c584f9cb 100644
--- a/.github/workflows/cd.yml
+++ b/.github/workflows/cd.yml
@@ -546,28 +546,110 @@ jobs:
- name: Download all artifacts
uses: actions/download-artifact@v8
+ - name: Prepare Release Assets
+ shell: bash
+ run: |
+ set -euo pipefail
+ VERSION="${{ needs.prepare.outputs.version }}"
+ mkdir -p release-assets
+ cp "siyuan-linux/siyuan-${VERSION}-linux.AppImage" release-assets/
+ cp "siyuan-linux/siyuan-${VERSION}-linux.tar.gz" release-assets/
+ cp "siyuan-linux/siyuan-${VERSION}-linux.deb" release-assets/
+ cp "siyuan-linux/siyuan-${VERSION}-linux.rpm" release-assets/
+ cp "siyuan-mac.dmg/siyuan-${VERSION}-mac.dmg" release-assets/
+ cp "siyuan-mac-arm64.dmg/siyuan-${VERSION}-mac-arm64.dmg" release-assets/
+ cp "siyuan-win.exe/siyuan-${VERSION}-win.exe" release-assets/
+ cp "siyuan-android/siyuan-${VERSION}.apk" release-assets/
+
+ EXPECTED_ASSETS=(
+ "siyuan-${VERSION}-linux.AppImage"
+ "siyuan-${VERSION}-linux.tar.gz"
+ "siyuan-${VERSION}-linux.deb"
+ "siyuan-${VERSION}-linux.rpm"
+ "siyuan-${VERSION}-mac.dmg"
+ "siyuan-${VERSION}-mac-arm64.dmg"
+ "siyuan-${VERSION}-win.exe"
+ "siyuan-${VERSION}.apk"
+ )
+ for asset in "${EXPECTED_ASSETS[@]}"; do
+ test -s "release-assets/${asset}"
+ done
+ (
+ cd release-assets
+ sha256sum "${EXPECTED_ASSETS[@]}" > SHA256SUMS.txt
+ sha256sum --check SHA256SUMS.txt
+ )
+
- name: Create Release
uses: ncipollo/release-action@v1
with:
name: ${{ needs.prepare.outputs.release_title }}
- tag: ${{ github.ref }}
+ tag: ${{ github.ref_name }}
body: ${{ needs.prepare.outputs.release_body }}
- draft: false
+ draft: true
prerelease: true
+ allowUpdates: true
+ omitDraftDuringUpdate: true
token: ${{ secrets.GITHUB_TOKEN }}
+ - name: Verify Release Is Draft
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ GH_REPO: ${{ github.repository }}
+ run: |
+ test "$(gh release view "${{ github.ref_name }}" --json isDraft --jq '.isDraft')" = "true"
+
- name: Upload Release Assets
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
run: |
- VERSION=${{ needs.prepare.outputs.version }}
- gh release upload ${{ github.ref_name }} \
- "siyuan-linux/siyuan-${VERSION}-linux.AppImage#siyuan-${VERSION}-linux.AppImage" \
- "siyuan-linux/siyuan-${VERSION}-linux.tar.gz#siyuan-${VERSION}-linux.tar.gz" \
- "siyuan-linux/siyuan-${VERSION}-linux.deb#siyuan-${VERSION}-linux.deb" \
- "siyuan-linux/siyuan-${VERSION}-linux.rpm#siyuan-${VERSION}-linux.rpm" \
- "siyuan-mac.dmg/siyuan-${VERSION}-mac.dmg#siyuan-${VERSION}-mac.dmg" \
- "siyuan-mac-arm64.dmg/siyuan-${VERSION}-mac-arm64.dmg#siyuan-${VERSION}-mac-arm64.dmg" \
- "siyuan-win.exe/siyuan-${VERSION}-win.exe#siyuan-${VERSION}-win.exe" \
- "siyuan-android/siyuan-${VERSION}.apk#siyuan-${VERSION}.apk"
+ gh release upload "${{ github.ref_name }}" release-assets/* --clobber
+
+ - name: Validate and Publish Release
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ GH_REPO: ${{ github.repository }}
+ run: |
+ set -euo pipefail
+ VERSION="${{ needs.prepare.outputs.version }}"
+ TAG="${{ github.ref_name }}"
+ RELEASE_ID="$(gh api "repos/${GH_REPO}/releases/tags/${TAG}" --jq '.id')"
+ EXPECTED_ASSETS=(
+ "siyuan-${VERSION}-linux.AppImage"
+ "siyuan-${VERSION}-linux.tar.gz"
+ "siyuan-${VERSION}-linux.deb"
+ "siyuan-${VERSION}-linux.rpm"
+ "siyuan-${VERSION}-mac.dmg"
+ "siyuan-${VERSION}-mac-arm64.dmg"
+ "siyuan-${VERSION}-win.exe"
+ "siyuan-${VERSION}.apk"
+ "SHA256SUMS.txt"
+ )
+ declare -A EXPECTED_DIGESTS
+ for asset in "${EXPECTED_ASSETS[@]}"; do
+ EXPECTED_DIGESTS["${asset}"]="sha256:$(sha256sum "release-assets/${asset}" | awk '{print $1}')"
+ done
+
+ for attempt in {1..12}; do
+ ASSETS="$(gh api -H "X-GitHub-Api-Version: 2022-11-28" \
+ "repos/${GH_REPO}/releases/${RELEASE_ID}/assets?per_page=100")"
+ READY=true
+ for asset in "${EXPECTED_ASSETS[@]}"; do
+ REMOTE_DIGEST="$(jq -r --arg name "${asset}" \
+ '.[] | select(.name == $name and .state == "uploaded") | .digest // empty' <<< "${ASSETS}")"
+ if [ "${REMOTE_DIGEST}" != "${EXPECTED_DIGESTS[$asset]}" ]; then
+ READY=false
+ break
+ fi
+ done
+ if [ "${READY}" = true ]; then
+ gh release edit "${TAG}" --draft=false --prerelease
+ exit 0
+ fi
+ sleep 5
+ done
+
+ echo "Release assets or SHA-256 digests are incomplete"
+ exit 1
diff --git a/README.ja.md b/README.ja.md
index 70855612e3..a78ead10bf 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -45,7 +45,7 @@
- [Docker ホスティング](#docker-ホスティング)
- [Unraid ホスティング](#unraid-ホスティング)
- [TrueNAS ホスティング](#truenas-ホスティング)
- - [インサイダープレビュー](#インサイダープレビュー)
+ - [テストチャンネル](#テストチャンネル)
- [⌨️ コマンドラインインターフェース](#-コマンドラインインターフェース)
- [🏘️ コミュニティ](#️-コミュニティ)
- [🛠️ 開発ガイド](#️-開発ガイド)
@@ -353,9 +353,9 @@ services:
</details>
-### インサイダープレビュー
+### テストチャンネル
-主要な更新前にインサイダープレビューをリリースします。詳細は[https://github.com/siyuan-note/insider](https://github.com/siyuan-note/insider)をご覧ください。
+プレリリースを受信するには、`設定 > 情報 > 更新チャンネル`で Beta または Alpha を選択します。Beta チャンネルでは正式版、RC、Beta 版を受信し、Alpha チャンネルではすべての版を受信します。テストチャンネルの利用には GitHub へのアクセスが必要です。
## ⌨️ コマンドラインインターフェース
diff --git a/README.md b/README.md
index 655e9be9f8..b3d9a82bb9 100644
--- a/README.md
+++ b/README.md
@@ -45,7 +45,7 @@
- [Docker Hosting](#docker-hosting)
- [Unraid Hosting](#unraid-hosting)
- [TrueNAS Hosting](#truenas-hosting)
- - [Insider Preview](#insider-preview)
+ - [Test Channels](#test-channels)
- [⌨️ Command-line Interface](#-command-line-interface)
- [🏘️ Community](#️-community)
- [🛠️ Development Guide](#️-development-guide)
@@ -349,9 +349,9 @@ services:
</details>
-### Insider Preview
+### Test Channels
-We release insider preview before major updates, please visit [https://github.com/siyuan-note/insider](https://github.com/siyuan-note/insider).
+Select Beta or Alpha in `Settings > About > Update channel` to receive prereleases. Beta includes stable, RC, and Beta releases; Alpha includes all releases. Test channels require access to GitHub.
## ⌨️ Command-line Interface
diff --git a/README.tr.md b/README.tr.md
index da43107c2a..708f29f1a8 100644
--- a/README.tr.md
+++ b/README.tr.md
@@ -45,7 +45,7 @@
- [Docker Barındırma](#docker-barındırma)
- [Unraid Barındırma](#unraid-barındırma)
- [TrueNAS Barındırma](#truenas-barındırma)
- - [Erken Önizleme (Insider Preview)](#erken-önizleme-insider-preview)
+ - [Test Kanalları](#test-kanalları)
- [⌨️ Komut Satırı Arayüzü](#-komut-satırı-arayüzü)
- [🏘️ Topluluk](#️-topluluk)
- [🛠️ Geliştirme Rehberi](#️-geliştirme-rehberi)
@@ -354,9 +354,9 @@ services:
</details>
-### Erken Önizleme (Insider Preview)
+### Test Kanalları
-Büyük güncellemelerden önce erken erişim (Insider Preview) sürümlerini yayınlıyoruz. Lütfen [https://github.com/siyuan-note/insider](https://github.com/siyuan-note/insider) adresini ziyaret edin.
+Ön sürümleri almak için `Ayarlar > Hakkında > Güncelleme kanalı` altında Beta veya Alpha seçeneğini belirleyin. Beta kanalı kararlı, RC ve Beta sürümlerini; Alpha kanalı ise tüm sürümleri alır. Test kanalları GitHub erişimi gerektirir.
## ⌨️ Komut Satırı Arayüzü
diff --git a/README.zh-CN.md b/README.zh-CN.md
index ebb0fffc16..1c926288ac 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -48,7 +48,7 @@
- [宝塔面板部署](#宝塔面板部署)
- [小皮面板部署](#小皮面板部署)
- [1Panel 面板部署](#1Panel-面板部署)
- - [内部预览版](#内部预览版)
+ - [测试通道](#测试通道)
- [⌨️ 命令行接口](#-命令行接口)
- [🏘️ 社区](#️-社区)
- [🛠️ 开发指南](#️-开发指南)
@@ -450,9 +450,9 @@ services:
</details>
-### 内部预览版
+### 测试通道
-我们会在有重大更新前发布内部预览版,请访问 [https://github.com/siyuan-note/insider](https://github.com/siyuan-note/insider)。
+可在`设置 > 关于 > 更新通道`中选择 Beta 或 Alpha 以接收预发布版本。Beta 通道接收正式版、RC 和 Beta,Alpha 通道接收全部版本。测试通道需要能够访问 GitHub。
## ⌨️ 命令行接口
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index acb4ca1f1e..0d3495ac11 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "قناة التحديث",
+ "updateChannelTip": "تتلقى قناة Beta الإصدارات المستقرة وRC وBeta، بينما تتلقى قناة Alpha جميع الإصدارات. تتطلب قنوات الاختبار إمكانية الوصول إلى GitHub.",
+ "updateChannelStable": "مستقر",
+ "updateChannelBeta": "بيتا",
+ "updateChannelAlpha": "ألفا",
"noMoreItems": "لا مزيد من العناصر",
"docCreateTemplatePathTip": "مسار قالب المستند الجديد (على سبيل المثال، <code class='fn__code'>document.md</code>؛ اتركه فارغًا لعدم تطبيق قالب؛ يجب وضع الملف ضمن workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "مسار قالب المستند الجديد (على سبيل المثال، <code class='fn__code'>document.md</code>؛ اتركه فارغًا لاستخدام الإعداد العام؛ يجب وضع الملف ضمن workspace/data/templates/)",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 96eb7b1c45..f32b573522 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Aktualisierungskanal",
+ "updateChannelTip": "Der Beta-Kanal erhält stabile, RC- und Beta-Versionen; der Alpha-Kanal erhält alle Versionen. Testkanäle erfordern Zugriff auf GitHub.",
+ "updateChannelStable": "Stabil",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Keine weiteren Einträge",
"docCreateTemplatePathTip": "Vorlagenpfad für neue Dokumente (zum Beispiel <code class='fn__code'>document.md</code>; leer lassen, um keine Vorlage anzuwenden; die Datei muss unter workspace/data/templates/ abgelegt werden)",
"docCreateTemplatePathInheritTip": "Vorlagenpfad für neue Dokumente (zum Beispiel <code class='fn__code'>document.md</code>; leer lassen, um die globale Einstellung zu verwenden; die Datei muss unter workspace/data/templates/ abgelegt werden)",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index c7cd300bcf..6d4ecd1105 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Update channel",
+ "updateChannelTip": "Beta receives stable, RC, and Beta releases; Alpha receives all releases. Test channels require access to GitHub.",
+ "updateChannelStable": "Stable",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "No more items",
"docCreateTemplatePathTip": "New document template path (for example, <code class='fn__code'>document.md</code>; leave blank to apply no template; the file needs to be placed under workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "New document template path (for example, <code class='fn__code'>document.md</code>; leave blank to use the global setting; the file needs to be placed under workspace/data/templates/)",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index f448b85655..af13dfa473 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Canal de actualización",
+ "updateChannelTip": "El canal Beta recibe versiones estables, RC y Beta; el canal Alpha recibe todas las versiones. Los canales de prueba requieren acceso a GitHub.",
+ "updateChannelStable": "Estable",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "No hay más elementos",
"docCreateTemplatePathTip": "Ruta de la plantilla para documentos nuevos (por ejemplo, <code class='fn__code'>document.md</code>; déjela en blanco para no aplicar ninguna plantilla; el archivo debe colocarse en workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Ruta de la plantilla para documentos nuevos (por ejemplo, <code class='fn__code'>document.md</code>; déjela en blanco para usar la configuración global; el archivo debe colocarse en workspace/data/templates/)",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 41af31e37a..c62a26fdfb 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Canal de mise à jour",
+ "updateChannelTip": "Le canal Beta reçoit les versions stables, RC et bêta ; le canal Alpha reçoit toutes les versions. Les canaux de test nécessitent un accès à GitHub.",
+ "updateChannelStable": "Stable",
+ "updateChannelBeta": "Bêta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Aucun autre élément",
"docCreateTemplatePathTip": "Chemin du modèle des nouveaux documents (par exemple, <code class='fn__code'>document.md</code> ; laisser vide pour ne pas appliquer de modèle ; le fichier doit être placé dans workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Chemin du modèle des nouveaux documents (par exemple, <code class='fn__code'>document.md</code> ; laisser vide pour utiliser le réglage global ; le fichier doit être placé dans workspace/data/templates/)",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 878dc90fff..0369a8c344 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "ערוץ עדכונים",
+ "updateChannelTip": "ערוץ Beta מקבל גרסאות יציבות, RC ו-Beta; ערוץ Alpha מקבל את כל הגרסאות. ערוצי הבדיקה דורשים גישה ל-GitHub.",
+ "updateChannelStable": "יציב",
+ "updateChannelBeta": "בטא",
+ "updateChannelAlpha": "אלפא",
"noMoreItems": "אין פריטים נוספים",
"docCreateTemplatePathTip": "נתיב תבנית למסמך חדש (לדוגמה, <code class='fn__code'>document.md</code>; יש להשאיר ריק כדי לא להחיל תבנית; הקובץ צריך להימצא תחת workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "נתיב תבנית למסמך חדש (לדוגמה, <code class='fn__code'>document.md</code>; יש להשאיר ריק כדי להשתמש בהגדרה הכללית; הקובץ צריך להימצא תחת workspace/data/templates/)",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index a189ecab03..d8cc863b18 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "अपडेट चैनल",
+ "updateChannelTip": "Beta चैनल को स्थिर, RC और Beta रिलीज़ मिलते हैं; Alpha चैनल को सभी रिलीज़ मिलते हैं। परीक्षण चैनलों के लिए GitHub तक पहुंच आवश्यक है।",
+ "updateChannelStable": "स्थिर",
+ "updateChannelBeta": "बीटा",
+ "updateChannelAlpha": "अल्फ़ा",
"noMoreItems": "कोई और आइटम नहीं",
"docCreateTemplatePathTip": "नए दस्तावेज़ का टेम्पलेट पथ (उदाहरण के लिए, <code class='fn__code'>document.md</code>; टेम्पलेट लागू न करने के लिए खाली छोड़ें; फ़ाइल को workspace/data/templates/ में रखना आवश्यक है)",
"docCreateTemplatePathInheritTip": "नए दस्तावेज़ का टेम्पलेट पथ (उदाहरण के लिए, <code class='fn__code'>document.md</code>; वैश्विक सेटिंग का उपयोग करने के लिए खाली छोड़ें; फ़ाइल को workspace/data/templates/ में रखना आवश्यक है)",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 4968c88b6c..79cff5c1fd 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Saluran pembaruan",
+ "updateChannelTip": "Kanal Beta menerima rilis stabil, RC, dan Beta; kanal Alpha menerima semua rilis. Kanal pengujian memerlukan akses ke GitHub.",
+ "updateChannelStable": "Stabil",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Tidak ada item lagi",
"docCreateTemplatePathTip": "Jalur templat dokumen baru (misalnya, <code class='fn__code'>document.md</code>; biarkan kosong agar tidak menerapkan templat; file harus ditempatkan di workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Jalur templat dokumen baru (misalnya, <code class='fn__code'>document.md</code>; biarkan kosong untuk menggunakan pengaturan global; file harus ditempatkan di workspace/data/templates/)",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index d8db91595e..4c456c1181 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Canale di aggiornamento",
+ "updateChannelTip": "Il canale Beta riceve le versioni stabili, RC e Beta; il canale Alpha riceve tutte le versioni. I canali di test richiedono l'accesso a GitHub.",
+ "updateChannelStable": "Stabile",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Nessun altro elemento",
"docCreateTemplatePathTip": "Percorso del modello per i nuovi documenti (ad esempio, <code class='fn__code'>document.md</code>; lascia vuoto per non applicare alcun modello; il file deve trovarsi in workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Percorso del modello per i nuovi documenti (ad esempio, <code class='fn__code'>document.md</code>; lascia vuoto per usare l'impostazione globale; il file deve trovarsi in workspace/data/templates/)",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index b690345bf2..3c86fdef32 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "更新チャンネル",
+ "updateChannelTip": "Beta チャンネルでは正式版、RC、Beta 版を受信し、Alpha チャンネルではすべての版を受信します。テストチャンネルの利用には GitHub へのアクセスが必要です。",
+ "updateChannelStable": "正式版",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "これ以上項目はありません",
"docCreateTemplatePathTip": "新規文書のテンプレートパス(例:<code class='fn__code'>document.md</code>。テンプレートを適用しない場合は空欄にします。ファイルは workspace/data/templates/ に配置してください)",
"docCreateTemplatePathInheritTip": "新規文書のテンプレートパス(例:<code class='fn__code'>document.md</code>。グローバル設定を使用する場合は空欄にします。ファイルは workspace/data/templates/ に配置してください)",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 41485c3017..69910b9aeb 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "업데이트 채널",
+ "updateChannelTip": "Beta 채널은 정식, RC 및 Beta 릴리스를 받고 Alpha 채널은 모든 릴리스를 받습니다. 테스트 채널을 사용하려면 GitHub에 접근할 수 있어야 합니다.",
+ "updateChannelStable": "정식",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "더 이상 항목이 없습니다",
"docCreateTemplatePathTip": "새 문서 템플릿 경로(예: <code class='fn__code'>document.md</code>, 템플릿을 적용하지 않으려면 비워 두세요. 파일은 workspace/data/templates/ 아래에 있어야 합니다)",
"docCreateTemplatePathInheritTip": "새 문서 템플릿 경로(예: <code class='fn__code'>document.md</code>, 전역 설정을 사용하려면 비워 두세요. 파일은 workspace/data/templates/ 아래에 있어야 합니다)",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index e375025c5d..c33470116d 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Updatekanaal",
+ "updateChannelTip": "Het Beta-kanaal ontvangt stabiele, RC- en Beta-versies; het Alpha-kanaal ontvangt alle versies. Testkanalen vereisen toegang tot GitHub.",
+ "updateChannelStable": "Stabiel",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Geen items meer",
"docCreateTemplatePathTip": "Sjabloonpad voor nieuwe documenten (bijvoorbeeld <code class='fn__code'>document.md</code>; laat leeg om geen sjabloon toe te passen; het bestand moet in workspace/data/templates/ worden geplaatst)",
"docCreateTemplatePathInheritTip": "Sjabloonpad voor nieuwe documenten (bijvoorbeeld <code class='fn__code'>document.md</code>; laat leeg om de algemene instelling te gebruiken; het bestand moet in workspace/data/templates/ worden geplaatst)",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 56290bf8e4..d82374d4ac 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Kanał aktualizacji",
+ "updateChannelTip": "Kanał Beta otrzymuje wydania stabilne, RC i Beta, a kanał Alpha wszystkie wydania. Kanały testowe wymagają dostępu do GitHub.",
+ "updateChannelStable": "Stabilny",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Brak kolejnych elementów",
"docCreateTemplatePathTip": "Ścieżka szablonu nowego dokumentu (na przykład <code class='fn__code'>document.md</code>; pozostaw puste, aby nie stosować szablonu; plik musi znajdować się w workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Ścieżka szablonu nowego dokumentu (na przykład <code class='fn__code'>document.md</code>; pozostaw puste, aby użyć ustawienia globalnego; plik musi znajdować się w workspace/data/templates/)",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index b041cd66f0..cbbeb97b32 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Canal de atualização",
+ "updateChannelTip": "O canal Beta recebe versões estáveis, RC e Beta; o canal Alpha recebe todas as versões. Os canais de teste exigem acesso ao GitHub.",
+ "updateChannelStable": "Estável",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Não há mais itens",
"docCreateTemplatePathTip": "Caminho do modelo de novos documentos (por exemplo, <code class='fn__code'>document.md</code>; deixe em branco para não aplicar um modelo; o arquivo deve ser colocado em workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Caminho do modelo de novos documentos (por exemplo, <code class='fn__code'>document.md</code>; deixe em branco para usar a configuração global; o arquivo deve ser colocado em workspace/data/templates/)",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 89af1c2d28..2634504d23 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Канал обновлений",
+ "updateChannelTip": "Канал Beta получает стабильные, RC- и Beta-версии, а канал Alpha — все версии. Для тестовых каналов требуется доступ к GitHub.",
+ "updateChannelStable": "Стабильный",
+ "updateChannelBeta": "Бета",
+ "updateChannelAlpha": "Альфа",
"noMoreItems": "Больше нет элементов",
"docCreateTemplatePathTip": "Путь к шаблону нового документа (например, <code class='fn__code'>document.md</code>; оставьте пустым, чтобы не применять шаблон; файл должен находиться в workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Путь к шаблону нового документа (например, <code class='fn__code'>document.md</code>; оставьте пустым, чтобы использовать глобальную настройку; файл должен находиться в workspace/data/templates/)",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 590f9af54d..5c2f3a837f 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Aktualizačný kanál",
+ "updateChannelTip": "Kanál Beta prijíma stabilné vydania, RC a Beta; kanál Alpha prijíma všetky vydania. Testovacie kanály vyžadujú prístup ku GitHubu.",
+ "updateChannelStable": "Stabilný",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Žiadne ďalšie položky",
"docCreateTemplatePathTip": "Cesta k šablóne nového dokumentu (napríklad <code class='fn__code'>document.md</code>; ak nechcete použiť šablónu, nechajte pole prázdne; súbor musí byť umiestnený v workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Cesta k šablóne nového dokumentu (napríklad <code class='fn__code'>document.md</code>; ak chcete použiť globálne nastavenie, nechajte pole prázdne; súbor musí byť umiestnený v workspace/data/templates/)",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index b7d3e41abb..87a7e52ba4 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "ช่องทางการอัปเดต",
+ "updateChannelTip": "ช่อง Beta จะได้รับรุ่นเสถียร รุ่น RC และรุ่น Beta ส่วนช่อง Alpha จะได้รับทุกรุ่น ช่องทดสอบจำเป็นต้องเข้าถึง GitHub",
+ "updateChannelStable": "เสถียร",
+ "updateChannelBeta": "เบต้า",
+ "updateChannelAlpha": "อัลฟ่า",
"noMoreItems": "ไม่มีรายการเพิ่มเติม",
"docCreateTemplatePathTip": "เส้นทางเทมเพลตเอกสารใหม่ (เช่น <code class='fn__code'>document.md</code> เว้นว่างไว้หากไม่ต้องการใช้เทมเพลต และต้องวางไฟล์ไว้ใน workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "เส้นทางเทมเพลตเอกสารใหม่ (เช่น <code class='fn__code'>document.md</code> เว้นว่างไว้เพื่อใช้การตั้งค่าส่วนกลาง และต้องวางไฟล์ไว้ใน workspace/data/templates/)",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 3f88b43ff4..23eeb6faf5 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Güncelleme kanalı",
+ "updateChannelTip": "Beta kanalı kararlı, RC ve Beta sürümlerini; Alpha kanalı ise tüm sürümleri alır. Test kanalları GitHub erişimi gerektirir.",
+ "updateChannelStable": "Kararlı",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "Başka öğe yok",
"docCreateTemplatePathTip": "Yeni belge şablonu yolu (örneğin <code class='fn__code'>document.md</code>; şablon uygulamamak için boş bırakın; dosya workspace/data/templates/ altında bulunmalıdır)",
"docCreateTemplatePathInheritTip": "Yeni belge şablonu yolu (örneğin <code class='fn__code'>document.md</code>; genel ayarı kullanmak için boş bırakın; dosya workspace/data/templates/ altında bulunmalıdır)",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 9b365dc6cb..9a34a32f16 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "Канал оновлень",
+ "updateChannelTip": "Канал Beta отримує стабільні, RC- та Beta-версії, а канал Alpha — усі версії. Для тестових каналів потрібен доступ до GitHub.",
+ "updateChannelStable": "Стабільний",
+ "updateChannelBeta": "Бета",
+ "updateChannelAlpha": "Альфа",
"noMoreItems": "Більше немає елементів",
"docCreateTemplatePathTip": "Шлях до шаблону нового документа (наприклад, <code class='fn__code'>document.md</code>; залиште порожнім, щоб не застосовувати шаблон; файл має бути розміщений у workspace/data/templates/)",
"docCreateTemplatePathInheritTip": "Шлях до шаблону нового документа (наприклад, <code class='fn__code'>document.md</code>; залиште порожнім, щоб використовувати глобальне налаштування; файл має бути розміщений у workspace/data/templates/)",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index d9feaa4118..f3469937b6 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "更新通道",
+ "updateChannelTip": "Beta 通道接收正式版、RC 和 Beta,Alpha 通道接收全部版本。测试通道需要能够访问 GitHub。",
+ "updateChannelStable": "正式版",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "无更多条目",
"docCreateTemplatePathTip": "新建文档模板路径(例如 <code class='fn__code'>document.md</code>,留空时不应用模板,需要将该文件放置于工作空间/data/templates/ 下)",
"docCreateTemplatePathInheritTip": "新建文档模板路径(例如 <code class='fn__code'>document.md</code>,留空时使用全局设置,需要将该文件放置于工作空间/data/templates/ 下)",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 5ea3cc2d9b..5efd6d4069 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,9 @@
{
+ "updateChannel": "更新通道",
+ "updateChannelTip": "Beta 通道接收正式版、RC 和 Beta,Alpha 通道接收所有版本。測試通道需要能夠存取 GitHub。",
+ "updateChannelStable": "正式版",
+ "updateChannelBeta": "Beta",
+ "updateChannelAlpha": "Alpha",
"noMoreItems": "無更多條目",
"docCreateTemplatePathTip": "新建文件範本路徑(例如 <code class='fn__code'>document.md</code>,留空時不套用範本,需要將該檔放置於工作空間/data/templates/ 下)",
"docCreateTemplatePathInheritTip": "新建文件範本路徑(例如 <code class='fn__code'>document.md</code>,留空時使用全域設定,需要將該檔放置於工作空間/data/templates/ 下)",
diff --git a/app/src/config/tabs/aboutTab.ts b/app/src/config/tabs/aboutTab.ts
index c8afb265ae..aee4faf3c7 100644
--- a/app/src/config/tabs/aboutTab.ts
+++ b/app/src/config/tabs/aboutTab.ts
@@ -15,10 +15,24 @@ const registerAboutVersionGroup = (tab: SettingTabBuilder) => {
window.siyuan.languages.downloadLatestVer,
window.siyuan.languages.isMsStoreVerTip,
window.siyuan.languages.checkUpdate,
+ window.siyuan.languages.updateChannel,
+ window.siyuan.languages.updateChannelTip,
],
html: genAboutVersionHtml,
afterMount: mountAboutVersionSlot,
});
+ if (!window.siyuan.config.system.isMicrosoftStore) {
+ group.select("system.updateChannel", {
+ title: window.siyuan.languages.updateChannel,
+ desc: window.siyuan.languages.updateChannelTip,
+ options: [
+ {value: "stable", label: window.siyuan.languages.updateChannelStable},
+ {value: "beta", label: window.siyuan.languages.updateChannelBeta},
+ {value: "alpha", label: window.siyuan.languages.updateChannelAlpha},
+ ],
+ save: (value) => sendAppSetting("system.updateChannel", value),
+ });
+ }
/// #if !BROWSER
if (!window.siyuan.config.system.isMicrosoftStore && window.siyuan.config.system.container === "std" && window.siyuan.config.system.os !== "linux") {
group.switch("system.downloadInstallPkg", {
@@ -34,14 +48,14 @@ const genAboutVersionHtml = (): string => {
if (window.siyuan.config.system.isMicrosoftStore) {
return `<div class="fn__flex b3-label config-item config-wrap">
<div class="fn__flex-1">
- <div class="config-name">${window.siyuan.languages.currentVer} v${Constants.SIYUAN_VERSION}<span id="isInsider"></span></div>
+ <div class="config-name">${window.siyuan.languages.currentVer} v${Constants.SIYUAN_VERSION}</div>
<div class="b3-label__text">${window.siyuan.languages.isMsStoreVerTip}</div>
</div>
</div>`;
}
return `<div class="fn__flex b3-label config-item config-wrap">
<div class="fn__flex-1">
- <div class="config-name">${window.siyuan.languages.currentVer} v${Constants.SIYUAN_VERSION}<span id="isInsider"></span></div>
+ <div class="config-name">${window.siyuan.languages.currentVer} v${Constants.SIYUAN_VERSION}</div>
<div class="b3-label__text">${window.siyuan.languages.downloadLatestVer}</div>
</div>
<div class="fn__space"></div>
@@ -54,10 +68,6 @@ const genAboutVersionHtml = (): string => {
};
const mountAboutVersionSlot = (root: HTMLElement) => {
- const isInsiderElement = root.querySelector("#isInsider");
- if (window.siyuan.config.system.isInsider && isInsiderElement) {
- isInsiderElement.innerHTML = " <span class='ft__secondary'>Insider Preview</span>";
- }
const updateElement = root.querySelector("#checkUpdateBtn") as HTMLButtonElement | null;
updateElement?.addEventListener("click", () => {
const svgElement = updateElement.querySelector("svg");
diff --git a/app/src/config/tabs/appRuntime.ts b/app/src/config/tabs/appRuntime.ts
index 464ce4edc8..dcc105bcf9 100644
--- a/app/src/config/tabs/appRuntime.ts
+++ b/app/src/config/tabs/appRuntime.ts
@@ -66,6 +66,13 @@ export const sendAppSetting = (controlId: string, value: unknown) => {
});
break;
}
+ case "system.updateChannel": {
+ const updateChannel = value as Config.TUpdateChannel;
+ fetchPost("/api/system/setUpdateChannel", {updateChannel}, () => {
+ window.siyuan.config.system.updateChannel = updateChannel;
+ });
+ break;
+ }
default:
console.warn(`[config] sendAppSetting: unhandled controlId "${controlId}"`);
break;
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index a7626a2ee4..fcf7cdc84c 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -1830,6 +1830,10 @@ declare namespace Config {
* Whether to automatically download the installation package for the new version
*/
downloadInstallPkg: boolean;
+ /**
+ * 更新通道
+ */
+ updateChannel: TUpdateChannel;
/**
* The absolute path of the user's home directory for the current operating system user
*/
@@ -1838,10 +1842,6 @@ declare namespace Config {
* The UUID of the current session
*/
id: string;
- /**
- * Whether the current version is an internal test version
- */
- isInsider: boolean;
/**
* Whether the current version is a Microsoft Store version
*/
@@ -1907,6 +1907,8 @@ declare namespace Config {
*/
export type TSystemContainer = "docker" | "android" | "ios" | "harmony" | "std";
+ export type TUpdateChannel = "stable" | "beta" | "alpha";
+
/**
* SiYuan Network proxy configuration
*/
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 7e03ec1b6e..d35c7dec8e 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -55,6 +55,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/system/importTLSCABundle", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importTLSCABundle)
ginServer.Handle("POST", "/api/system/setAutoLaunch", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAutoLaunch)
ginServer.Handle("POST", "/api/system/setDownloadInstallPkg", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setDownloadInstallPkg)
+ ginServer.Handle("POST", "/api/system/setUpdateChannel", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setUpdateChannel)
ginServer.Handle("POST", "/api/system/setNetworkProxy", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setNetworkProxy)
ginServer.Handle("POST", "/api/system/setWorkspaceDir", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setWorkspaceDir)
ginServer.Handle("POST", "/api/system/getWorkspaces", model.CheckAuth, getWorkspaces)
diff --git a/kernel/api/system.go b/kernel/api/system.go
index fefe97be89..c84048f728 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -346,7 +346,7 @@ func exportConf(c *gin.Context) {
clonedConf.System.OSPlatform = ""
clonedConf.System.Container = ""
clonedConf.System.IsMicrosoftStore = false
- clonedConf.System.IsInsider = false
+ clonedConf.System.UpdateChannel = ""
clonedConf.System.MicrosoftDefenderExcluded = false
}
clonedConf.Sync = nil
@@ -538,6 +538,10 @@ func importConf(c *gin.Context) {
return
}
preserveImportedAISecrets(importedConf.AI, model.Conf.AI)
+ if nil != importedConf.System && nil != model.Conf.System {
+ // 更新通道是应用级全局设置,导入工作空间配置时保持不变。
+ importedConf.System.UpdateChannel = model.Conf.System.UpdateChannel
+ }
model.Conf.FileTree = importedConf.FileTree
model.Conf.Tag = importedConf.Tag
@@ -1096,6 +1100,27 @@ func setDownloadInstallPkg(c *gin.Context) {
model.Conf.Save()
}
+func setUpdateChannel(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ updateChannel, ok := arg["updateChannel"].(string)
+ if !ok {
+ ret.Code = -1
+ ret.Msg = "update channel is invalid"
+ return
+ }
+ if err := model.SetUpdateChannel(updateChannel); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ }
+}
+
func setNetworkProxy(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/conf/system.go b/kernel/conf/system.go
index 95b7aaea7b..d01f5885fb 100644
--- a/kernel/conf/system.go
+++ b/kernel/conf/system.go
@@ -28,7 +28,6 @@ type System struct {
OSPlatform string `json:"osPlatform"`
Container string `json:"container"` // docker, android, ios, harmony, std
IsMicrosoftStore bool `json:"isMicrosoftStore"`
- IsInsider bool `json:"isInsider"`
HomeDir string `json:"homeDir"`
WorkspaceDir string `json:"workspaceDir"`
@@ -40,9 +39,10 @@ type System struct {
NetworkServeTLS bool `json:"networkServeTLS"` // 是否开启 HTTPS 网络伺服
NetworkProxy *NetworkProxy `json:"networkProxy"`
- DownloadInstallPkg bool `json:"downloadInstallPkg"`
- AutoLaunch2 int `json:"autoLaunch2"` // 0:不自动启动,1:自动启动,2:自动启动+隐藏主窗口
- LockScreenMode int `json:"lockScreenMode"` // 0:手动,1:手动+跟随系统 https://github.com/siyuan-note/siyuan/issues/9087
+ DownloadInstallPkg bool `json:"downloadInstallPkg"`
+ UpdateChannel string `json:"updateChannel,omitempty"`
+ AutoLaunch2 int `json:"autoLaunch2"` // 0:不自动启动,1:自动启动,2:自动启动+隐藏主窗口
+ LockScreenMode int `json:"lockScreenMode"` // 0:手动,1:手动+跟随系统 https://github.com/siyuan-note/siyuan/issues/9087
DisabledFeatures []string `json:"disabledFeatures"`
@@ -57,6 +57,12 @@ const (
OnboardingCompleted = "completed"
)
+const (
+ UpdateChannelStable = "stable"
+ UpdateChannelBeta = "beta"
+ UpdateChannelAlpha = "alpha"
+)
+
type Onboarding struct {
State string `json:"state"`
NewUser bool `json:"newUser"`
@@ -72,6 +78,7 @@ func NewSystem() *System {
KernelVersion: util.Ver,
NetworkProxy: &NetworkProxy{},
DownloadInstallPkg: true,
+ UpdateChannel: UpdateChannelStable,
}
}
diff --git a/kernel/model/cloud_service.go b/kernel/model/cloud_service.go
index 5bd67a489f..ae647b3fb2 100644
--- a/kernel/model/cloud_service.go
+++ b/kernel/model/cloud_service.go
@@ -277,7 +277,7 @@ func refreshCheckDownloadInstallPkg() {
defer logging.Recover()
time.Sleep(3 * time.Minute)
- checkDownloadInstallPkg()
+ checkDownloadInstallPkg(true)
}
func refreshAnnouncement() {
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index ac3e990a1b..871d38d652 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -458,8 +458,8 @@ func InitConf() {
}
Conf.System.KernelVersion = util.Ver
- Conf.System.IsInsider = util.IsInsider
}
+ Conf.System.UpdateChannel = loadGlobalUpdateChannel()
if nil == Conf.Onboarding {
Conf.Onboarding = &conf.Onboarding{State: conf.OnboardingCompleted}
}
@@ -1053,6 +1053,8 @@ func (conf *AppConf) Save() {
// safeMode 是纯运行时状态(由 --safe-mode 注入),不随 conf.json 持久化,避免跨启动残留。
if snapshot.System != nil {
snapshot.System.SafeMode = false
+ // 更新通道由用户目录下的全局配置持久化,不写入工作空间配置。
+ snapshot.System.UpdateChannel = ""
}
newData, err := gulu.JSON.MarshalIndentJSON(snapshot, "", " ")
diff --git a/kernel/model/update_channel.go b/kernel/model/update_channel.go
new file mode 100644
index 0000000000..2864868445
--- /dev/null
+++ b/kernel/model/update_channel.go
@@ -0,0 +1,84 @@
+// 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 (
+ "errors"
+ "os"
+ "path/filepath"
+
+ "github.com/88250/gulu"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type globalUpdateConf struct {
+ Channel string `json:"channel"`
+}
+
+func loadGlobalUpdateChannel() string {
+ configPath := globalUpdateConfPath()
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ logging.LogWarnf("read update channel config [%s] failed: %s", configPath, err)
+ }
+ return conf.UpdateChannelStable
+ }
+
+ config := &globalUpdateConf{}
+ if err = gulu.JSON.UnmarshalJSON(data, config); err != nil {
+ logging.LogWarnf("parse update channel config [%s] failed: %s", configPath, err)
+ return conf.UpdateChannelStable
+ }
+ if !isValidUpdateChannel(config.Channel) {
+ logging.LogWarnf("invalid update channel [%s], using stable channel", config.Channel)
+ return conf.UpdateChannelStable
+ }
+ return config.Channel
+}
+
+// SetUpdateChannel 校验并保存应用级更新通道。
+func SetUpdateChannel(channel string) error {
+ if !isValidUpdateChannel(channel) {
+ return errors.New("update channel is invalid")
+ }
+
+ data, err := gulu.JSON.MarshalIndentJSON(&globalUpdateConf{Channel: channel}, "", " ")
+ if err != nil {
+ return err
+ }
+ configPath := globalUpdateConfPath()
+ if err = os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
+ return err
+ }
+ if err = filelock.WriteFile(configPath, data); err != nil {
+ return err
+ }
+ Conf.System.UpdateChannel = channel
+ return nil
+}
+
+func globalUpdateConfPath() string {
+ return filepath.Join(util.HomeDir, ".config", "siyuan", "update.json")
+}
+
+func isValidUpdateChannel(channel string) bool {
+ return conf.UpdateChannelStable == channel || conf.UpdateChannelBeta == channel || conf.UpdateChannelAlpha == channel
+}
diff --git a/kernel/model/updater.go b/kernel/model/updater.go
index 4333fd55c6..8b9cfe0023 100644
--- a/kernel/model/updater.go
+++ b/kernel/model/updater.go
@@ -17,15 +17,14 @@
package model
import (
- "bufio"
"context"
"crypto/sha256"
+ "errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
- "runtime"
"strings"
"sync"
"time"
@@ -57,8 +56,9 @@ func getNewVerInstallPkgPath() string {
}
var checkDownloadInstallPkgLock = sync.Mutex{}
+var errUpdatePackageUnavailable = errors.New("update package is unavailable")
-func checkDownloadInstallPkg() {
+func checkDownloadInstallPkg(notifyPackageUnavailable bool) {
defer logging.Recover()
if skipNewVerInstallPkg() {
@@ -72,6 +72,11 @@ func checkDownloadInstallPkg() {
downloadPkgURLs, checksum, err := getUpdatePkg()
if err != nil {
+ if notifyPackageUnavailable && errors.Is(err, errUpdatePackageUnavailable) {
+ if release, releaseErr := getUpdateRelease(false); nil == releaseErr && !isVersionUpToDate(release.Version) {
+ pushNewVersionNotification(release)
+ }
+ }
return
}
@@ -99,62 +104,38 @@ func checkDownloadInstallPkg() {
}
func getUpdatePkg() (downloadPkgURLs []string, checksum string, err error) {
- defer logging.Recover()
- result, err := util.GetRhyResult(context.TODO(), false)
+ release, err := getUpdateRelease(false)
if err != nil {
return
}
- ver := result["ver"].(string)
- if isVersionUpToDate(ver) {
+ if isVersionUpToDate(release.Version) {
err = fmt.Errorf("version is up to date")
return
}
- var suffix string
- if gulu.OS.IsWindows() {
- if "arm64" == runtime.GOARCH {
- suffix = "win-arm64.exe"
- } else {
- suffix = "win.exe"
- }
- } else if gulu.OS.IsDarwin() {
- if "arm64" == runtime.GOARCH {
- suffix = "mac-arm64.dmg"
- } else {
- suffix = "mac.dmg"
- }
+ pkgName := currentInstallPackageName(release.Version)
+ if "" == pkgName {
+ err = fmt.Errorf("%w for the current platform", errUpdatePackageUnavailable)
+ return
}
- pkg := "siyuan-" + ver + "-" + suffix
-
- b3logURL := "https://release.b3log.org/siyuan/" + pkg
- liuyunURL := "https://release.liuyun.io/siyuan/" + pkg
- githubURL := "https://github.com/siyuan-note/siyuan/releases/download/v" + ver + "/" + pkg
- ghproxyURL := "https://ghfast.top/" + githubURL
- if util.IsChinaCloud() {
- downloadPkgURLs = append(downloadPkgURLs, b3logURL)
- downloadPkgURLs = append(downloadPkgURLs, liuyunURL)
- downloadPkgURLs = append(downloadPkgURLs, ghproxyURL)
- downloadPkgURLs = append(downloadPkgURLs, githubURL)
- } else {
- downloadPkgURLs = append(downloadPkgURLs, b3logURL)
- downloadPkgURLs = append(downloadPkgURLs, liuyunURL)
- downloadPkgURLs = append(downloadPkgURLs, githubURL)
- downloadPkgURLs = append(downloadPkgURLs, ghproxyURL)
+ pkg := release.Packages[pkgName]
+ if nil == pkg || 0 == len(pkg.URLs) {
+ err = fmt.Errorf("%w: [%s]", errUpdatePackageUnavailable, pkgName)
+ return
}
-
- checksums := result["checksums"].(map[string]any)
- checksum = checksums[pkg].(string)
-
- if "" == checksum {
- err = fmt.Errorf("checksum is empty")
+ if "" == pkg.Checksum {
+ err = fmt.Errorf("%w: [%s] checksum is unavailable", errUpdatePackageUnavailable, pkgName)
return
}
+ downloadPkgURLs = append(downloadPkgURLs, pkg.URLs...)
+ checksum = pkg.Checksum
return
}
func downloadInstallPkg(pkgURL, checksum string) (err error) {
if "" == pkgURL || "" == checksum {
+ err = errors.New("update package URL or checksum is empty")
return
}
@@ -183,12 +164,19 @@ func downloadInstallPkg(pkgURL, checksum string) (err error) {
_, err = client.R().SetOutputFile(savePath).SetDownloadCallbackWithInterval(callback, 1*time.Second).Get(pkgURL)
if err != nil {
logging.LogErrorf("download install package [%s] failed: %s", pkgURL, err)
+ if removeErr := os.Remove(savePath); nil != removeErr && !os.IsNotExist(removeErr) {
+ logging.LogErrorf("remove incomplete install package [%s] failed: %s", savePath, removeErr)
+ }
return
}
localChecksum, _ := sha256Hash(savePath)
if checksum != localChecksum {
- logging.LogErrorf("verify checksum failed, download install package [%s] checksum [%s] not equal to downloaded [%s] checksum [%s]", pkgURL, checksum, savePath, localChecksum)
+ err = fmt.Errorf("verify checksum failed, download install package [%s] checksum [%s] not equal to downloaded [%s] checksum [%s]", pkgURL, checksum, savePath, localChecksum)
+ logging.LogError(err.Error())
+ if removeErr := os.Remove(savePath); nil != removeErr && !os.IsNotExist(removeErr) {
+ logging.LogErrorf("remove invalid install package [%s] failed: %s", savePath, removeErr)
+ }
return
}
logging.LogInfof("downloaded install package [%s] to [%s]", pkgURL, savePath)
@@ -204,18 +192,10 @@ func sha256Hash(filename string) (ret string, err error) {
defer file.Close()
hash := sha256.New()
- reader := bufio.NewReader(file)
- buf := make([]byte, 1024*1024*4)
- for {
- switch n, readErr := reader.Read(buf); readErr {
- case nil:
- hash.Write(buf[:n])
- case io.EOF:
- return fmt.Sprintf("%x", hash.Sum(nil)), nil
- default:
- return "", err
- }
+ if _, err = io.Copy(hash, file); err != nil {
+ return "", err
}
+ return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
type Announcement struct {
@@ -258,31 +238,27 @@ func CheckUpdate(showMsg bool) {
return
}
- result, err := util.GetRhyResult(context.TODO(), showMsg)
+ release, err := getUpdateRelease(showMsg)
if err != nil {
return
}
- ver := result["ver"].(string)
- releaseLang := result["release"].(string)
- if releaseLangArg := result["release_"+Conf.Lang]; nil != releaseLangArg {
- releaseLang = releaseLangArg.(string)
- } else if releaseLangArg := result["release_"+util.LangToLegacy(Conf.Lang)]; nil != releaseLangArg {
- // 兼容云端 JSON 数据中历史下划线 key(release_zh_CN 等)
- releaseLang = releaseLangArg.(string)
- }
-
- if isVersionUpToDate(ver) {
+ if isVersionUpToDate(release.Version) {
util.PushUpdateMsg("update-notify", Conf.Language(10), 3000)
} else {
- util.PushUpdateMsg("update-notify", fmt.Sprintf(Conf.Language(9), "<a href=\""+releaseLang+"\">"+releaseLang+"</a>"), 15000)
+ pushNewVersionNotification(release)
}
go func() {
defer logging.Recover()
- checkDownloadInstallPkg()
+ checkDownloadInstallPkg(false)
}()
}
+func pushNewVersionNotification(release *updateRelease) {
+ releaseLink := "<a href=\"" + release.ReleaseURL + "\">" + release.ReleaseURL + "</a>"
+ util.PushUpdateMsg("update-notify", fmt.Sprintf(Conf.Language(9), releaseLink), 15000)
+}
+
func isVersionUpToDate(releaseVer string) bool {
return semver.Compare("v"+releaseVer, "v"+util.Ver) <= 0
}
diff --git a/kernel/model/updater_release.go b/kernel/model/updater_release.go
new file mode 100644
index 0000000000..dae247f7f3
--- /dev/null
+++ b/kernel/model/updater_release.go
@@ -0,0 +1,443 @@
+// 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 (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "path"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/88250/gulu"
+ "github.com/siyuan-note/httpclient"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "golang.org/x/mod/semver"
+ "golang.org/x/sync/singleflight"
+)
+
+const (
+ githubReleasesURL = "https://api.github.com/repos/siyuan-note/siyuan/releases?per_page=100"
+ githubReleaseURLPrefix = "https://github.com/siyuan-note/siyuan/releases/tag/v"
+ githubAPIReleaseCacheSeconds = int64(6 * 60 * 60)
+ maxChecksumManifestSize = int64(1024 * 1024)
+)
+
+type updateRelease struct {
+ Version string
+ ReleaseURL string
+ Packages map[string]*updatePackage
+}
+
+type updatePackage struct {
+ URLs []string
+ Checksum string
+}
+
+type githubRelease struct {
+ TagName string `json:"tag_name"`
+ HTMLURL string `json:"html_url"`
+ Draft bool `json:"draft"`
+ Assets []*githubReleaseAsset `json:"assets"`
+}
+
+type githubReleaseAsset struct {
+ Name string `json:"name"`
+ BrowserDownloadURL string `json:"browser_download_url"`
+ Digest string `json:"digest"`
+ State string `json:"state"`
+}
+
+var (
+ cachedGitHubReleases []*githubRelease
+ githubReleasesCacheTime int64
+ githubReleasesLock sync.RWMutex
+ githubReleasesFlight singleflight.Group
+ githubManifestCache sync.Map
+)
+
+func getUpdateRelease(force bool) (*updateRelease, error) {
+ channel := Conf.System.UpdateChannel
+ if conf.UpdateChannelStable == channel {
+ return getStableUpdateRelease(force)
+ }
+ if !isValidUpdateChannel(channel) {
+ return nil, errors.New("update channel is invalid")
+ }
+ return getGitHubUpdateRelease(channel, force)
+}
+
+func getStableUpdateRelease(force bool) (*updateRelease, error) {
+ result, err := util.GetRhyResult(context.TODO(), force)
+ if err != nil {
+ return nil, err
+ }
+ version, ok := result["ver"].(string)
+ normalizedVersion := normalizeReleaseVersion(version)
+ if !ok || !semver.IsValid(normalizedVersion) || "" != semver.Prerelease(normalizedVersion) {
+ return nil, errors.New("stable release version is invalid")
+ }
+ version = strings.TrimPrefix(normalizedVersion, "v")
+
+ release := &updateRelease{
+ Version: version,
+ ReleaseURL: getStableReleaseURL(result, version),
+ Packages: map[string]*updatePackage{},
+ }
+ pkgName := currentInstallPackageName(release.Version)
+ if "" == pkgName {
+ return release, nil
+ }
+ checksum := getStablePackageChecksum(result, pkgName)
+ if "" == checksum {
+ return release, nil
+ }
+ release.Packages[pkgName] = &updatePackage{
+ URLs: getStablePackageURLs(release.Version, pkgName),
+ Checksum: checksum,
+ }
+ return release, nil
+}
+
+func getStableReleaseURL(result map[string]any, version string) string {
+ releaseURL, _ := result["release"].(string)
+ if localized, ok := result["release_"+Conf.Lang].(string); ok && "" != localized {
+ releaseURL = localized
+ } else if localized, ok = result["release_"+util.LangToLegacy(Conf.Lang)].(string); ok && "" != localized {
+ // 兼容云端 JSON 数据中历史下划线 key(release_zh_CN 等)。
+ releaseURL = localized
+ }
+ if "" == releaseURL {
+ releaseURL = githubReleaseURLPrefix + strings.TrimPrefix(version, "v")
+ }
+ return releaseURL
+}
+
+func getStablePackageChecksum(result map[string]any, pkgName string) string {
+ checksums, ok := result["checksums"].(map[string]any)
+ if !ok {
+ return ""
+ }
+ checksum, ok := checksums[pkgName].(string)
+ if !ok {
+ return ""
+ }
+ return normalizeSHA256(checksum)
+}
+
+func getStablePackageURLs(version, pkgName string) []string {
+ b3logURL := "https://release.b3log.org/siyuan/" + pkgName
+ liuyunURL := "https://release.liuyun.io/siyuan/" + pkgName
+ githubURL := "https://github.com/siyuan-note/siyuan/releases/download/v" + strings.TrimPrefix(version, "v") + "/" + pkgName
+ ghproxyURL := "https://ghfast.top/" + githubURL
+ if util.IsChinaCloud() {
+ return []string{b3logURL, liuyunURL, ghproxyURL, githubURL}
+ }
+ return []string{b3logURL, liuyunURL, githubURL, ghproxyURL}
+}
+
+func getGitHubUpdateRelease(channel string, force bool) (*updateRelease, error) {
+ releases, err := getGitHubReleases(context.TODO(), force)
+ if err != nil {
+ return nil, err
+ }
+ selected := selectGitHubRelease(releases, channel)
+ if nil == selected {
+ return nil, errors.New("no release is available for the update channel")
+ }
+
+ version := strings.TrimPrefix(normalizeReleaseVersion(selected.TagName), "v")
+ release := &updateRelease{
+ Version: version,
+ ReleaseURL: selected.HTMLURL,
+ Packages: map[string]*updatePackage{},
+ }
+ if "" == release.ReleaseURL {
+ release.ReleaseURL = githubReleaseURLPrefix + version
+ }
+
+ pkgName := currentInstallPackageName(version)
+ if "" == pkgName {
+ return release, nil
+ }
+ asset := findGitHubReleaseAsset(selected, pkgName)
+ if nil == asset || "uploaded" != asset.State || "" == asset.BrowserDownloadURL {
+ return release, nil
+ }
+
+ checksum := normalizeSHA256(asset.Digest)
+ if "" == checksum {
+ checksum, err = getGitHubManifestChecksum(context.TODO(), selected, pkgName)
+ if err != nil {
+ logging.LogWarnf("get release package [%s] checksum failed: %s", pkgName, err)
+ return release, nil
+ }
+ }
+ release.Packages[pkgName] = &updatePackage{
+ URLs: []string{asset.BrowserDownloadURL},
+ Checksum: checksum,
+ }
+ return release, nil
+}
+
+func getGitHubReleases(ctx context.Context, force bool) ([]*githubRelease, error) {
+ if !force {
+ githubReleasesLock.RLock()
+ if githubAPIReleaseCacheSeconds >= time.Now().Unix()-githubReleasesCacheTime && 0 < len(cachedGitHubReleases) {
+ ret := cachedGitHubReleases
+ githubReleasesLock.RUnlock()
+ return ret, nil
+ }
+ githubReleasesLock.RUnlock()
+ }
+
+ value, err, _ := githubReleasesFlight.Do("github-releases", func() (any, error) {
+ if !force {
+ githubReleasesLock.RLock()
+ if githubAPIReleaseCacheSeconds >= time.Now().Unix()-githubReleasesCacheTime && 0 < len(cachedGitHubReleases) {
+ ret := cachedGitHubReleases
+ githubReleasesLock.RUnlock()
+ return ret, nil
+ }
+ githubReleasesLock.RUnlock()
+ }
+ return fetchGitHubReleases(ctx)
+ })
+ if err != nil {
+ return nil, err
+ }
+ return value.([]*githubRelease), nil
+}
+
+func fetchGitHubReleases(ctx context.Context) ([]*githubRelease, error) {
+ releases := []*githubRelease{}
+ request := httpclient.NewCloudRequest30s().
+ SetContext(ctx).
+ SetHeader("Accept", "application/vnd.github+json").
+ SetHeader("X-GitHub-Api-Version", "2022-11-28").
+ SetSuccessResult(&releases)
+ response, err := request.Get(githubReleasesURL)
+ if err != nil {
+ logging.LogErrorf("get GitHub releases failed: %s", err)
+ return nil, err
+ }
+ if 200 != response.StatusCode {
+ err = fmt.Errorf("get GitHub releases failed: %d", response.StatusCode)
+ logging.LogError(err.Error())
+ return nil, err
+ }
+ if 0 == len(releases) {
+ return nil, errors.New("GitHub releases are empty")
+ }
+
+ githubReleasesLock.Lock()
+ cachedGitHubReleases = releases
+ githubReleasesCacheTime = time.Now().Unix()
+ githubReleasesLock.Unlock()
+ return releases, nil
+}
+
+func selectGitHubRelease(releases []*githubRelease, channel string) *githubRelease {
+ var selected *githubRelease
+ for _, release := range releases {
+ if nil == release || release.Draft || !isReleaseAllowed(channel, release.TagName) {
+ continue
+ }
+ if nil == selected || 0 < semver.Compare(normalizeReleaseVersion(release.TagName), normalizeReleaseVersion(selected.TagName)) {
+ selected = release
+ }
+ }
+ return selected
+}
+
+func isReleaseAllowed(channel, version string) bool {
+ normalized := normalizeReleaseVersion(version)
+ if !semver.IsValid(normalized) {
+ return false
+ }
+ prerelease := strings.TrimPrefix(semver.Prerelease(normalized), "-")
+ label := prereleaseChannelLabel(prerelease)
+ switch channel {
+ case conf.UpdateChannelStable:
+ return "" == prerelease
+ case conf.UpdateChannelBeta:
+ return "" == prerelease || "beta" == label || "rc" == label
+ case conf.UpdateChannelAlpha:
+ return "" == prerelease || "alpha" == label || "beta" == label || "rc" == label
+ default:
+ return false
+ }
+}
+
+func prereleaseChannelLabel(prerelease string) string {
+ identifier := strings.SplitN(prerelease, ".", 2)[0]
+ for _, channel := range []string{"alpha", "beta", "rc"} {
+ if channel == identifier {
+ return channel
+ }
+ suffix := strings.TrimPrefix(identifier, channel)
+ if suffix == identifier || "" == suffix {
+ continue
+ }
+ allDigits := true
+ for _, r := range suffix {
+ if '0' > r || '9' < r {
+ allDigits = false
+ break
+ }
+ }
+ if allDigits {
+ return channel
+ }
+ }
+ return ""
+}
+
+func normalizeReleaseVersion(version string) string {
+ return "v" + strings.TrimPrefix(strings.TrimSpace(version), "v")
+}
+
+func currentInstallPackageName(version string) string {
+ suffix := currentInstallPackageSuffix()
+ if "" == suffix {
+ return ""
+ }
+ return "siyuan-" + strings.TrimPrefix(version, "v") + "-" + suffix
+}
+
+func currentInstallPackageSuffix() string {
+ if gulu.OS.IsWindows() {
+ switch runtime.GOARCH {
+ case "amd64":
+ return "win.exe"
+ case "arm64":
+ return "win-arm64.exe"
+ default:
+ return ""
+ }
+ }
+ if gulu.OS.IsDarwin() {
+ switch runtime.GOARCH {
+ case "amd64":
+ return "mac.dmg"
+ case "arm64":
+ return "mac-arm64.dmg"
+ default:
+ return ""
+ }
+ }
+ return ""
+}
+
+func findGitHubReleaseAsset(release *githubRelease, name string) *githubReleaseAsset {
+ for _, asset := range release.Assets {
+ if nil != asset && name == asset.Name {
+ return asset
+ }
+ }
+ return nil
+}
+
+func getGitHubManifestChecksum(ctx context.Context, release *githubRelease, pkgName string) (string, error) {
+ manifestAsset := findGitHubReleaseAsset(release, "SHA256SUMS.txt")
+ if nil == manifestAsset || "uploaded" != manifestAsset.State || "" == manifestAsset.BrowserDownloadURL {
+ return "", errors.New("checksum manifest is unavailable")
+ }
+ manifestDigest := normalizeSHA256(manifestAsset.Digest)
+ manifestCacheKey := ""
+ if "" != manifestDigest {
+ manifestCacheKey = manifestAsset.BrowserDownloadURL + "#" + manifestDigest
+ }
+ if "" != manifestCacheKey {
+ cached, ok := githubManifestCache.Load(manifestCacheKey)
+ if ok {
+ if checksum := parseChecksumManifest(cached.(string), pkgName); "" != checksum {
+ return checksum, nil
+ }
+ return "", errors.New("package checksum is unavailable")
+ }
+ }
+
+ response, err := httpclient.NewCloudRequest30s().SetContext(ctx).Get(manifestAsset.BrowserDownloadURL)
+ if err != nil {
+ return "", err
+ }
+ if nil == response || nil == response.Response {
+ return "", errors.New("checksum manifest response is empty")
+ }
+ defer response.Body.Close()
+ if 200 != response.StatusCode {
+ return "", fmt.Errorf("get checksum manifest failed: %d", response.StatusCode)
+ }
+ data, err := io.ReadAll(io.LimitReader(response.Body, maxChecksumManifestSize+1))
+ if err != nil {
+ return "", err
+ }
+ if maxChecksumManifestSize < int64(len(data)) {
+ return "", errors.New("checksum manifest is too large")
+ }
+ if "" != manifestDigest {
+ actualDigest := fmt.Sprintf("%x", sha256.Sum256(data))
+ if manifestDigest != actualDigest {
+ return "", errors.New("checksum manifest digest mismatch")
+ }
+ }
+ manifest := string(data)
+ if "" != manifestCacheKey {
+ githubManifestCache.Store(manifestCacheKey, manifest)
+ }
+ checksum := parseChecksumManifest(manifest, pkgName)
+ if "" == checksum {
+ return "", errors.New("package checksum is unavailable")
+ }
+ return checksum, nil
+}
+
+func parseChecksumManifest(manifest, pkgName string) string {
+ for _, line := range strings.Split(manifest, "\n") {
+ fields := strings.Fields(line)
+ if 2 > len(fields) {
+ continue
+ }
+ name := strings.TrimPrefix(fields[1], "*")
+ name = path.Base(strings.ReplaceAll(name, "\\", "/"))
+ if pkgName == name {
+ return normalizeSHA256(fields[0])
+ }
+ }
+ return ""
+}
+
+func normalizeSHA256(value string) string {
+ value = strings.ToLower(strings.TrimSpace(value))
+ value = strings.TrimPrefix(value, "sha256:")
+ if 64 != len(value) {
+ return ""
+ }
+ if _, err := hex.DecodeString(value); err != nil {
+ return ""
+ }
+ return value
+}
diff --git a/kernel/model/updater_release_test.go b/kernel/model/updater_release_test.go
new file mode 100644
index 0000000000..cdc3304932
--- /dev/null
+++ b/kernel/model/updater_release_test.go
@@ -0,0 +1,113 @@
+// 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 (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+)
+
+func TestIsReleaseAllowed(t *testing.T) {
+ tests := []struct {
+ channel string
+ version string
+ want bool
+ }{
+ {conf.UpdateChannelStable, "v3.7.3", true},
+ {conf.UpdateChannelStable, "v3.7.4-rc.1", false},
+ {conf.UpdateChannelBeta, "v3.7.3", true},
+ {conf.UpdateChannelBeta, "v3.7.4-alpha.1", false},
+ {conf.UpdateChannelBeta, "v3.7.4-beta.1", true},
+ {conf.UpdateChannelBeta, "v2.0.0-beta2", true},
+ {conf.UpdateChannelBeta, "v3.7.4-rc.1", true},
+ {conf.UpdateChannelBeta, "v1.2.0-rc3", true},
+ {conf.UpdateChannelAlpha, "v3.7.4-alpha.1", true},
+ {conf.UpdateChannelAlpha, "v0.5.6-alpha1", true},
+ {conf.UpdateChannelAlpha, "v3.7.4-beta.1", true},
+ {conf.UpdateChannelAlpha, "v3.7.4-rc.1", true},
+ {conf.UpdateChannelAlpha, "v3.7.4-preview.1", false},
+ {conf.UpdateChannelAlpha, "v3.7.4-alphabet.1", false},
+ {conf.UpdateChannelAlpha, "invalid", false},
+ {"invalid", "v3.7.3", false},
+ }
+ for _, test := range tests {
+ if got := isReleaseAllowed(test.channel, test.version); got != test.want {
+ t.Fatalf("channel [%s] version [%s]: got %t, want %t", test.channel, test.version, got, test.want)
+ }
+ }
+}
+
+func TestSelectGitHubRelease(t *testing.T) {
+ releases := []*githubRelease{
+ {TagName: "v3.7.4-beta.1"},
+ {TagName: "v3.7.3"},
+ {TagName: "v3.8.0-preview.1"},
+ {TagName: "v3.7.4-rc.1"},
+ {TagName: "v3.8.0-alpha.1"},
+ {TagName: "v4.0.0", Draft: true},
+ }
+
+ beta := selectGitHubRelease(releases, conf.UpdateChannelBeta)
+ if nil == beta || "v3.7.4-rc.1" != beta.TagName {
+ t.Fatalf("unexpected Beta release: %#v", beta)
+ }
+ alpha := selectGitHubRelease(releases, conf.UpdateChannelAlpha)
+ if nil == alpha || "v3.8.0-alpha.1" != alpha.TagName {
+ t.Fatalf("unexpected Alpha release: %#v", alpha)
+ }
+}
+
+func TestParseChecksumManifest(t *testing.T) {
+ checksum := strings.Repeat("A", 64)
+ manifest := checksum + " *nested\\siyuan-3.7.4-alpha.1-win.exe\n"
+ got := parseChecksumManifest(manifest, "siyuan-3.7.4-alpha.1-win.exe")
+ if strings.ToLower(checksum) != got {
+ t.Fatalf("unexpected checksum: %q", got)
+ }
+ if "" != parseChecksumManifest(manifest, "siyuan-3.7.4-alpha.1-win-arm64.exe") {
+ t.Fatal("unexpected checksum for missing package")
+ }
+}
+
+func TestNormalizeSHA256(t *testing.T) {
+ checksum := strings.Repeat("A", 64)
+ if got := normalizeSHA256("sha256:" + checksum); strings.ToLower(checksum) != got {
+ t.Fatalf("unexpected normalized checksum: %q", got)
+ }
+ if "" != normalizeSHA256(strings.Repeat("z", 64)) {
+ t.Fatal("invalid checksum should be rejected")
+ }
+}
+
+func TestSHA256Hash(t *testing.T) {
+ filePath := filepath.Join(t.TempDir(), "package")
+ if err := os.WriteFile(filePath, []byte("abc"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ got, err := sha256Hash(filePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const want = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
+ if want != got {
+ t.Fatalf("unexpected checksum: %q", got)
+ }
+}
diff --git a/kernel/util/working.go b/kernel/util/working.go
index ccd3f6a4a9..1875011b26 100644
--- a/kernel/util/working.go
+++ b/kernel/util/working.go
@@ -44,10 +44,7 @@ import (
// var Mode = "dev"
var Mode = "prod"
-const (
- Ver = "3.7.4-alpha.2"
- IsInsider = false
-)
+const Ver = "3.7.4-alpha.2"
// IsReleaseVer 判断是否为正式版(不含 alpha、beta、rc 等预发布标识)。
func IsReleaseVer(ver string) bool {