Skip to content

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

:art: Normalize bazaar naming and reorganize kernel/bazaar structure (#17133)

Jeffrey Chenba733eedfd9b
diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.ts
index 64814a0f25..7a5d73bcc3 100644
--- a/app/src/dialog/processSystem.ts
+++ b/app/src/dialog/processSystem.ts
@@ -537,14 +537,14 @@ export const setTitle = (title: string) => {
};
export const downloadProgress = (data: { id: string, percent: number }) => {
- const bazzarSideElement = document.querySelector("#configBazaarReadme .item__side");
- if (!bazzarSideElement) {
+ const bazaarSideElement = document.querySelector("#configBazaarReadme .item__side");
+ if (!bazaarSideElement) {
return;
}
- if (data.id !== JSON.parse(bazzarSideElement.getAttribute("data-obj")).repoURL) {
+ if (data.id !== JSON.parse(bazaarSideElement.getAttribute("data-obj")).repoURL) {
return;
}
- const btnElement = bazzarSideElement.querySelector('[data-type="install"]') as HTMLElement;
+ const btnElement = bazaarSideElement.querySelector('[data-type="install"]') as HTMLElement;
if (btnElement) {
if (data.percent >= 1) {
btnElement.parentElement.classList.add("fn__none");
diff --git a/kernel/bazaar/package.go b/kernel/bazaar/package.go
index 59004a03ae..6ecaae1c7c 100644
--- a/kernel/bazaar/package.go
+++ b/kernel/bazaar/package.go
@@ -18,7 +18,6 @@ package bazaar
import (
"bytes"
- "context"
"errors"
"fmt"
"os"
@@ -28,7 +27,6 @@ import (
"time"
"github.com/88250/gulu"
- "github.com/88250/lute"
"github.com/araddon/dateparse"
"github.com/imroc/req/v3"
gcache "github.com/patrickmn/go-cache"
@@ -37,9 +35,6 @@ import (
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/util"
"golang.org/x/mod/semver"
- "golang.org/x/sync/singleflight"
- textUnicode "golang.org/x/text/encoding/unicode"
- "golang.org/x/text/transform"
)
// LocaleStrings 表示按语种 key 的字符串表,key 为语种如 "default"、"en_US"、"zh_CN" 等
@@ -274,388 +269,6 @@ func ThemeJSON(themeDirName string) (ret *Theme, err error) {
return
}
-var cachedStageIndex = map[string]*StageIndex{}
-var stageIndexCacheTime int64
-var stageIndexLock = sync.RWMutex{}
-
-type StageBazaarResult struct {
- StageIndex *StageIndex // stage 索引
- BazaarIndex map[string]*bazaarPackage // bazaar 索引
- Online bool // online 状态
- StageErr error // stage 错误
-}
-
-var stageBazaarFlight singleflight.Group
-var onlineCheckFlight singleflight.Group
-
-// getStageAndBazaar 获取 stage 索引和 bazaar 索引,相同 pkgType 的并发调用会合并为一次实际请求 (single-flight)
-func getStageAndBazaar(pkgType string) (result StageBazaarResult) {
- key := "stageBazaar:" + pkgType
- v, err, _ := stageBazaarFlight.Do(key, func() (interface{}, error) {
- return getStageAndBazaar0(pkgType), nil
- })
- if err != nil {
- return
- }
- result = v.(StageBazaarResult)
- return
-}
-
-// getStageAndBazaar0 执行一次 stage 和 bazaar 索引拉取
-func getStageAndBazaar0(pkgType string) (result StageBazaarResult) {
- stageIndex, stageErr := getStageIndexFromCache(pkgType)
- bazaarIndex := getBazaarIndexFromCache()
- if nil != stageIndex && nil != bazaarIndex {
- // 两者都从缓存返回,不需要 online 检查
- return StageBazaarResult{
- StageIndex: stageIndex,
- BazaarIndex: bazaarIndex,
- Online: true,
- StageErr: stageErr,
- }
- }
-
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- var onlineResult bool
- onlineDone := make(chan bool, 1)
- wg := &sync.WaitGroup{}
- wg.Add(3)
- go func() {
- defer wg.Done()
- onlineResult = isBazzarOnline()
- onlineDone <- true
- }()
- go func() {
- defer wg.Done()
- stageIndex, stageErr = getStageIndex(ctx, pkgType)
- }()
- go func() {
- defer wg.Done()
- bazaarIndex = getBazaarIndex(ctx)
- }()
-
- <-onlineDone
- if !onlineResult {
- // 不在线时立即取消其他请求并返回结果,避免等待 HTTP 请求超时
- cancel()
- return StageBazaarResult{
- StageIndex: stageIndex,
- BazaarIndex: bazaarIndex,
- Online: false,
- StageErr: stageErr,
- }
- }
-
- // 在线时等待所有请求完成
- wg.Wait()
-
- return StageBazaarResult{
- StageIndex: stageIndex,
- BazaarIndex: bazaarIndex,
- Online: onlineResult,
- StageErr: stageErr,
- }
-}
-
-// getStageIndexFromCache 仅从缓存获取 stage 索引,过期或无缓存时返回 nil
-func getStageIndexFromCache(pkgType string) (ret *StageIndex, err error) {
- stageIndexLock.RLock()
- cacheTime := stageIndexCacheTime
- cached := cachedStageIndex[pkgType]
- stageIndexLock.RUnlock()
- if util.RhyCacheDuration >= time.Now().Unix()-cacheTime && nil != cached {
- ret = cached
- }
- return
-}
-
-// getStageIndex 获取 stage 索引
-func getStageIndex(ctx context.Context, pkgType string) (ret *StageIndex, err error) {
- if cached, cacheErr := getStageIndexFromCache(pkgType); nil != cached {
- ret = cached
- err = cacheErr
- return
- }
-
- var rhyRet map[string]interface{}
- rhyRet, err = util.GetRhyResult(ctx, false)
- if nil != err {
- return
- }
-
- stageIndexLock.Lock()
- defer stageIndexLock.Unlock()
-
- bazaarHash := rhyRet["bazaar"].(string)
- ret = &StageIndex{}
- request := httpclient.NewBrowserRequest()
- u := util.BazaarOSSServer + "/bazaar@" + bazaarHash + "/stage/" + pkgType + ".json"
- resp, reqErr := request.SetContext(ctx).SetSuccessResult(ret).Get(u)
- if nil != reqErr {
- logging.LogErrorf("get community stage index [%s] failed: %s", u, reqErr)
- err = reqErr
- return
- }
- if 200 != resp.StatusCode {
- logging.LogErrorf("get community stage index [%s] failed: %d", u, resp.StatusCode)
- err = errors.New("get stage index failed")
- return
- }
-
- stageIndexCacheTime = time.Now().Unix()
- cachedStageIndex[pkgType] = ret
- return
-}
-
-func isOutdatedTheme(theme *Theme, bazaarThemes []*Theme) bool {
- if !strings.HasPrefix(theme.URL, "https://github.com/") {
- return false
- }
-
- repo := strings.TrimPrefix(theme.URL, "https://github.com/")
- parts := strings.Split(repo, "/")
- if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
- return false
- }
-
- for _, pkg := range bazaarThemes {
- if theme.Name == pkg.Name && 0 > semver.Compare("v"+theme.Version, "v"+pkg.Version) {
- theme.RepoHash = pkg.RepoHash
- return true
- }
- }
- return false
-}
-
-func isOutdatedIcon(icon *Icon, bazaarIcons []*Icon) bool {
- if !strings.HasPrefix(icon.URL, "https://github.com/") {
- return false
- }
-
- repo := strings.TrimPrefix(icon.URL, "https://github.com/")
- parts := strings.Split(repo, "/")
- if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
- return false
- }
-
- for _, pkg := range bazaarIcons {
- if icon.Name == pkg.Name && 0 > semver.Compare("v"+icon.Version, "v"+pkg.Version) {
- icon.RepoHash = pkg.RepoHash
- return true
- }
- }
- return false
-}
-
-func isOutdatedPlugin(plugin *Plugin, bazaarPlugins []*Plugin) bool {
- if !strings.HasPrefix(plugin.URL, "https://github.com/") {
- return false
- }
-
- repo := strings.TrimPrefix(plugin.URL, "https://github.com/")
- parts := strings.Split(repo, "/")
- if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
- return false
- }
-
- for _, pkg := range bazaarPlugins {
- if plugin.Name == pkg.Name && 0 > semver.Compare("v"+plugin.Version, "v"+pkg.Version) {
- plugin.RepoHash = pkg.RepoHash
- return true
- }
- }
- return false
-}
-
-func isOutdatedWidget(widget *Widget, bazaarWidgets []*Widget) bool {
- if !strings.HasPrefix(widget.URL, "https://github.com/") {
- return false
- }
-
- repo := strings.TrimPrefix(widget.URL, "https://github.com/")
- parts := strings.Split(repo, "/")
- if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
- return false
- }
-
- for _, pkg := range bazaarWidgets {
- if widget.Name == pkg.Name && 0 > semver.Compare("v"+widget.Version, "v"+pkg.Version) {
- widget.RepoHash = pkg.RepoHash
- return true
- }
- }
- return false
-}
-
-func isOutdatedTemplate(template *Template, bazaarTemplates []*Template) bool {
- if !strings.HasPrefix(template.URL, "https://github.com/") {
- return false
- }
-
- repo := strings.TrimPrefix(template.URL, "https://github.com/")
- parts := strings.Split(repo, "/")
- if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
- return false
- }
-
- for _, pkg := range bazaarTemplates {
- if template.Name == pkg.Name && 0 > semver.Compare("v"+template.Version, "v"+pkg.Version) {
- template.RepoHash = pkg.RepoHash
- return true
- }
- }
- return false
-}
-
-func isBazzarOnline() bool {
- v, err, _ := onlineCheckFlight.Do("bazaarOnline", func() (interface{}, error) {
- return isBazzarOnline0(), nil
- })
- if err != nil {
- return false
- }
- return v.(bool)
-}
-
-func isBazzarOnline0() (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
-}
-
-func GetPackageREADME(repoURL, repoHash, packageType string) (ret string) {
- repoURLHash := repoURL + "@" + repoHash
-
- stageIndexLock.RLock()
- stageIndex := cachedStageIndex[packageType]
- stageIndexLock.RUnlock()
- if nil == stageIndex {
- return
- }
-
- url := strings.TrimPrefix(repoURLHash, "https://github.com/")
- var repo *StageRepo
- for _, r := range stageIndex.Repos {
- if r.URL == url {
- repo = r
- break
- }
- }
- if nil == repo || nil == repo.Package {
- return
- }
-
- readme := getPreferredReadme(repo.Package.Readme)
-
- data, err := downloadPackage(repoURLHash+"/"+readme, false, "")
- if err != nil {
- ret = fmt.Sprintf("Load bazaar package's preferred README(%s) failed: %s", readme, err.Error())
- // 回退到 Default README
- var defaultReadme string
- if len(repo.Package.Readme) > 0 {
- defaultReadme = repo.Package.Readme["default"]
- }
- if "" == strings.TrimSpace(defaultReadme) {
- defaultReadme = "README.md"
- }
- if readme != defaultReadme {
- data, err = downloadPackage(repoURLHash+"/"+defaultReadme, false, "")
- if err != nil {
- ret += fmt.Sprintf("<br>Load bazaar package's default README(%s) failed: %s", defaultReadme, err.Error())
- }
- }
- // 回退到 README.md
- if err != nil && readme != "README.md" && defaultReadme != "README.md" {
- data, err = downloadPackage(repoURLHash+"/README.md", false, "")
- if err != nil {
- ret += fmt.Sprintf("<br>Load bazaar package's README.md failed: %s", err.Error())
- return
- }
- } else if err != nil {
- return
- }
- }
-
- if 2 < len(data) {
- if 255 == data[0] && 254 == data[1] {
- data, _, err = transform.Bytes(textUnicode.UTF16(textUnicode.LittleEndian, textUnicode.ExpectBOM).NewDecoder(), data)
- } else if 254 == data[0] && 255 == data[1] {
- data, _, err = transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.ExpectBOM).NewDecoder(), data)
- }
- }
-
- ret, err = renderREADME(repoURL, data)
- return
-}
-
-func loadInstalledReadme(installPath, basePath string, readme LocaleStrings) (ret string) {
- readmeFilename := getPreferredReadme(readme)
- readmeData, readErr := os.ReadFile(filepath.Join(installPath, readmeFilename))
- if nil == readErr {
- ret, _ = renderLocalREADME(basePath, readmeData)
- return
- }
-
- logging.LogWarnf("read installed %s failed: %s", readmeFilename, readErr)
- ret = fmt.Sprintf("File %s not found", readmeFilename)
- // 回退到 Default README
- var defaultReadme string
- if len(readme) > 0 {
- defaultReadme = strings.TrimSpace(readme["default"])
- }
- if "" == defaultReadme {
- defaultReadme = "README.md"
- }
- if readmeFilename != defaultReadme {
- readmeData, readErr = os.ReadFile(filepath.Join(installPath, defaultReadme))
- if nil == readErr {
- ret, _ = renderLocalREADME(basePath, readmeData)
- return
- }
- logging.LogWarnf("read installed %s failed: %s", defaultReadme, readErr)
- ret += fmt.Sprintf("<br>File %s not found", defaultReadme)
- }
- // 回退到 README.md
- if nil != readErr && readmeFilename != "README.md" && defaultReadme != "README.md" {
- readmeData, readErr = os.ReadFile(filepath.Join(installPath, "README.md"))
- if nil == readErr {
- ret, _ = renderLocalREADME(basePath, readmeData)
- return
- }
- logging.LogWarnf("read installed README.md failed: %s", readErr)
- ret += "<br>File README.md not found"
- }
- return
-}
-
-func renderREADME(repoURL string, mdData []byte) (ret string, err error) {
- mdData = bytes.TrimPrefix(mdData, []byte("\xef\xbb\xbf"))
- luteEngine := lute.New()
- luteEngine.SetSoftBreak2HardBreak(false)
- luteEngine.SetCodeSyntaxHighlight(false)
- linkBase := "https://cdn.jsdelivr.net/gh/" + strings.TrimPrefix(repoURL, "https://github.com/")
- luteEngine.SetLinkBase(linkBase)
- ret = luteEngine.Md2HTML(string(mdData))
- ret = util.LinkTarget(ret, linkBase)
- return
-}
-
-func renderLocalREADME(basePath string, mdData []byte) (ret string, err error) {
- mdData = bytes.TrimPrefix(mdData, []byte("\xef\xbb\xbf"))
- luteEngine := lute.New()
- luteEngine.SetSoftBreak2HardBreak(false)
- luteEngine.SetCodeSyntaxHighlight(false)
- linkBase := basePath
- luteEngine.SetLinkBase(linkBase)
- ret = luteEngine.Md2HTML(string(mdData))
- ret = util.LinkTarget(ret, linkBase)
- return
-}
-
var (
packageLocks = map[string]*sync.Mutex{}
packageLocksLock = sync.Mutex{}
@@ -779,54 +392,6 @@ func formatUpdated(updated string) (ret string) {
return
}
-type bazaarPackage struct {
- Name string `json:"name"`
- Downloads int `json:"downloads"`
-}
-
-var cachedBazaarIndex = map[string]*bazaarPackage{}
-var bazaarIndexCacheTime int64
-var bazaarIndexLock = sync.RWMutex{}
-
-// getBazaarIndexFromCache 仅从缓存获取 bazaar 索引,过期或无缓存时返回 nil
-func getBazaarIndexFromCache() (ret map[string]*bazaarPackage) {
- bazaarIndexLock.RLock()
- cacheTime := bazaarIndexCacheTime
- cached := cachedBazaarIndex
- hasData := 0 < len(cached)
- bazaarIndexLock.RUnlock()
- if util.RhyCacheDuration >= time.Now().Unix()-cacheTime && hasData {
- ret = cached
- } else {
- ret = nil
- }
- return
-}
-
-// getBazaarIndex 获取 bazaar 索引
-func getBazaarIndex(ctx context.Context) map[string]*bazaarPackage {
- if cached := getBazaarIndexFromCache(); nil != cached {
- return cached
- }
-
- bazaarIndexLock.Lock()
- defer bazaarIndexLock.Unlock()
-
- request := httpclient.NewBrowserRequest()
- u := util.BazaarStatServer + "/bazaar/index.json"
- resp, reqErr := request.SetContext(ctx).SetSuccessResult(&cachedBazaarIndex).Get(u)
- if nil != reqErr {
- logging.LogErrorf("get bazaar index [%s] failed: %s", u, reqErr)
- return cachedBazaarIndex
- }
- if 200 != resp.StatusCode {
- logging.LogErrorf("get bazaar index [%s] failed: %d", u, resp.StatusCode)
- return cachedBazaarIndex
- }
- bazaarIndexCacheTime = time.Now().Unix()
- return cachedBazaarIndex
-}
-
// Add marketplace package config item `minAppVersion` https://github.com/siyuan-note/siyuan/issues/8330
func disallowInstallBazaarPackage(pkg *Package) bool {
// 如果包没有指定 minAppVersion,则允许安装
diff --git a/kernel/bazaar/readme.go b/kernel/bazaar/readme.go
new file mode 100644
index 0000000000..ff3a350cbf
--- /dev/null
+++ b/kernel/bazaar/readme.go
@@ -0,0 +1,160 @@
+// 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 bazaar
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/88250/lute"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/util"
+ textUnicode "golang.org/x/text/encoding/unicode"
+ "golang.org/x/text/transform"
+)
+
+func GetPackageREADME(repoURL, repoHash, packageType string) (ret string) {
+ repoURLHash := repoURL + "@" + repoHash
+
+ stageIndexLock.RLock()
+ stageIndex := cachedStageIndex[packageType]
+ stageIndexLock.RUnlock()
+ if nil == stageIndex {
+ return
+ }
+
+ url := strings.TrimPrefix(repoURLHash, "https://github.com/")
+ var repo *StageRepo
+ for _, r := range stageIndex.Repos {
+ if r.URL == url {
+ repo = r
+ break
+ }
+ }
+ if nil == repo || nil == repo.Package {
+ return
+ }
+
+ readme := getPreferredReadme(repo.Package.Readme)
+
+ data, err := downloadPackage(repoURLHash+"/"+readme, false, "")
+ if err != nil {
+ ret = fmt.Sprintf("Load bazaar package's preferred README(%s) failed: %s", readme, err.Error())
+ // 回退到 Default README
+ var defaultReadme string
+ if len(repo.Package.Readme) > 0 {
+ defaultReadme = repo.Package.Readme["default"]
+ }
+ if "" == strings.TrimSpace(defaultReadme) {
+ defaultReadme = "README.md"
+ }
+ if readme != defaultReadme {
+ data, err = downloadPackage(repoURLHash+"/"+defaultReadme, false, "")
+ if err != nil {
+ ret += fmt.Sprintf("<br>Load bazaar package's default README(%s) failed: %s", defaultReadme, err.Error())
+ }
+ }
+ // 回退到 README.md
+ if err != nil && readme != "README.md" && defaultReadme != "README.md" {
+ data, err = downloadPackage(repoURLHash+"/README.md", false, "")
+ if err != nil {
+ ret += fmt.Sprintf("<br>Load bazaar package's README.md failed: %s", err.Error())
+ return
+ }
+ } else if err != nil {
+ return
+ }
+ }
+
+ if 2 < len(data) {
+ if 255 == data[0] && 254 == data[1] {
+ data, _, err = transform.Bytes(textUnicode.UTF16(textUnicode.LittleEndian, textUnicode.ExpectBOM).NewDecoder(), data)
+ } else if 254 == data[0] && 255 == data[1] {
+ data, _, err = transform.Bytes(textUnicode.UTF16(textUnicode.BigEndian, textUnicode.ExpectBOM).NewDecoder(), data)
+ }
+ }
+
+ ret, err = renderREADME(repoURL, data)
+ return
+}
+
+func loadInstalledReadme(installPath, basePath string, readme LocaleStrings) (ret string) {
+ readmeFilename := getPreferredReadme(readme)
+ readmeData, readErr := os.ReadFile(filepath.Join(installPath, readmeFilename))
+ if nil == readErr {
+ ret, _ = renderLocalREADME(basePath, readmeData)
+ return
+ }
+
+ logging.LogWarnf("read installed %s failed: %s", readmeFilename, readErr)
+ ret = fmt.Sprintf("File %s not found", readmeFilename)
+ // 回退到 Default README
+ var defaultReadme string
+ if len(readme) > 0 {
+ defaultReadme = strings.TrimSpace(readme["default"])
+ }
+ if "" == defaultReadme {
+ defaultReadme = "README.md"
+ }
+ if readmeFilename != defaultReadme {
+ readmeData, readErr = os.ReadFile(filepath.Join(installPath, defaultReadme))
+ if nil == readErr {
+ ret, _ = renderLocalREADME(basePath, readmeData)
+ return
+ }
+ logging.LogWarnf("read installed %s failed: %s", defaultReadme, readErr)
+ ret += fmt.Sprintf("<br>File %s not found", defaultReadme)
+ }
+ // 回退到 README.md
+ if nil != readErr && readmeFilename != "README.md" && defaultReadme != "README.md" {
+ readmeData, readErr = os.ReadFile(filepath.Join(installPath, "README.md"))
+ if nil == readErr {
+ ret, _ = renderLocalREADME(basePath, readmeData)
+ return
+ }
+ logging.LogWarnf("read installed README.md failed: %s", readErr)
+ ret += "<br>File README.md not found"
+ }
+ return
+}
+
+func renderREADME(repoURL string, mdData []byte) (ret string, err error) {
+ mdData = bytes.TrimPrefix(mdData, []byte("\xef\xbb\xbf"))
+ luteEngine := lute.New()
+ luteEngine.SetSoftBreak2HardBreak(false)
+ luteEngine.SetCodeSyntaxHighlight(false)
+ linkBase := "https://cdn.jsdelivr.net/gh/" + strings.TrimPrefix(repoURL, "https://github.com/")
+ luteEngine.SetLinkBase(linkBase)
+ ret = luteEngine.Md2HTML(string(mdData))
+ ret = util.LinkTarget(ret, linkBase)
+ return
+}
+
+func renderLocalREADME(basePath string, mdData []byte) (ret string, err error) {
+ mdData = bytes.TrimPrefix(mdData, []byte("\xef\xbb\xbf"))
+ luteEngine := lute.New()
+ luteEngine.SetSoftBreak2HardBreak(false)
+ luteEngine.SetCodeSyntaxHighlight(false)
+ linkBase := basePath
+ luteEngine.SetLinkBase(linkBase)
+ ret = luteEngine.Md2HTML(string(mdData))
+ ret = util.LinkTarget(ret, linkBase)
+ return
+}
diff --git a/kernel/bazaar/stage.go b/kernel/bazaar/stage.go
new file mode 100644
index 0000000000..6b90f4797a
--- /dev/null
+++ b/kernel/bazaar/stage.go
@@ -0,0 +1,332 @@
+// 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 bazaar
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/siyuan-note/httpclient"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "golang.org/x/mod/semver"
+ "golang.org/x/sync/singleflight"
+)
+
+var cachedStageIndex = map[string]*StageIndex{}
+var stageIndexCacheTime int64
+var stageIndexLock = sync.RWMutex{}
+
+type StageBazaarResult struct {
+ StageIndex *StageIndex // stage 索引
+ BazaarIndex map[string]*bazaarPackage // bazaar 索引
+ Online bool // online 状态
+ StageErr error // stage 错误
+}
+
+var stageBazaarFlight singleflight.Group
+var onlineCheckFlight singleflight.Group
+
+// getStageAndBazaar 获取 stage 索引和 bazaar 索引,相同 pkgType 的并发调用会合并为一次实际请求 (single-flight)
+func getStageAndBazaar(pkgType string) (result StageBazaarResult) {
+ key := "stageBazaar:" + pkgType
+ v, err, _ := stageBazaarFlight.Do(key, func() (interface{}, error) {
+ return getStageAndBazaar0(pkgType), nil
+ })
+ if err != nil {
+ return
+ }
+ result = v.(StageBazaarResult)
+ return
+}
+
+// getStageAndBazaar0 执行一次 stage 和 bazaar 索引拉取
+func getStageAndBazaar0(pkgType string) (result StageBazaarResult) {
+ stageIndex, stageErr := getStageIndexFromCache(pkgType)
+ bazaarIndex := getBazaarIndexFromCache()
+ if nil != stageIndex && nil != bazaarIndex {
+ // 两者都从缓存返回,不需要 online 检查
+ return StageBazaarResult{
+ StageIndex: stageIndex,
+ BazaarIndex: bazaarIndex,
+ Online: true,
+ StageErr: stageErr,
+ }
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var onlineResult bool
+ onlineDone := make(chan bool, 1)
+ wg := &sync.WaitGroup{}
+ wg.Add(3)
+ go func() {
+ defer wg.Done()
+ onlineResult = isBazzarOnline()
+ onlineDone <- true
+ }()
+ go func() {
+ defer wg.Done()
+ stageIndex, stageErr = getStageIndex(ctx, pkgType)
+ }()
+ go func() {
+ defer wg.Done()
+ bazaarIndex = getBazaarIndex(ctx)
+ }()
+
+ <-onlineDone
+ if !onlineResult {
+ // 不在线时立即取消其他请求并返回结果,避免等待 HTTP 请求超时
+ cancel()
+ return StageBazaarResult{
+ StageIndex: stageIndex,
+ BazaarIndex: bazaarIndex,
+ Online: false,
+ StageErr: stageErr,
+ }
+ }
+
+ // 在线时等待所有请求完成
+ wg.Wait()
+
+ return StageBazaarResult{
+ StageIndex: stageIndex,
+ BazaarIndex: bazaarIndex,
+ Online: onlineResult,
+ StageErr: stageErr,
+ }
+}
+
+// getStageIndexFromCache 仅从缓存获取 stage 索引,过期或无缓存时返回 nil
+func getStageIndexFromCache(pkgType string) (ret *StageIndex, err error) {
+ stageIndexLock.RLock()
+ cacheTime := stageIndexCacheTime
+ cached := cachedStageIndex[pkgType]
+ stageIndexLock.RUnlock()
+ if util.RhyCacheDuration >= time.Now().Unix()-cacheTime && nil != cached {
+ ret = cached
+ }
+ return
+}
+
+// getStageIndex 获取 stage 索引
+func getStageIndex(ctx context.Context, pkgType string) (ret *StageIndex, err error) {
+ if cached, cacheErr := getStageIndexFromCache(pkgType); nil != cached {
+ ret = cached
+ err = cacheErr
+ return
+ }
+
+ var rhyRet map[string]interface{}
+ rhyRet, err = util.GetRhyResult(ctx, false)
+ if nil != err {
+ return
+ }
+
+ stageIndexLock.Lock()
+ defer stageIndexLock.Unlock()
+
+ bazaarHash := rhyRet["bazaar"].(string)
+ ret = &StageIndex{}
+ request := httpclient.NewBrowserRequest()
+ u := util.BazaarOSSServer + "/bazaar@" + bazaarHash + "/stage/" + pkgType + ".json"
+ resp, reqErr := request.SetContext(ctx).SetSuccessResult(ret).Get(u)
+ if nil != reqErr {
+ logging.LogErrorf("get community stage index [%s] failed: %s", u, reqErr)
+ err = reqErr
+ return
+ }
+ if 200 != resp.StatusCode {
+ logging.LogErrorf("get community stage index [%s] failed: %d", u, resp.StatusCode)
+ err = errors.New("get stage index failed")
+ return
+ }
+
+ stageIndexCacheTime = time.Now().Unix()
+ cachedStageIndex[pkgType] = ret
+ return
+}
+
+func isOutdatedTheme(theme *Theme, bazaarThemes []*Theme) bool {
+ if !strings.HasPrefix(theme.URL, "https://github.com/") {
+ return false
+ }
+
+ repo := strings.TrimPrefix(theme.URL, "https://github.com/")
+ parts := strings.Split(repo, "/")
+ if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
+ return false
+ }
+
+ for _, pkg := range bazaarThemes {
+ if theme.Name == pkg.Name && 0 > semver.Compare("v"+theme.Version, "v"+pkg.Version) {
+ theme.RepoHash = pkg.RepoHash
+ return true
+ }
+ }
+ return false
+}
+
+func isOutdatedIcon(icon *Icon, bazaarIcons []*Icon) bool {
+ if !strings.HasPrefix(icon.URL, "https://github.com/") {
+ return false
+ }
+
+ repo := strings.TrimPrefix(icon.URL, "https://github.com/")
+ parts := strings.Split(repo, "/")
+ if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
+ return false
+ }
+
+ for _, pkg := range bazaarIcons {
+ if icon.Name == pkg.Name && 0 > semver.Compare("v"+icon.Version, "v"+pkg.Version) {
+ icon.RepoHash = pkg.RepoHash
+ return true
+ }
+ }
+ return false
+}
+
+func isOutdatedPlugin(plugin *Plugin, bazaarPlugins []*Plugin) bool {
+ if !strings.HasPrefix(plugin.URL, "https://github.com/") {
+ return false
+ }
+
+ repo := strings.TrimPrefix(plugin.URL, "https://github.com/")
+ parts := strings.Split(repo, "/")
+ if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
+ return false
+ }
+
+ for _, pkg := range bazaarPlugins {
+ if plugin.Name == pkg.Name && 0 > semver.Compare("v"+plugin.Version, "v"+pkg.Version) {
+ plugin.RepoHash = pkg.RepoHash
+ return true
+ }
+ }
+ return false
+}
+
+func isOutdatedWidget(widget *Widget, bazaarWidgets []*Widget) bool {
+ if !strings.HasPrefix(widget.URL, "https://github.com/") {
+ return false
+ }
+
+ repo := strings.TrimPrefix(widget.URL, "https://github.com/")
+ parts := strings.Split(repo, "/")
+ if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
+ return false
+ }
+
+ for _, pkg := range bazaarWidgets {
+ if widget.Name == pkg.Name && 0 > semver.Compare("v"+widget.Version, "v"+pkg.Version) {
+ widget.RepoHash = pkg.RepoHash
+ return true
+ }
+ }
+ return false
+}
+
+func isOutdatedTemplate(template *Template, bazaarTemplates []*Template) bool {
+ if !strings.HasPrefix(template.URL, "https://github.com/") {
+ return false
+ }
+
+ repo := strings.TrimPrefix(template.URL, "https://github.com/")
+ parts := strings.Split(repo, "/")
+ if 2 != len(parts) || "" == strings.TrimSpace(parts[1]) {
+ return false
+ }
+
+ for _, pkg := range bazaarTemplates {
+ if template.Name == pkg.Name && 0 > semver.Compare("v"+template.Version, "v"+pkg.Version) {
+ template.RepoHash = pkg.RepoHash
+ return true
+ }
+ }
+ return false
+}
+
+func isBazzarOnline() bool {
+ v, err, _ := onlineCheckFlight.Do("bazaarOnline", func() (interface{}, error) {
+ return isBazzarOnline0(), nil
+ })
+ if err != nil {
+ return false
+ }
+ return v.(bool)
+}
+
+func isBazzarOnline0() (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
+}
+
+type bazaarPackage struct {
+ Name string `json:"name"`
+ Downloads int `json:"downloads"`
+}
+
+var cachedBazaarIndex = map[string]*bazaarPackage{}
+var bazaarIndexCacheTime int64
+var bazaarIndexLock = sync.RWMutex{}
+
+// getBazaarIndexFromCache 仅从缓存获取 bazaar 索引,过期或无缓存时返回 nil
+func getBazaarIndexFromCache() (ret map[string]*bazaarPackage) {
+ bazaarIndexLock.RLock()
+ cacheTime := bazaarIndexCacheTime
+ cached := cachedBazaarIndex
+ hasData := 0 < len(cached)
+ bazaarIndexLock.RUnlock()
+ if util.RhyCacheDuration >= time.Now().Unix()-cacheTime && hasData {
+ ret = cached
+ } else {
+ ret = nil
+ }
+ return
+}
+
+// getBazaarIndex 获取 bazaar 索引
+func getBazaarIndex(ctx context.Context) map[string]*bazaarPackage {
+ if cached := getBazaarIndexFromCache(); nil != cached {
+ return cached
+ }
+
+ bazaarIndexLock.Lock()
+ defer bazaarIndexLock.Unlock()
+
+ request := httpclient.NewBrowserRequest()
+ u := util.BazaarStatServer + "/bazaar/index.json"
+ resp, reqErr := request.SetContext(ctx).SetSuccessResult(&cachedBazaarIndex).Get(u)
+ if nil != reqErr {
+ logging.LogErrorf("get bazaar index [%s] failed: %s", u, reqErr)
+ return cachedBazaarIndex
+ }
+ if 200 != resp.StatusCode {
+ logging.LogErrorf("get bazaar index [%s] failed: %d", u, resp.StatusCode)
+ return cachedBazaarIndex
+ }
+ bazaarIndexCacheTime = time.Now().Unix()
+ return cachedBazaarIndex
+}