working.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // SiYuan - Build Your Eternal Digital Garden
  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. "bytes"
  19. "flag"
  20. "log"
  21. "math/rand"
  22. "mime"
  23. "os"
  24. "os/exec"
  25. "path/filepath"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "time"
  30. "github.com/88250/gulu"
  31. figure "github.com/common-nighthawk/go-figure"
  32. goPS "github.com/mitchellh/go-ps"
  33. "github.com/siyuan-note/httpclient"
  34. "github.com/siyuan-note/logging"
  35. )
  36. // var Mode = "dev"
  37. var Mode = "prod"
  38. const (
  39. Ver = "2.4.7"
  40. IsInsider = false
  41. )
  42. var (
  43. bootProgress float64 // 启动进度,从 0 到 100
  44. bootDetails string // 启动细节描述
  45. HttpServing = false // 是否 HTTP 伺服已经可用
  46. )
  47. func Boot() {
  48. IncBootProgress(3, "Booting...")
  49. rand.Seed(time.Now().UTC().UnixNano())
  50. initMime()
  51. workspacePath := flag.String("workspace", "", "dir path of the workspace, default to ~/Documents/SiYuan/")
  52. wdPath := flag.String("wd", WorkingDir, "working directory of SiYuan")
  53. servePath := flag.String("servePath", "", "obsoleted https://github.com/siyuan-note/siyuan/issues/4647")
  54. _ = servePath
  55. port := flag.String("port", "0", "port of the HTTP server")
  56. resident := flag.String("resident", "true", "resident memory even if no active session")
  57. readOnly := flag.String("readonly", "false", "read-only mode")
  58. accessAuthCode := flag.String("accessAuthCode", "", "access auth code")
  59. ssl := flag.Bool("ssl", false, "for https and wss")
  60. lang := flag.String("lang", "", "zh_CN/zh_CHT/en_US/fr_FR/es_ES")
  61. mode := flag.String("mode", "prod", "dev/prod")
  62. flag.Parse()
  63. if "" != *wdPath {
  64. WorkingDir = *wdPath
  65. }
  66. if "" != *lang {
  67. Lang = *lang
  68. }
  69. Mode = *mode
  70. Resident, _ = strconv.ParseBool(*resident)
  71. ServerPort = *port
  72. ReadOnly, _ = strconv.ParseBool(*readOnly)
  73. AccessAuthCode = *accessAuthCode
  74. Container = ContainerStd
  75. if isRunningInDockerContainer() {
  76. Container = ContainerDocker
  77. }
  78. if ContainerStd != Container || "dev" == Mode {
  79. ServerPort = FixedPort
  80. }
  81. msStoreFilePath := filepath.Join(WorkingDir, "ms-store")
  82. ISMicrosoftStore = gulu.File.IsExist(msStoreFilePath)
  83. UserAgent = UserAgent + " " + Container
  84. httpclient.SetUserAgent(UserAgent)
  85. initWorkspaceDir(*workspacePath)
  86. SSL = *ssl
  87. LogPath = filepath.Join(TempDir, "siyuan.log")
  88. logging.SetLogPath(LogPath)
  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. go initPandoc()
  99. bootBanner := figure.NewColorFigure("SiYuan", "isometric3", "green", true)
  100. logging.LogInfof("\n" + bootBanner.String())
  101. logBootInfo()
  102. }
  103. func setBootDetails(details string) {
  104. bootDetails = "v" + Ver + " " + details
  105. }
  106. func SetBootDetails(details string) {
  107. if 100 <= bootProgress {
  108. return
  109. }
  110. setBootDetails(details)
  111. }
  112. func IncBootProgress(progress float64, details string) {
  113. if 100 <= bootProgress {
  114. return
  115. }
  116. bootProgress += progress
  117. setBootDetails(details)
  118. }
  119. func IsBooted() bool {
  120. return 100 <= bootProgress
  121. }
  122. func GetBootProgressDetails() (float64, string) {
  123. return bootProgress, bootDetails
  124. }
  125. func GetBootProgress() float64 {
  126. return bootProgress
  127. }
  128. func SetBooted() {
  129. setBootDetails("Finishing boot...")
  130. bootProgress = 100
  131. logging.LogInfof("kernel booted")
  132. }
  133. var (
  134. HomeDir, _ = gulu.OS.Home()
  135. WorkingDir, _ = os.Getwd()
  136. WorkspaceDir string // 工作空间目录路径
  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. BlockTreePath string // 区块树文件路径
  147. PandocBinPath string // Pandoc 可执行文件路径
  148. AppearancePath string // 配置目录下的外观目录 appearance/ 路径
  149. ThemesPath string // 配置目录下的外观目录下的 themes/ 路径
  150. IconsPath string // 配置目录下的外观目录下的 icons/ 路径
  151. AndroidNativeLibDir string // Android 库路径
  152. AndroidPrivateDataDir string // Android 私有数据路径
  153. UIProcessIDs = sync.Map{} // UI 进程 ID
  154. IsNewbie bool // 是否是第一次安装
  155. )
  156. func initWorkspaceDir(workspaceArg string) {
  157. userHomeConfDir := filepath.Join(HomeDir, ".config", "siyuan")
  158. workspaceConf := filepath.Join(userHomeConfDir, "workspace.json")
  159. if !gulu.File.IsExist(workspaceConf) {
  160. IsNewbie = ContainerStd == Container // 只有桌面端需要设置新手标识,前端自动挂载帮助文档
  161. if err := os.MkdirAll(userHomeConfDir, 0755); nil != err && !os.IsExist(err) {
  162. log.Printf("create user home conf folder [%s] failed: %s", userHomeConfDir, err)
  163. os.Exit(ExitCodeCreateConfDirErr)
  164. }
  165. }
  166. defaultWorkspaceDir := filepath.Join(HomeDir, "Documents", "SiYuan")
  167. if gulu.OS.IsWindows() {
  168. // 改进 Windows 端默认工作空间路径 https://github.com/siyuan-note/siyuan/issues/5622
  169. if userProfile := os.Getenv("USERPROFILE"); "" != userProfile {
  170. defaultWorkspaceDir = filepath.Join(userProfile, "Documents", "SiYuan")
  171. }
  172. }
  173. var workspacePaths []string
  174. if !gulu.File.IsExist(workspaceConf) {
  175. WorkspaceDir = defaultWorkspaceDir
  176. if "" != workspaceArg {
  177. WorkspaceDir = workspaceArg
  178. }
  179. if !gulu.File.IsDir(WorkspaceDir) {
  180. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  181. WorkspaceDir = defaultWorkspaceDir
  182. }
  183. workspacePaths = append(workspacePaths, WorkspaceDir)
  184. } else {
  185. data, err := os.ReadFile(workspaceConf)
  186. if err = gulu.JSON.UnmarshalJSON(data, &workspacePaths); nil != err {
  187. log.Printf("unmarshal workspace conf [%s] failed: %s", workspaceConf, err)
  188. }
  189. tmp := workspacePaths[:0]
  190. for _, d := range workspacePaths {
  191. d = strings.TrimRight(d, " \t\n") // 去掉工作空间路径尾部空格 https://github.com/siyuan-note/siyuan/issues/6353
  192. if gulu.File.IsDir(d) {
  193. tmp = append(tmp, d)
  194. }
  195. }
  196. workspacePaths = tmp
  197. if 0 < len(workspacePaths) {
  198. WorkspaceDir = workspacePaths[len(workspacePaths)-1]
  199. if "" != workspaceArg {
  200. WorkspaceDir = workspaceArg
  201. }
  202. if !gulu.File.IsDir(WorkspaceDir) {
  203. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  204. WorkspaceDir = defaultWorkspaceDir
  205. }
  206. workspacePaths[len(workspacePaths)-1] = WorkspaceDir
  207. } else {
  208. WorkspaceDir = defaultWorkspaceDir
  209. if "" != workspaceArg {
  210. WorkspaceDir = workspaceArg
  211. }
  212. if !gulu.File.IsDir(WorkspaceDir) {
  213. log.Printf("use the default workspace [%s] since the specified workspace [%s] is not a dir", WorkspaceDir, defaultWorkspaceDir)
  214. WorkspaceDir = defaultWorkspaceDir
  215. }
  216. workspacePaths = append(workspacePaths, WorkspaceDir)
  217. }
  218. }
  219. if data, err := gulu.JSON.MarshalJSON(workspacePaths); nil == err {
  220. if err = os.WriteFile(workspaceConf, data, 0644); nil != err {
  221. log.Fatalf("write workspace conf [%s] failed: %s", workspaceConf, err)
  222. }
  223. } else {
  224. log.Fatalf("marshal workspace conf [%s] failed: %s", workspaceConf, err)
  225. }
  226. ConfDir = filepath.Join(WorkspaceDir, "conf")
  227. DataDir = filepath.Join(WorkspaceDir, "data")
  228. RepoDir = filepath.Join(WorkspaceDir, "repo")
  229. HistoryDir = filepath.Join(WorkspaceDir, "history")
  230. TempDir = filepath.Join(WorkspaceDir, "temp")
  231. osTmpDir := filepath.Join(TempDir, "os")
  232. os.RemoveAll(osTmpDir)
  233. if err := os.MkdirAll(osTmpDir, 0755); nil != err {
  234. log.Fatalf("create os tmp dir [%s] failed: %s", osTmpDir, err)
  235. }
  236. os.RemoveAll(filepath.Join(TempDir, "repo"))
  237. os.Setenv("TMPDIR", osTmpDir)
  238. os.Setenv("TEMP", osTmpDir)
  239. os.Setenv("TMP", osTmpDir)
  240. DBPath = filepath.Join(TempDir, DBName)
  241. HistoryDBPath = filepath.Join(TempDir, "history.db")
  242. BlockTreePath = filepath.Join(TempDir, "blocktree.msgpack")
  243. }
  244. var (
  245. ServerPort = "0" // HTTP/WebSocket 端口,0 为使用随机端口
  246. Resident bool
  247. ReadOnly bool
  248. AccessAuthCode string
  249. Lang = ""
  250. Container string // docker, android, ios, std
  251. ISMicrosoftStore bool // 桌面端是否是微软商店版
  252. )
  253. const (
  254. ContainerStd = "std" // 桌面端
  255. ContainerDocker = "docker" // Docker 容器端
  256. ContainerAndroid = "android" // Android 端
  257. ContainerIOS = "ios" // iOS 端
  258. LocalHost = "siyuan.localhost" // 本地域名,由操作系统自动解析到 127.0.0.1
  259. FixedPort = "6806" // 固定端口
  260. )
  261. func initPathDir() {
  262. if err := os.MkdirAll(ConfDir, 0755); nil != err && !os.IsExist(err) {
  263. log.Fatalf("create conf folder [%s] failed: %s", ConfDir, err)
  264. }
  265. if err := os.MkdirAll(DataDir, 0755); nil != err && !os.IsExist(err) {
  266. log.Fatalf("create data folder [%s] failed: %s", DataDir, err)
  267. }
  268. if err := os.MkdirAll(TempDir, 0755); nil != err && !os.IsExist(err) {
  269. log.Fatalf("create temp folder [%s] failed: %s", TempDir, err)
  270. }
  271. assets := filepath.Join(DataDir, "assets")
  272. if err := os.MkdirAll(assets, 0755); nil != err && !os.IsExist(err) {
  273. log.Fatalf("create data assets folder [%s] failed: %s", assets, err)
  274. }
  275. templates := filepath.Join(DataDir, "templates")
  276. if err := os.MkdirAll(templates, 0755); nil != err && !os.IsExist(err) {
  277. log.Fatalf("create data templates folder [%s] failed: %s", templates, err)
  278. }
  279. widgets := filepath.Join(DataDir, "widgets")
  280. if err := os.MkdirAll(widgets, 0755); nil != err && !os.IsExist(err) {
  281. log.Fatalf("create data widgets folder [%s] failed: %s", widgets, err)
  282. }
  283. emojis := filepath.Join(DataDir, "emojis")
  284. if err := os.MkdirAll(emojis, 0755); nil != err && !os.IsExist(err) {
  285. log.Fatalf("create data emojis folder [%s] failed: %s", widgets, err)
  286. }
  287. }
  288. func initMime() {
  289. // 在某版本的 Windows 10 操作系统上界面样式异常问题
  290. // https://github.com/siyuan-note/siyuan/issues/247
  291. // https://github.com/siyuan-note/siyuan/issues/3813
  292. mime.AddExtensionType(".css", "text/css")
  293. mime.AddExtensionType(".js", "application/x-javascript")
  294. mime.AddExtensionType(".json", "application/json")
  295. mime.AddExtensionType(".html", "text/html")
  296. // 某些系统上下载资源文件后打开是 zip
  297. // https://github.com/siyuan-note/siyuan/issues/6347
  298. mime.AddExtensionType(".doc", "application/msword")
  299. mime.AddExtensionType(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
  300. mime.AddExtensionType(".xls", "application/vnd.ms-excel")
  301. mime.AddExtensionType(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  302. mime.AddExtensionType(".dwg", "image/x-dwg")
  303. mime.AddExtensionType(".dxf", "image/x-dxf")
  304. mime.AddExtensionType(".dwf", "drawing/x-dwf")
  305. mime.AddExtensionType(".pdf", "application/pdf")
  306. }
  307. func KillByPort(port string) {
  308. if pid := PidByPort(port); "" != pid {
  309. pidInt, _ := strconv.Atoi(pid)
  310. proc, _ := goPS.FindProcess(pidInt)
  311. var name string
  312. if nil != proc {
  313. name = proc.Executable()
  314. }
  315. Kill(pid)
  316. logging.LogInfof("killed process [name=%s, pid=%s]", name, pid)
  317. }
  318. }
  319. func Kill(pid string) {
  320. var kill *exec.Cmd
  321. if gulu.OS.IsWindows() {
  322. kill = exec.Command("cmd", "/c", "TASKKILL /F /PID "+pid)
  323. } else {
  324. kill = exec.Command("kill", "-9", pid)
  325. }
  326. gulu.CmdAttr(kill)
  327. kill.CombinedOutput()
  328. }
  329. func PidByPort(port string) (ret string) {
  330. if gulu.OS.IsWindows() {
  331. cmd := exec.Command("cmd", "/c", "netstat -ano | findstr "+port)
  332. gulu.CmdAttr(cmd)
  333. data, err := cmd.CombinedOutput()
  334. if nil != err {
  335. logging.LogErrorf("netstat failed: %s", err)
  336. return
  337. }
  338. output := string(data)
  339. lines := strings.Split(output, "\n")
  340. for _, l := range lines {
  341. if strings.Contains(l, "LISTENING") {
  342. l = l[strings.Index(l, "LISTENING")+len("LISTENING"):]
  343. l = strings.TrimSpace(l)
  344. ret = l
  345. return
  346. }
  347. }
  348. return
  349. }
  350. cmd := exec.Command("lsof", "-Fp", "-i", ":"+port)
  351. gulu.CmdAttr(cmd)
  352. data, err := cmd.CombinedOutput()
  353. if nil != err {
  354. logging.LogErrorf("lsof failed: %s", err)
  355. return
  356. }
  357. output := string(data)
  358. lines := strings.Split(output, "\n")
  359. for _, l := range lines {
  360. if strings.HasPrefix(l, "p") {
  361. l = l[1:]
  362. ret = l
  363. return
  364. }
  365. }
  366. return
  367. }
  368. func initPandoc() {
  369. if ContainerStd != Container {
  370. return
  371. }
  372. pandocDir := filepath.Join(TempDir, "pandoc")
  373. if gulu.OS.IsWindows() {
  374. PandocBinPath = filepath.Join(pandocDir, "bin", "pandoc.exe")
  375. } else if gulu.OS.IsDarwin() || gulu.OS.IsLinux() {
  376. PandocBinPath = filepath.Join(pandocDir, "bin", "pandoc")
  377. }
  378. pandocVer := getPandocVer(PandocBinPath)
  379. if "" != pandocVer {
  380. logging.LogInfof("built-in pandoc [ver=%s, bin=%s]", pandocVer, PandocBinPath)
  381. return
  382. }
  383. pandocZip := filepath.Join(WorkingDir, "pandoc.zip")
  384. if "dev" == Mode {
  385. if gulu.OS.IsWindows() {
  386. pandocZip = filepath.Join(WorkingDir, "pandoc/pandoc-windows-amd64.zip")
  387. } else if gulu.OS.IsDarwin() {
  388. pandocZip = filepath.Join(WorkingDir, "pandoc/pandoc-darwin-amd64.zip")
  389. } else if gulu.OS.IsLinux() {
  390. pandocZip = filepath.Join(WorkingDir, "pandoc/pandoc-linux-amd64.zip")
  391. }
  392. }
  393. if err := gulu.Zip.Unzip(pandocZip, pandocDir); nil != err {
  394. logging.LogErrorf("unzip pandoc failed: %s", err)
  395. return
  396. }
  397. if gulu.OS.IsDarwin() || gulu.OS.IsLinux() {
  398. exec.Command("chmod", "+x", PandocBinPath).CombinedOutput()
  399. }
  400. pandocVer = getPandocVer(PandocBinPath)
  401. logging.LogInfof("initialized built-in pandoc [ver=%s, bin=%s]", pandocVer, PandocBinPath)
  402. }
  403. func getPandocVer(binPath string) (ret string) {
  404. if "" == binPath {
  405. return
  406. }
  407. cmd := exec.Command(binPath, "--version")
  408. gulu.CmdAttr(cmd)
  409. data, err := cmd.CombinedOutput()
  410. if nil == err && strings.HasPrefix(string(data), "pandoc") {
  411. parts := bytes.Split(data, []byte("\n"))
  412. if 0 < len(parts) {
  413. ret = strings.TrimPrefix(string(parts[0]), "pandoc")
  414. ret = strings.ReplaceAll(ret, ".exe", "")
  415. ret = strings.TrimSpace(ret)
  416. }
  417. return
  418. }
  419. return
  420. }
  421. func IsValidPandocBin(binPath string) bool {
  422. if "" == binPath {
  423. return false
  424. }
  425. cmd := exec.Command(binPath, "--version")
  426. gulu.CmdAttr(cmd)
  427. data, err := cmd.CombinedOutput()
  428. if nil == err && strings.HasPrefix(string(data), "pandoc") {
  429. return true
  430. }
  431. return false
  432. }
  433. func GetDataAssetsAbsPath() (ret string) {
  434. ret = filepath.Join(DataDir, "assets")
  435. var err error
  436. stat, err := os.Lstat(ret)
  437. if nil != err {
  438. logging.LogErrorf("stat assets failed: %s", err)
  439. return
  440. }
  441. if 0 != stat.Mode()&os.ModeSymlink {
  442. // 跟随符号链接 https://github.com/siyuan-note/siyuan/issues/5480
  443. ret, err = os.Readlink(ret)
  444. if nil != err {
  445. logging.LogErrorf("read assets link failed: %s", err)
  446. }
  447. }
  448. return
  449. }