working.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package util
  17. import (
  18. "errors"
  19. "flag"
  20. "fmt"
  21. "math/rand"
  22. "mime"
  23. "os"
  24. "path/filepath"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "time"
  30. "github.com/88250/gulu"
  31. figure "github.com/common-nighthawk/go-figure"
  32. "github.com/gofrs/flock"
  33. "github.com/siyuan-note/filelock"
  34. "github.com/siyuan-note/httpclient"
  35. "github.com/siyuan-note/logging"
  36. )
  37. // var Mode = "dev"
  38. var Mode = "prod"
  39. const (
  40. Ver = "2.10.0"
  41. IsInsider = false
  42. )
  43. var (
  44. bootProgress float64 // 启动进度,从 0 到 100
  45. bootDetails string // 启动细节描述
  46. HttpServing = false // 是否 HTTP 伺服已经可用
  47. )
  48. func Boot() {
  49. IncBootProgress(3, "Booting kernel...")
  50. rand.Seed(time.Now().UTC().UnixNano())
  51. initMime()
  52. initHttpClient()
  53. workspacePath := flag.String("workspace", "", "dir path of the workspace, default to ~/SiYuan/")
  54. wdPath := flag.String("wd", WorkingDir, "working directory of SiYuan")
  55. port := flag.String("port", "0", "port of the HTTP server")
  56. readOnly := flag.String("readonly", "false", "read-only mode")
  57. accessAuthCode := flag.String("accessAuthCode", "", "access auth code")
  58. ssl := flag.Bool("ssl", false, "for https and wss")
  59. lang := flag.String("lang", "", "zh_CN/zh_CHT/en_US/fr_FR/es_ES")
  60. mode := flag.String("mode", "prod", "dev/prod")
  61. flag.Parse()
  62. if "" != *wdPath {
  63. WorkingDir = *wdPath
  64. }
  65. if "" != *lang {
  66. Lang = *lang
  67. }
  68. Mode = *mode
  69. ServerPort = *port
  70. ReadOnly, _ = strconv.ParseBool(*readOnly)
  71. AccessAuthCode = *accessAuthCode
  72. Container = ContainerStd
  73. if isRunningInDockerContainer() {
  74. Container = ContainerDocker
  75. }
  76. if ContainerStd != Container {
  77. ServerPort = FixedPort
  78. }
  79. msStoreFilePath := filepath.Join(WorkingDir, "ms-store")
  80. ISMicrosoftStore = gulu.File.IsExist(msStoreFilePath)
  81. UserAgent = UserAgent + " " + Container + "/" + runtime.GOOS
  82. httpclient.SetUserAgent(UserAgent)
  83. initWorkspaceDir(*workspacePath)
  84. SSL = *ssl
  85. LogPath = filepath.Join(TempDir, "siyuan.log")
  86. logging.SetLogPath(LogPath)
  87. // 工作空间仅允许被一个内核进程伺服
  88. tryLockWorkspace()
  89. AppearancePath = filepath.Join(ConfDir, "appearance")
  90. if "dev" == Mode {
  91. ThemesPath = filepath.Join(WorkingDir, "appearance", "themes")
  92. IconsPath = filepath.Join(WorkingDir, "appearance", "icons")
  93. } else {
  94. ThemesPath = filepath.Join(AppearancePath, "themes")
  95. IconsPath = filepath.Join(AppearancePath, "icons")
  96. }
  97. initPathDir()
  98. bootBanner := figure.NewColorFigure("SiYuan", "isometric3", "green", true)
  99. logging.LogInfof("\n" + bootBanner.String())
  100. logBootInfo()
  101. }
  102. func setBootDetails(details string) {
  103. bootDetails = "v" + Ver + " " + details
  104. }
  105. func SetBootDetails(details string) {
  106. if 100 <= bootProgress {
  107. return
  108. }
  109. setBootDetails(details)
  110. }
  111. func IncBootProgress(progress float64, details string) {
  112. if 100 <= bootProgress {
  113. return
  114. }
  115. bootProgress += progress
  116. setBootDetails(details)
  117. }
  118. func IsBooted() bool {
  119. return 100 <= bootProgress
  120. }
  121. func GetBootProgressDetails() (float64, string) {
  122. return bootProgress, bootDetails
  123. }
  124. func GetBootProgress() float64 {
  125. return bootProgress
  126. }
  127. func SetBooted() {
  128. setBootDetails("Finishing boot...")
  129. bootProgress = 100
  130. logging.LogInfof("kernel booted")
  131. }
  132. var (
  133. HomeDir, _ = gulu.OS.Home()
  134. WorkingDir, _ = os.Getwd()
  135. WorkspaceDir string // 工作空间目录路径
  136. WorkspaceLock *flock.Flock // 工作空间锁
  137. ConfDir string // 配置目录路径
  138. DataDir string // 数据目录路径
  139. RepoDir string // 仓库目录路径
  140. HistoryDir string // 数据历史目录路径
  141. TempDir string // 临时目录路径
  142. LogPath string // 配置目录下的日志文件 siyuan.log 路径
  143. DBName = "siyuan.db" // SQLite 数据库文件名
  144. DBPath string // SQLite 数据库文件路径
  145. HistoryDBPath string // SQLite 历史数据库文件路径
  146. AssetContentDBPath string // SQLite 资源文件内容数据库文件路径
  147. BlockTreePath string // 区块树文件路径
  148. AppearancePath string // 配置目录下的外观目录 appearance/ 路径
  149. ThemesPath string // 配置目录下的外观目录下的 themes/ 路径
  150. IconsPath string // 配置目录下的外观目录下的 icons/ 路径
  151. SnippetsPath string // 数据目录下的 snippets/ 路径
  152. UIProcessIDs = sync.Map{} // UI 进程 ID
  153. )
  154. func initWorkspaceDir(workspaceArg string) {
  155. userHomeConfDir := filepath.Join(HomeDir, ".config", "siyuan")
  156. workspaceConf := filepath.Join(userHomeConfDir, "workspace.json")
  157. logging.SetLogPath(filepath.Join(userHomeConfDir, "kernel.log"))
  158. if !gulu.File.IsExist(workspaceConf) {
  159. if err := os.MkdirAll(userHomeConfDir, 0755); nil != err && !os.IsExist(err) {
  160. logging.LogErrorf("create user home conf folder [%s] failed: %s", userHomeConfDir, err)
  161. os.Exit(logging.ExitCodeInitWorkspaceErr)
  162. }
  163. }
  164. defaultWorkspaceDir := filepath.Join(HomeDir, "SiYuan")
  165. if gulu.OS.IsWindows() {
  166. // 改进 Windows 端默认工作空间路径 https://github.com/siyuan-note/siyuan/issues/5622
  167. if userProfile := os.Getenv("USERPROFILE"); "" != userProfile {
  168. defaultWorkspaceDir = filepath.Join(userProfile, "SiYuan")
  169. }
  170. }
  171. var workspacePaths []string
  172. if !gulu.File.IsExist(workspaceConf) {
  173. WorkspaceDir = defaultWorkspaceDir
  174. } else {
  175. workspacePaths, _ = ReadWorkspacePaths()
  176. if 0 < len(workspacePaths) {
  177. // 取最后一个(也就是最近打开的)工作空间
  178. WorkspaceDir = workspacePaths[len(workspacePaths)-1]
  179. } else {
  180. WorkspaceDir = defaultWorkspaceDir
  181. }
  182. }
  183. if "" != workspaceArg {
  184. WorkspaceDir = workspaceArg
  185. }
  186. if !gulu.File.IsDir(WorkspaceDir) {
  187. logging.LogWarnf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  188. if err := os.MkdirAll(defaultWorkspaceDir, 0755); nil != err && !os.IsExist(err) {
  189. logging.LogErrorf("create default workspace folder [%s] failed: %s", defaultWorkspaceDir, err)
  190. os.Exit(logging.ExitCodeInitWorkspaceErr)
  191. }
  192. WorkspaceDir = defaultWorkspaceDir
  193. }
  194. workspacePaths = append(workspacePaths, WorkspaceDir)
  195. if err := WriteWorkspacePaths(workspacePaths); nil != err {
  196. logging.LogErrorf("write workspace conf [%s] failed: %s", workspaceConf, err)
  197. os.Exit(logging.ExitCodeInitWorkspaceErr)
  198. }
  199. ConfDir = filepath.Join(WorkspaceDir, "conf")
  200. DataDir = filepath.Join(WorkspaceDir, "data")
  201. RepoDir = filepath.Join(WorkspaceDir, "repo")
  202. HistoryDir = filepath.Join(WorkspaceDir, "history")
  203. TempDir = filepath.Join(WorkspaceDir, "temp")
  204. osTmpDir := filepath.Join(TempDir, "os")
  205. os.RemoveAll(osTmpDir)
  206. if err := os.MkdirAll(osTmpDir, 0755); nil != err {
  207. logging.LogErrorf("create os tmp dir [%s] failed: %s", osTmpDir, err)
  208. os.Exit(logging.ExitCodeInitWorkspaceErr)
  209. }
  210. os.RemoveAll(filepath.Join(TempDir, "repo"))
  211. os.Setenv("TMPDIR", osTmpDir)
  212. os.Setenv("TEMP", osTmpDir)
  213. os.Setenv("TMP", osTmpDir)
  214. DBPath = filepath.Join(TempDir, DBName)
  215. HistoryDBPath = filepath.Join(TempDir, "history.db")
  216. AssetContentDBPath = filepath.Join(TempDir, "asset_content.db")
  217. BlockTreePath = filepath.Join(TempDir, "blocktree")
  218. SnippetsPath = filepath.Join(DataDir, "snippets")
  219. }
  220. func ReadWorkspacePaths() (ret []string, err error) {
  221. ret = []string{}
  222. workspaceConf := filepath.Join(HomeDir, ".config", "siyuan", "workspace.json")
  223. data, err := os.ReadFile(workspaceConf)
  224. if nil != err {
  225. msg := fmt.Sprintf("read workspace conf [%s] failed: %s", workspaceConf, err)
  226. logging.LogErrorf(msg)
  227. err = errors.New(msg)
  228. return
  229. }
  230. if err = gulu.JSON.UnmarshalJSON(data, &ret); nil != err {
  231. msg := fmt.Sprintf("unmarshal workspace conf [%s] failed: %s", workspaceConf, err)
  232. logging.LogErrorf(msg)
  233. err = errors.New(msg)
  234. return
  235. }
  236. var tmp []string
  237. for _, d := range ret {
  238. d = strings.TrimRight(d, " \t\n") // 去掉工作空间路径尾部空格 https://github.com/siyuan-note/siyuan/issues/6353
  239. if gulu.File.IsDir(d) {
  240. tmp = append(tmp, d)
  241. }
  242. }
  243. ret = tmp
  244. ret = gulu.Str.RemoveDuplicatedElem(ret)
  245. return
  246. }
  247. func WriteWorkspacePaths(workspacePaths []string) (err error) {
  248. workspacePaths = gulu.Str.RemoveDuplicatedElem(workspacePaths)
  249. workspaceConf := filepath.Join(HomeDir, ".config", "siyuan", "workspace.json")
  250. data, err := gulu.JSON.MarshalJSON(workspacePaths)
  251. if nil != err {
  252. msg := fmt.Sprintf("marshal workspace conf [%s] failed: %s", workspaceConf, err)
  253. logging.LogErrorf(msg)
  254. err = errors.New(msg)
  255. return
  256. }
  257. if err = filelock.WriteFile(workspaceConf, data); nil != err {
  258. msg := fmt.Sprintf("write workspace conf [%s] failed: %s", workspaceConf, err)
  259. logging.LogErrorf(msg)
  260. err = errors.New(msg)
  261. return
  262. }
  263. return
  264. }
  265. var (
  266. ServerPort = "0" // HTTP/WebSocket 端口,0 为使用随机端口
  267. ReadOnly bool
  268. AccessAuthCode string
  269. Lang = ""
  270. Container string // docker, android, ios, std
  271. ISMicrosoftStore bool // 桌面端是否是微软商店版
  272. )
  273. const (
  274. ContainerStd = "std" // 桌面端
  275. ContainerDocker = "docker" // Docker 容器端
  276. ContainerAndroid = "android" // Android 端
  277. ContainerIOS = "ios" // iOS 端
  278. LocalHost = "127.0.0.1" // 伺服地址
  279. FixedPort = "6806" // 固定端口
  280. )
  281. func initPathDir() {
  282. if err := os.MkdirAll(ConfDir, 0755); nil != err && !os.IsExist(err) {
  283. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create conf folder [%s] failed: %s", ConfDir, err)
  284. }
  285. if err := os.MkdirAll(DataDir, 0755); nil != err && !os.IsExist(err) {
  286. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data folder [%s] failed: %s", DataDir, err)
  287. }
  288. if err := os.MkdirAll(TempDir, 0755); nil != err && !os.IsExist(err) {
  289. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create temp folder [%s] failed: %s", TempDir, err)
  290. }
  291. assets := filepath.Join(DataDir, "assets")
  292. if err := os.MkdirAll(assets, 0755); nil != err && !os.IsExist(err) {
  293. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data assets folder [%s] failed: %s", assets, err)
  294. }
  295. templates := filepath.Join(DataDir, "templates")
  296. if err := os.MkdirAll(templates, 0755); nil != err && !os.IsExist(err) {
  297. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data templates folder [%s] failed: %s", templates, err)
  298. }
  299. widgets := filepath.Join(DataDir, "widgets")
  300. if err := os.MkdirAll(widgets, 0755); nil != err && !os.IsExist(err) {
  301. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data widgets folder [%s] failed: %s", widgets, err)
  302. }
  303. plugins := filepath.Join(DataDir, "plugins")
  304. if err := os.MkdirAll(plugins, 0755); nil != err && !os.IsExist(err) {
  305. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data plugins folder [%s] failed: %s", widgets, err)
  306. }
  307. emojis := filepath.Join(DataDir, "emojis")
  308. if err := os.MkdirAll(emojis, 0755); nil != err && !os.IsExist(err) {
  309. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data emojis folder [%s] failed: %s", widgets, err)
  310. }
  311. // Support directly access `data/public/*` contents via URL link https://github.com/siyuan-note/siyuan/issues/8593
  312. public := filepath.Join(DataDir, "public")
  313. if err := os.MkdirAll(public, 0755); nil != err && !os.IsExist(err) {
  314. logging.LogFatalf(logging.ExitCodeInitWorkspaceErr, "create data public folder [%s] failed: %s", widgets, err)
  315. }
  316. }
  317. func initMime() {
  318. // 在某版本的 Windows 10 操作系统上界面样式异常问题
  319. // https://github.com/siyuan-note/siyuan/issues/247
  320. // https://github.com/siyuan-note/siyuan/issues/3813
  321. mime.AddExtensionType(".css", "text/css")
  322. mime.AddExtensionType(".js", "application/x-javascript")
  323. mime.AddExtensionType(".json", "application/json")
  324. mime.AddExtensionType(".html", "text/html")
  325. // 某些系统上下载资源文件后打开是 zip
  326. // https://github.com/siyuan-note/siyuan/issues/6347
  327. mime.AddExtensionType(".doc", "application/msword")
  328. mime.AddExtensionType(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
  329. mime.AddExtensionType(".xls", "application/vnd.ms-excel")
  330. mime.AddExtensionType(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  331. mime.AddExtensionType(".dwg", "image/x-dwg")
  332. mime.AddExtensionType(".dxf", "image/x-dxf")
  333. mime.AddExtensionType(".dwf", "drawing/x-dwf")
  334. mime.AddExtensionType(".pdf", "application/pdf")
  335. // 文档数据文件
  336. mime.AddExtensionType(".sy", "application/json")
  337. }
  338. func GetDataAssetsAbsPath() (ret string) {
  339. ret = filepath.Join(DataDir, "assets")
  340. var err error
  341. stat, err := os.Lstat(ret)
  342. if nil != err {
  343. logging.LogErrorf("stat assets failed: %s", err)
  344. return
  345. }
  346. if 0 != stat.Mode()&os.ModeSymlink {
  347. // 跟随符号链接 https://github.com/siyuan-note/siyuan/issues/5480
  348. ret, err = os.Readlink(ret)
  349. if nil != err {
  350. logging.LogErrorf("read assets link failed: %s", err)
  351. }
  352. }
  353. return
  354. }
  355. func tryLockWorkspace() {
  356. WorkspaceLock = flock.New(filepath.Join(WorkspaceDir, ".lock"))
  357. ok, err := WorkspaceLock.TryLock()
  358. if ok {
  359. return
  360. }
  361. if nil != err {
  362. logging.LogErrorf("lock workspace [%s] failed: %s", WorkspaceDir, err)
  363. } else {
  364. logging.LogErrorf("lock workspace [%s] failed", WorkspaceDir)
  365. }
  366. os.Exit(logging.ExitCodeWorkspaceLocked)
  367. }
  368. func IsWorkspaceLocked(workspacePath string) bool {
  369. if !gulu.File.IsDir(workspacePath) {
  370. return false
  371. }
  372. lockFilePath := filepath.Join(workspacePath, ".lock")
  373. if !gulu.File.IsExist(lockFilePath) {
  374. return false
  375. }
  376. f := flock.New(lockFilePath)
  377. defer f.Unlock()
  378. ok, _ := f.TryLock()
  379. if ok {
  380. return false
  381. }
  382. return true
  383. }
  384. func UnlockWorkspace() {
  385. if nil == WorkspaceLock {
  386. return
  387. }
  388. if err := WorkspaceLock.Unlock(); nil != err {
  389. logging.LogErrorf("unlock workspace [%s] failed: %s", WorkspaceDir, err)
  390. return
  391. }
  392. if err := os.Remove(filepath.Join(WorkspaceDir, ".lock")); nil != err {
  393. logging.LogErrorf("remove workspace lock failed: %s", err)
  394. return
  395. }
  396. }