The backend for the AiteStory website
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

359 lines
8.6 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package model
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "net/url"
  8. "time"
  9. "git.aiterp.net/AiteRP/aitestory/formparser"
  10. "git.aiterp.net/AiteRP/aitestory/server"
  11. "git.aiterp.net/gisle/wrouter/generate"
  12. "github.com/microcosm-cc/bluemonday"
  13. "github.com/russross/blackfriday"
  14. )
  15. // PageTypes describes how the source is rendered. For now it's only markdown,
  16. // but who knows what the future holds.
  17. var PageTypes = []string{
  18. "Markdown",
  19. }
  20. // PageMinDate is the earliest date possible. Stories from Matriarch Eriana's childhood
  21. // are thus not going to happen.
  22. var PageMinDate, _ = time.Parse(time.RFC3339, "1753-01-01T00:00:00Z")
  23. // Page is the model describing the individual articles posted
  24. // by users.
  25. type Page struct {
  26. ID string `json:"id"`
  27. Name string `json:"name"`
  28. Author string `json:"author"`
  29. Category string `json:"category"`
  30. FictionalDate time.Time `json:"fictionalDate"`
  31. PublishDate time.Time `json:"publishDate"`
  32. EditDate time.Time `json:"editDate"`
  33. Dated bool `json:"dated"`
  34. Published bool `json:"published"`
  35. Unlisted bool `json:"unlisted"`
  36. Specific bool `json:"specific"`
  37. Indexed bool `json:"indexed"`
  38. BackgroundURL string `json:"backgroundUrl"`
  39. Type string `json:"type"`
  40. Source string `json:"source"`
  41. Tags []Tag `json:"tags"`
  42. prevTags []Tag
  43. cachedOutput string
  44. primaryTag *Tag
  45. }
  46. // Defaults fills in the default details for a page, suited for populating a form
  47. func (page *Page) Defaults() {
  48. page.Category = PageCategories[0].Key
  49. page.Dated = true
  50. page.Published = true
  51. page.Unlisted = false
  52. page.Specific = false
  53. page.Indexed = true
  54. page.BackgroundURL = ""
  55. page.Type = PageTypes[0]
  56. page.Source = ""
  57. }
  58. // Insert adds the page to the database
  59. func (page *Page) Insert() error {
  60. const insertPage = `
  61. INSERT INTO page (
  62. id, name, author, category, fictional_date,
  63. publish_date, edit_date, dated, published,
  64. unlisted, page.specific, indexed, type, source
  65. ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
  66. `
  67. const insertTag = `INSERT INTO page_tag (page_id,tag_id,page_tag.primary) VALUES (?, ?, ?)`
  68. db := server.Main.DB
  69. if page.ID == "" {
  70. page.generateID()
  71. }
  72. // Do the thing
  73. _, err := db.Exec(insertPage,
  74. page.ID, page.Name, page.Author, page.Category, page.FictionalDate, page.PublishDate,
  75. page.EditDate, page.Dated, page.Published, page.Unlisted, page.Specific, page.Indexed,
  76. page.Type, page.Source,
  77. )
  78. if err != nil {
  79. return err
  80. }
  81. // Insert tags
  82. for i, tag := range page.Tags {
  83. _, err := db.Exec(insertTag, page.ID, tag.ID, i == 0)
  84. if err != nil {
  85. page.Delete()
  86. return err
  87. }
  88. }
  89. if len(page.Tags) > 0 {
  90. page.primaryTag = &page.Tags[0]
  91. }
  92. return nil
  93. }
  94. // Update saves the page to the database
  95. func (page *Page) Update() error {
  96. const updatePage = `
  97. UPDATE page SET
  98. name=?,category=?,fictional_date=?,publish_date=?,
  99. edit_date=?,dated=?,published=?,unlisted=?,page.specific=?,
  100. indexed=?,type=?,source=?
  101. WHERE id=?
  102. `
  103. const clearTags = `DELETE FROM page_tag WHERE page_id=?`
  104. const insertTag = `INSERT INTO page_tag (page_id,tag_id,page_tag.primary) VALUES (?, ?, ?)`
  105. db := server.Main.DB
  106. if page.ID == "" {
  107. return errors.New("no id")
  108. }
  109. // Do the thing
  110. _, err := db.Exec(updatePage,
  111. page.Name, page.Category, page.FictionalDate, page.PublishDate,
  112. page.EditDate, page.Dated, page.Published, page.Unlisted, page.Specific, page.Indexed,
  113. page.Type, page.Source, page.ID,
  114. )
  115. if err != nil {
  116. return err
  117. }
  118. // Stop now if the tages haven't changed
  119. if len(page.prevTags) == len(page.Tags) {
  120. change := false
  121. for i, tag := range page.prevTags {
  122. if tag.ID != page.prevTags[i].ID {
  123. change = true
  124. break
  125. }
  126. }
  127. if !change {
  128. return nil
  129. }
  130. }
  131. // Re-tag (can be optimized if need arise)
  132. _, err = db.Exec(clearTags, page.ID)
  133. if err != nil {
  134. return err
  135. }
  136. for i, tag := range page.Tags {
  137. _, err := db.Exec(insertTag, page.ID, tag.ID, i == 0)
  138. if err != nil {
  139. return err
  140. }
  141. }
  142. if len(page.Tags) > 0 {
  143. page.primaryTag = &page.Tags[0]
  144. }
  145. return nil
  146. }
  147. // Delete removes the page from the database
  148. func (page *Page) Delete() error {
  149. db := server.Main.DB
  150. // Do the thing
  151. results, err := db.Exec("DELETE FROM `page` WHERE id=? LIMIT 1", page.ID)
  152. if err != nil {
  153. return err
  154. }
  155. // Count the stuffs that were done things to
  156. affected, err := results.RowsAffected()
  157. if err != nil {
  158. return err
  159. }
  160. if affected == 0 {
  161. return errors.New("page not found")
  162. }
  163. return nil
  164. }
  165. // Content parses the content of the page
  166. func (page *Page) Content() (template.HTML, error) {
  167. if page.Type == "Markdown" {
  168. // TODO: Convert [[Ehanis Tioran]] to [Ehanis Tioran](https://wiki.aiterp.net/index.php?title=Ehanis%20Tioran)
  169. unsafe := blackfriday.MarkdownCommon([]byte(page.Source))
  170. output := string(bluemonday.UGCPolicy().SanitizeBytes(unsafe))
  171. return template.HTML(output), nil
  172. }
  173. return "", fmt.Errorf("Page type '%s' is not supported", page.Type)
  174. }
  175. // PrimaryTag gets the page's primary tag
  176. func (page *Page) PrimaryTag() Tag {
  177. if page.primaryTag == nil {
  178. return Tag{}
  179. }
  180. return *page.primaryTag
  181. }
  182. // ParseForm validates the values in a form and sets the page's values whenever possible regardless
  183. // so that it can be pushed to the viewmodel to allow the user to correct their mistakes without fear
  184. // of losing their hard work
  185. func (page *Page) ParseForm(form url.Values) []error {
  186. errors := make([]error, 0, 4)
  187. err := formparser.String(form.Get("name"), &page.Name, 2, 192)
  188. if err != nil {
  189. errors = append(errors, fmt.Errorf("Name: %s", err))
  190. }
  191. err = formparser.Select(form.Get("category"), &page.Category, pageCategories, page.Category != "")
  192. if err != nil {
  193. errors = append(errors, fmt.Errorf("Category: %s", err))
  194. }
  195. err = formparser.Date(form.Get("fictionalDate"), &page.FictionalDate, !page.FictionalDate.IsZero())
  196. if err != nil {
  197. errors = append(errors, fmt.Errorf("Fictonal Date: %s", err))
  198. }
  199. page.Dated = form.Get("dated") != ""
  200. page.Published = form.Get("published") != ""
  201. page.Unlisted = form.Get("unlisted") != ""
  202. page.Specific = form.Get("specific") != ""
  203. page.Indexed = form.Get("indexed") != ""
  204. err = formparser.String(form.Get("backgroundUrl"), &page.BackgroundURL, 0, 255)
  205. if err != nil {
  206. errors = append(errors, fmt.Errorf("Background URL: %s", err))
  207. }
  208. err = formparser.Select(form.Get("type"), &page.Type, PageTypes, page.Type != "")
  209. if err != nil {
  210. errors = append(errors, fmt.Errorf("Type: %s", err))
  211. }
  212. err = formparser.String(form.Get("source"), &page.Source, 0, 102400)
  213. if err != nil {
  214. errors = append(errors, fmt.Errorf("Content is too long, max: 100 KB (~16k words)"))
  215. }
  216. if len(errors) == 0 {
  217. errors = nil
  218. }
  219. return errors
  220. }
  221. // Standardize page ID generation
  222. func (page *Page) generateID() {
  223. page.ID = generate.FriendlyID(16)
  224. }
  225. // FindPage finds a page by ID. The Header model handles
  226. // listning pages
  227. func FindPage(id string) (*Page, error) {
  228. const selectPage = `
  229. SELECT id,name,author,category,fictional_date,publish_date,edit_date,dated,published,
  230. unlisted,page.specific,indexed,type,source,background_url
  231. FROM page
  232. WHERE id=?
  233. `
  234. const selectPageTags = `
  235. SELECT tag.id,tag.type,tag.name,page_tag.primary
  236. FROM page_tag
  237. RIGHT JOIN tag ON (tag.id = page_tag.tag_id)
  238. WHERE page_tag.page_id = ?
  239. ORDER BY tag.type DESC, tag.name
  240. `
  241. db := server.Main.DB
  242. rows, err := db.Query(selectPage, id)
  243. if err != nil {
  244. return nil, err
  245. }
  246. defer rows.Close()
  247. if !rows.Next() {
  248. return nil, errors.New("not found")
  249. }
  250. page := new(Page)
  251. err = parsePage(page, rows)
  252. if err != nil {
  253. return nil, err
  254. }
  255. rows, err = db.Query(selectPageTags, page.ID)
  256. if err != nil {
  257. return nil, err
  258. }
  259. page.Tags = make([]Tag, 0, 64)
  260. for rows.Next() {
  261. primary := false
  262. tag := Tag{}
  263. rows.Scan(&tag.ID, &tag.Type, &tag.Name, &primary)
  264. page.Tags = append(page.Tags, tag)
  265. if primary {
  266. page.primaryTag = &tag
  267. }
  268. }
  269. return page, nil
  270. }
  271. func parsePage(page *Page, rows *sql.Rows) error {
  272. var fictionalDate, publishDate, editDate string
  273. var bgURL *string
  274. err := rows.Scan(
  275. &page.ID, &page.Name, &page.Author, &page.Category, &fictionalDate,
  276. &publishDate, &editDate, &page.Dated, &page.Published, &page.Unlisted,
  277. &page.Specific, &page.Indexed, &page.Type, &page.Source, &bgURL,
  278. )
  279. if err != nil {
  280. return err
  281. }
  282. if bgURL != nil {
  283. page.BackgroundURL = *bgURL
  284. }
  285. page.FictionalDate, err = time.Parse("2006-01-02 15:04:05", fictionalDate)
  286. if err != nil {
  287. return err
  288. }
  289. page.PublishDate, err = time.Parse("2006-01-02 15:04:05", publishDate)
  290. if err != nil {
  291. return err
  292. }
  293. page.EditDate, err = time.Parse("2006-01-02 15:04:05", editDate)
  294. if err != nil {
  295. return err
  296. }
  297. return nil
  298. }