install.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "regexp"
  8. "strings"
  9. "github.com/gofrs/uuid"
  10. "github.com/jmoiron/sqlx"
  11. goyesqlx "github.com/knadh/goyesql/v2/sqlx"
  12. "github.com/knadh/listmonk/models"
  13. "github.com/knadh/stuffbin"
  14. "github.com/lib/pq"
  15. )
  16. // install runs the first time setup of creating and
  17. // migrating the database and creating the super user.
  18. func install(lastVer string, db *sqlx.DB, fs stuffbin.FileSystem, prompt bool) {
  19. qMap, _ := initQueries(queryFilePath, db, fs, false)
  20. fmt.Println("")
  21. fmt.Println("** first time installation **")
  22. fmt.Printf("** IMPORTANT: This will wipe existing listmonk tables and types in the DB '%s' **",
  23. ko.String("db.database"))
  24. fmt.Println("")
  25. if prompt {
  26. var ok string
  27. fmt.Print("continue (y/n)? ")
  28. if _, err := fmt.Scanf("%s", &ok); err != nil {
  29. lo.Fatalf("error reading value from terminal: %v", err)
  30. }
  31. if strings.ToLower(ok) != "y" {
  32. fmt.Println("install cancelled.")
  33. return
  34. }
  35. }
  36. // Migrate the tables.
  37. err := installSchema(lastVer, db, fs)
  38. if err != nil {
  39. lo.Fatalf("Error migrating DB schema: %v", err)
  40. }
  41. // Load the queries.
  42. var q Queries
  43. if err := goyesqlx.ScanToStruct(&q, qMap, db.Unsafe()); err != nil {
  44. lo.Fatalf("error loading SQL queries: %v", err)
  45. }
  46. // Sample list.
  47. var (
  48. defList int
  49. optinList int
  50. )
  51. if err := q.CreateList.Get(&defList,
  52. uuid.Must(uuid.NewV4()),
  53. "Default list",
  54. models.ListTypePrivate,
  55. models.ListOptinSingle,
  56. pq.StringArray{"test"},
  57. ); err != nil {
  58. lo.Fatalf("Error creating list: %v", err)
  59. }
  60. if err := q.CreateList.Get(&optinList, uuid.Must(uuid.NewV4()),
  61. "Opt-in list",
  62. models.ListTypePublic,
  63. models.ListOptinDouble,
  64. pq.StringArray{"test"},
  65. ); err != nil {
  66. lo.Fatalf("Error creating list: %v", err)
  67. }
  68. // Sample subscriber.
  69. if _, err := q.UpsertSubscriber.Exec(
  70. uuid.Must(uuid.NewV4()),
  71. "john@example.com",
  72. "John Doe",
  73. `{"type": "known", "good": true, "city": "Bengaluru"}`,
  74. pq.Int64Array{int64(defList)},
  75. true); err != nil {
  76. lo.Fatalf("Error creating subscriber: %v", err)
  77. }
  78. if _, err := q.UpsertSubscriber.Exec(
  79. uuid.Must(uuid.NewV4()),
  80. "anon@example.com",
  81. "Anon Doe",
  82. `{"type": "unknown", "good": true, "city": "Bengaluru"}`,
  83. pq.Int64Array{int64(optinList)},
  84. true); err != nil {
  85. lo.Fatalf("Error creating subscriber: %v", err)
  86. }
  87. // Default template.
  88. tplBody, err := ioutil.ReadFile("static/email-templates/default.tpl")
  89. if err != nil {
  90. tplBody = []byte(tplTag)
  91. }
  92. var tplID int
  93. if err := q.CreateTemplate.Get(&tplID,
  94. "Default template",
  95. string(tplBody),
  96. ); err != nil {
  97. lo.Fatalf("error creating default template: %v", err)
  98. }
  99. if _, err := q.SetDefaultTemplate.Exec(tplID); err != nil {
  100. lo.Fatalf("error setting default template: %v", err)
  101. }
  102. // Sample campaign.
  103. if _, err := q.CreateCampaign.Exec(uuid.Must(uuid.NewV4()),
  104. models.CampaignTypeRegular,
  105. "Test campaign",
  106. "Welcome to listmonk",
  107. "No Reply <noreply@yoursite.com>",
  108. `<h3>Hi {{ .Subscriber.FirstName }}!</h3>
  109. This is a test e-mail campaign. Your second name is {{ .Subscriber.LastName }} and you are from {{ .Subscriber.Attribs.city }}.`,
  110. "richtext",
  111. nil,
  112. pq.StringArray{"test-campaign"},
  113. emailMsgr,
  114. 1,
  115. pq.Int64Array{1},
  116. ); err != nil {
  117. lo.Fatalf("error creating sample campaign: %v", err)
  118. }
  119. lo.Printf("Setup complete")
  120. lo.Printf(`Run the program and access the dashboard at %s`, ko.MustString("app.address"))
  121. }
  122. // installSchema executes the SQL schema and creates the necessary tables and types.
  123. func installSchema(curVer string, db *sqlx.DB, fs stuffbin.FileSystem) error {
  124. q, err := fs.Read("/schema.sql")
  125. if err != nil {
  126. return err
  127. }
  128. if _, err := db.Exec(string(q)); err != nil {
  129. return err
  130. }
  131. // Insert the current migration version.
  132. return recordMigrationVersion(curVer, db)
  133. }
  134. // recordMigrationVersion inserts the given version (of DB migration) into the
  135. // `migrations` array in the settings table.
  136. func recordMigrationVersion(ver string, db *sqlx.DB) error {
  137. _, err := db.Exec(fmt.Sprintf(`INSERT INTO settings (key, value)
  138. VALUES('migrations', '["%s"]'::JSONB)
  139. ON CONFLICT (key) DO UPDATE SET value = settings.value || EXCLUDED.value`, ver))
  140. return err
  141. }
  142. func newConfigFile() error {
  143. if _, err := os.Stat("config.toml"); !os.IsNotExist(err) {
  144. return errors.New("config.toml exists. Remove it to generate a new one")
  145. }
  146. // Initialize the static file system into which all
  147. // required static assets (.sql, .js files etc.) are loaded.
  148. fs := initFS("")
  149. b, err := fs.Read("config.toml.sample")
  150. if err != nil {
  151. return fmt.Errorf("error reading sample config (is binary stuffed?): %v", err)
  152. }
  153. // Generate a random admin password.
  154. pwd, err := generateRandomString(16)
  155. if err == nil {
  156. b = regexp.MustCompile(`admin_password\s+?=\s+?(.*)`).
  157. ReplaceAll(b, []byte(fmt.Sprintf(`admin_password = "%s"`, pwd)))
  158. }
  159. return ioutil.WriteFile("config.toml", b, 0644)
  160. }
  161. // checkSchema checks if the DB schema is installed.
  162. func checkSchema(db *sqlx.DB) (bool, error) {
  163. if _, err := db.Exec(`SELECT id FROM templates LIMIT 1`); err != nil {
  164. if isTableNotExistErr(err) {
  165. return false, nil
  166. }
  167. return false, err
  168. }
  169. return true, nil
  170. }