message_cache.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. package server
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. _ "github.com/mattn/go-sqlite3" // SQLite driver
  8. "heckel.io/ntfy/util"
  9. "log"
  10. "strings"
  11. "time"
  12. )
  13. var (
  14. errUnexpectedMessageType = errors.New("unexpected message type")
  15. )
  16. // Messages cache
  17. const (
  18. createMessagesTableQuery = `
  19. BEGIN;
  20. CREATE TABLE IF NOT EXISTS messages (
  21. id INTEGER PRIMARY KEY AUTOINCREMENT,
  22. mid TEXT NOT NULL,
  23. time INT NOT NULL,
  24. topic TEXT NOT NULL,
  25. message TEXT NOT NULL,
  26. title TEXT NOT NULL,
  27. priority INT NOT NULL,
  28. tags TEXT NOT NULL,
  29. click TEXT NOT NULL,
  30. actions TEXT NOT NULL,
  31. attachment_name TEXT NOT NULL,
  32. attachment_type TEXT NOT NULL,
  33. attachment_size INT NOT NULL,
  34. attachment_expires INT NOT NULL,
  35. attachment_url TEXT NOT NULL,
  36. attachment_owner TEXT NOT NULL,
  37. encoding TEXT NOT NULL,
  38. published INT NOT NULL
  39. );
  40. CREATE INDEX IF NOT EXISTS idx_mid ON messages (mid);
  41. CREATE INDEX IF NOT EXISTS idx_topic ON messages (topic);
  42. COMMIT;
  43. `
  44. insertMessageQuery = `
  45. INSERT INTO messages (mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding, published)
  46. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  47. `
  48. pruneMessagesQuery = `DELETE FROM messages WHERE time < ? AND published = 1`
  49. selectRowIDFromMessageID = `SELECT id FROM messages WHERE topic = ? AND mid = ?`
  50. selectMessagesSinceTimeQuery = `
  51. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  52. FROM messages
  53. WHERE topic = ? AND time >= ? AND published = 1
  54. ORDER BY time, id
  55. `
  56. selectMessagesSinceTimeIncludeScheduledQuery = `
  57. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  58. FROM messages
  59. WHERE topic = ? AND time >= ?
  60. ORDER BY time, id
  61. `
  62. selectMessagesSinceIDQuery = `
  63. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  64. FROM messages
  65. WHERE topic = ? AND id > ? AND published = 1
  66. ORDER BY time, id
  67. `
  68. selectMessagesSinceIDIncludeScheduledQuery = `
  69. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  70. FROM messages
  71. WHERE topic = ? AND (id > ? OR published = 0)
  72. ORDER BY time, id
  73. `
  74. selectMessagesDueQuery = `
  75. SELECT mid, time, topic, message, title, priority, tags, click, actions, attachment_name, attachment_type, attachment_size, attachment_expires, attachment_url, attachment_owner, encoding
  76. FROM messages
  77. WHERE time <= ? AND published = 0
  78. ORDER BY time, id
  79. `
  80. updateMessagePublishedQuery = `UPDATE messages SET published = 1 WHERE mid = ?`
  81. selectMessagesCountQuery = `SELECT COUNT(*) FROM messages`
  82. selectMessageCountForTopicQuery = `SELECT COUNT(*) FROM messages WHERE topic = ?`
  83. selectTopicsQuery = `SELECT topic FROM messages GROUP BY topic`
  84. selectAttachmentsSizeQuery = `SELECT IFNULL(SUM(attachment_size), 0) FROM messages WHERE attachment_owner = ? AND attachment_expires >= ?`
  85. selectAttachmentsExpiredQuery = `SELECT mid FROM messages WHERE attachment_expires > 0 AND attachment_expires < ?`
  86. )
  87. // Schema management queries
  88. const (
  89. currentSchemaVersion = 6
  90. createSchemaVersionTableQuery = `
  91. CREATE TABLE IF NOT EXISTS schemaVersion (
  92. id INT PRIMARY KEY,
  93. version INT NOT NULL
  94. );
  95. `
  96. insertSchemaVersion = `INSERT INTO schemaVersion VALUES (1, ?)`
  97. updateSchemaVersion = `UPDATE schemaVersion SET version = ? WHERE id = 1`
  98. selectSchemaVersionQuery = `SELECT version FROM schemaVersion WHERE id = 1`
  99. // 0 -> 1
  100. migrate0To1AlterMessagesTableQuery = `
  101. BEGIN;
  102. ALTER TABLE messages ADD COLUMN title TEXT NOT NULL DEFAULT('');
  103. ALTER TABLE messages ADD COLUMN priority INT NOT NULL DEFAULT(0);
  104. ALTER TABLE messages ADD COLUMN tags TEXT NOT NULL DEFAULT('');
  105. COMMIT;
  106. `
  107. // 1 -> 2
  108. migrate1To2AlterMessagesTableQuery = `
  109. ALTER TABLE messages ADD COLUMN published INT NOT NULL DEFAULT(1);
  110. `
  111. // 2 -> 3
  112. migrate2To3AlterMessagesTableQuery = `
  113. BEGIN;
  114. ALTER TABLE messages ADD COLUMN click TEXT NOT NULL DEFAULT('');
  115. ALTER TABLE messages ADD COLUMN attachment_name TEXT NOT NULL DEFAULT('');
  116. ALTER TABLE messages ADD COLUMN attachment_type TEXT NOT NULL DEFAULT('');
  117. ALTER TABLE messages ADD COLUMN attachment_size INT NOT NULL DEFAULT('0');
  118. ALTER TABLE messages ADD COLUMN attachment_expires INT NOT NULL DEFAULT('0');
  119. ALTER TABLE messages ADD COLUMN attachment_owner TEXT NOT NULL DEFAULT('');
  120. ALTER TABLE messages ADD COLUMN attachment_url TEXT NOT NULL DEFAULT('');
  121. COMMIT;
  122. `
  123. // 3 -> 4
  124. migrate3To4AlterMessagesTableQuery = `
  125. ALTER TABLE messages ADD COLUMN encoding TEXT NOT NULL DEFAULT('');
  126. `
  127. // 4 -> 5
  128. migrate4To5AlterMessagesTableQuery = `
  129. BEGIN;
  130. CREATE TABLE IF NOT EXISTS messages_new (
  131. id INTEGER PRIMARY KEY AUTOINCREMENT,
  132. mid TEXT NOT NULL,
  133. time INT NOT NULL,
  134. topic TEXT NOT NULL,
  135. message TEXT NOT NULL,
  136. title TEXT NOT NULL,
  137. priority INT NOT NULL,
  138. tags TEXT NOT NULL,
  139. click TEXT NOT NULL,
  140. attachment_name TEXT NOT NULL,
  141. attachment_type TEXT NOT NULL,
  142. attachment_size INT NOT NULL,
  143. attachment_expires INT NOT NULL,
  144. attachment_url TEXT NOT NULL,
  145. attachment_owner TEXT NOT NULL,
  146. encoding TEXT NOT NULL,
  147. published INT NOT NULL
  148. );
  149. CREATE INDEX IF NOT EXISTS idx_mid ON messages_new (mid);
  150. CREATE INDEX IF NOT EXISTS idx_topic ON messages_new (topic);
  151. INSERT
  152. INTO messages_new (
  153. mid, time, topic, message, title, priority, tags, click, attachment_name, attachment_type,
  154. attachment_size, attachment_expires, attachment_url, attachment_owner, encoding, published)
  155. SELECT
  156. id, time, topic, message, title, priority, tags, click, attachment_name, attachment_type,
  157. attachment_size, attachment_expires, attachment_url, attachment_owner, encoding, published
  158. FROM messages;
  159. DROP TABLE messages;
  160. ALTER TABLE messages_new RENAME TO messages;
  161. COMMIT;
  162. `
  163. // 5 -> 6
  164. migrate5To6AlterMessagesTableQuery = `
  165. ALTER TABLE messages ADD COLUMN actions TEXT NOT NULL DEFAULT('');
  166. `
  167. )
  168. type messageCache struct {
  169. db *sql.DB
  170. nop bool
  171. }
  172. // newSqliteCache creates a SQLite file-backed cache
  173. func newSqliteCache(filename string, nop bool) (*messageCache, error) {
  174. db, err := sql.Open("sqlite3", filename)
  175. if err != nil {
  176. return nil, err
  177. }
  178. if err := setupCacheDB(db); err != nil {
  179. return nil, err
  180. }
  181. return &messageCache{
  182. db: db,
  183. nop: nop,
  184. }, nil
  185. }
  186. // newMemCache creates an in-memory cache
  187. func newMemCache() (*messageCache, error) {
  188. return newSqliteCache(createMemoryFilename(), false)
  189. }
  190. // newNopCache creates an in-memory cache that discards all messages;
  191. // it is always empty and can be used if caching is entirely disabled
  192. func newNopCache() (*messageCache, error) {
  193. return newSqliteCache(createMemoryFilename(), true)
  194. }
  195. // createMemoryFilename creates a unique memory filename to use for the SQLite backend.
  196. // From mattn/go-sqlite3: "Each connection to ":memory:" opens a brand new in-memory
  197. // sql database, so if the stdlib's sql engine happens to open another connection and
  198. // you've only specified ":memory:", that connection will see a brand new database.
  199. // A workaround is to use "file::memory:?cache=shared" (or "file:foobar?mode=memory&cache=shared").
  200. // Every connection to this string will point to the same in-memory database."
  201. func createMemoryFilename() string {
  202. return fmt.Sprintf("file:%s?mode=memory&cache=shared", util.RandomString(10))
  203. }
  204. func (c *messageCache) AddMessage(m *message) error {
  205. if m.Event != messageEvent {
  206. return errUnexpectedMessageType
  207. }
  208. if c.nop {
  209. return nil
  210. }
  211. published := m.Time <= time.Now().Unix()
  212. tags := strings.Join(m.Tags, ",")
  213. var attachmentName, attachmentType, attachmentURL, attachmentOwner string
  214. var attachmentSize, attachmentExpires int64
  215. if m.Attachment != nil {
  216. attachmentName = m.Attachment.Name
  217. attachmentType = m.Attachment.Type
  218. attachmentSize = m.Attachment.Size
  219. attachmentExpires = m.Attachment.Expires
  220. attachmentURL = m.Attachment.URL
  221. attachmentOwner = m.Attachment.Owner
  222. }
  223. var actionsStr string
  224. if len(m.Actions) > 0 {
  225. actionsBytes, err := json.Marshal(m.Actions)
  226. if err != nil {
  227. return err
  228. }
  229. actionsStr = string(actionsBytes)
  230. }
  231. _, err := c.db.Exec(
  232. insertMessageQuery,
  233. m.ID,
  234. m.Time,
  235. m.Topic,
  236. m.Message,
  237. m.Title,
  238. m.Priority,
  239. tags,
  240. m.Click,
  241. actionsStr,
  242. attachmentName,
  243. attachmentType,
  244. attachmentSize,
  245. attachmentExpires,
  246. attachmentURL,
  247. attachmentOwner,
  248. m.Encoding,
  249. published,
  250. )
  251. return err
  252. }
  253. func (c *messageCache) Messages(topic string, since sinceMarker, scheduled bool) ([]*message, error) {
  254. if since.IsNone() {
  255. return make([]*message, 0), nil
  256. } else if since.IsID() {
  257. return c.messagesSinceID(topic, since, scheduled)
  258. }
  259. return c.messagesSinceTime(topic, since, scheduled)
  260. }
  261. func (c *messageCache) messagesSinceTime(topic string, since sinceMarker, scheduled bool) ([]*message, error) {
  262. var rows *sql.Rows
  263. var err error
  264. if scheduled {
  265. rows, err = c.db.Query(selectMessagesSinceTimeIncludeScheduledQuery, topic, since.Time().Unix())
  266. } else {
  267. rows, err = c.db.Query(selectMessagesSinceTimeQuery, topic, since.Time().Unix())
  268. }
  269. if err != nil {
  270. return nil, err
  271. }
  272. return readMessages(rows)
  273. }
  274. func (c *messageCache) messagesSinceID(topic string, since sinceMarker, scheduled bool) ([]*message, error) {
  275. idrows, err := c.db.Query(selectRowIDFromMessageID, topic, since.ID())
  276. if err != nil {
  277. return nil, err
  278. }
  279. defer idrows.Close()
  280. if !idrows.Next() {
  281. return c.messagesSinceTime(topic, sinceAllMessages, scheduled)
  282. }
  283. var rowID int64
  284. if err := idrows.Scan(&rowID); err != nil {
  285. return nil, err
  286. }
  287. idrows.Close()
  288. var rows *sql.Rows
  289. if scheduled {
  290. rows, err = c.db.Query(selectMessagesSinceIDIncludeScheduledQuery, topic, rowID)
  291. } else {
  292. rows, err = c.db.Query(selectMessagesSinceIDQuery, topic, rowID)
  293. }
  294. if err != nil {
  295. return nil, err
  296. }
  297. return readMessages(rows)
  298. }
  299. func (c *messageCache) MessagesDue() ([]*message, error) {
  300. rows, err := c.db.Query(selectMessagesDueQuery, time.Now().Unix())
  301. if err != nil {
  302. return nil, err
  303. }
  304. return readMessages(rows)
  305. }
  306. func (c *messageCache) MarkPublished(m *message) error {
  307. _, err := c.db.Exec(updateMessagePublishedQuery, m.ID)
  308. return err
  309. }
  310. func (c *messageCache) MessageCount(topic string) (int, error) {
  311. rows, err := c.db.Query(selectMessageCountForTopicQuery, topic)
  312. if err != nil {
  313. return 0, err
  314. }
  315. defer rows.Close()
  316. var count int
  317. if !rows.Next() {
  318. return 0, errors.New("no rows found")
  319. }
  320. if err := rows.Scan(&count); err != nil {
  321. return 0, err
  322. } else if err := rows.Err(); err != nil {
  323. return 0, err
  324. }
  325. return count, nil
  326. }
  327. func (c *messageCache) Topics() (map[string]*topic, error) {
  328. rows, err := c.db.Query(selectTopicsQuery)
  329. if err != nil {
  330. return nil, err
  331. }
  332. defer rows.Close()
  333. topics := make(map[string]*topic)
  334. for rows.Next() {
  335. var id string
  336. if err := rows.Scan(&id); err != nil {
  337. return nil, err
  338. }
  339. topics[id] = newTopic(id)
  340. }
  341. if err := rows.Err(); err != nil {
  342. return nil, err
  343. }
  344. return topics, nil
  345. }
  346. func (c *messageCache) Prune(olderThan time.Time) error {
  347. _, err := c.db.Exec(pruneMessagesQuery, olderThan.Unix())
  348. return err
  349. }
  350. func (c *messageCache) AttachmentBytesUsed(owner string) (int64, error) {
  351. rows, err := c.db.Query(selectAttachmentsSizeQuery, owner, time.Now().Unix())
  352. if err != nil {
  353. return 0, err
  354. }
  355. defer rows.Close()
  356. var size int64
  357. if !rows.Next() {
  358. return 0, errors.New("no rows found")
  359. }
  360. if err := rows.Scan(&size); err != nil {
  361. return 0, err
  362. } else if err := rows.Err(); err != nil {
  363. return 0, err
  364. }
  365. return size, nil
  366. }
  367. func (c *messageCache) AttachmentsExpired() ([]string, error) {
  368. rows, err := c.db.Query(selectAttachmentsExpiredQuery, time.Now().Unix())
  369. if err != nil {
  370. return nil, err
  371. }
  372. defer rows.Close()
  373. ids := make([]string, 0)
  374. for rows.Next() {
  375. var id string
  376. if err := rows.Scan(&id); err != nil {
  377. return nil, err
  378. }
  379. ids = append(ids, id)
  380. }
  381. if err := rows.Err(); err != nil {
  382. return nil, err
  383. }
  384. return ids, nil
  385. }
  386. func readMessages(rows *sql.Rows) ([]*message, error) {
  387. defer rows.Close()
  388. messages := make([]*message, 0)
  389. for rows.Next() {
  390. var timestamp, attachmentSize, attachmentExpires int64
  391. var priority int
  392. var id, topic, msg, title, tagsStr, click, actionsStr, attachmentName, attachmentType, attachmentURL, attachmentOwner, encoding string
  393. err := rows.Scan(
  394. &id,
  395. &timestamp,
  396. &topic,
  397. &msg,
  398. &title,
  399. &priority,
  400. &tagsStr,
  401. &click,
  402. &actionsStr,
  403. &attachmentName,
  404. &attachmentType,
  405. &attachmentSize,
  406. &attachmentExpires,
  407. &attachmentURL,
  408. &attachmentOwner,
  409. &encoding,
  410. )
  411. if err != nil {
  412. return nil, err
  413. }
  414. var tags []string
  415. if tagsStr != "" {
  416. tags = strings.Split(tagsStr, ",")
  417. }
  418. var actions []*action
  419. if actionsStr != "" {
  420. if err := json.Unmarshal([]byte(actionsStr), &actions); err != nil {
  421. return nil, err
  422. }
  423. }
  424. var att *attachment
  425. if attachmentName != "" && attachmentURL != "" {
  426. att = &attachment{
  427. Name: attachmentName,
  428. Type: attachmentType,
  429. Size: attachmentSize,
  430. Expires: attachmentExpires,
  431. URL: attachmentURL,
  432. Owner: attachmentOwner,
  433. }
  434. }
  435. messages = append(messages, &message{
  436. ID: id,
  437. Time: timestamp,
  438. Event: messageEvent,
  439. Topic: topic,
  440. Message: msg,
  441. Title: title,
  442. Priority: priority,
  443. Tags: tags,
  444. Click: click,
  445. Actions: actions,
  446. Attachment: att,
  447. Encoding: encoding,
  448. })
  449. }
  450. if err := rows.Err(); err != nil {
  451. return nil, err
  452. }
  453. return messages, nil
  454. }
  455. func setupCacheDB(db *sql.DB) error {
  456. // If 'messages' table does not exist, this must be a new database
  457. rowsMC, err := db.Query(selectMessagesCountQuery)
  458. if err != nil {
  459. return setupNewCacheDB(db)
  460. }
  461. rowsMC.Close()
  462. // If 'messages' table exists, check 'schemaVersion' table
  463. schemaVersion := 0
  464. rowsSV, err := db.Query(selectSchemaVersionQuery)
  465. if err == nil {
  466. defer rowsSV.Close()
  467. if !rowsSV.Next() {
  468. return errors.New("cannot determine schema version: cache file may be corrupt")
  469. }
  470. if err := rowsSV.Scan(&schemaVersion); err != nil {
  471. return err
  472. }
  473. rowsSV.Close()
  474. }
  475. // Do migrations
  476. if schemaVersion == currentSchemaVersion {
  477. return nil
  478. } else if schemaVersion == 0 {
  479. return migrateFrom0(db)
  480. } else if schemaVersion == 1 {
  481. return migrateFrom1(db)
  482. } else if schemaVersion == 2 {
  483. return migrateFrom2(db)
  484. } else if schemaVersion == 3 {
  485. return migrateFrom3(db)
  486. } else if schemaVersion == 4 {
  487. return migrateFrom4(db)
  488. } else if schemaVersion == 5 {
  489. return migrateFrom5(db)
  490. }
  491. return fmt.Errorf("unexpected schema version found: %d", schemaVersion)
  492. }
  493. func setupNewCacheDB(db *sql.DB) error {
  494. if _, err := db.Exec(createMessagesTableQuery); err != nil {
  495. return err
  496. }
  497. if _, err := db.Exec(createSchemaVersionTableQuery); err != nil {
  498. return err
  499. }
  500. if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
  501. return err
  502. }
  503. return nil
  504. }
  505. func migrateFrom0(db *sql.DB) error {
  506. log.Print("Migrating cache database schema: from 0 to 1")
  507. if _, err := db.Exec(migrate0To1AlterMessagesTableQuery); err != nil {
  508. return err
  509. }
  510. if _, err := db.Exec(createSchemaVersionTableQuery); err != nil {
  511. return err
  512. }
  513. if _, err := db.Exec(insertSchemaVersion, 1); err != nil {
  514. return err
  515. }
  516. return migrateFrom1(db)
  517. }
  518. func migrateFrom1(db *sql.DB) error {
  519. log.Print("Migrating cache database schema: from 1 to 2")
  520. if _, err := db.Exec(migrate1To2AlterMessagesTableQuery); err != nil {
  521. return err
  522. }
  523. if _, err := db.Exec(updateSchemaVersion, 2); err != nil {
  524. return err
  525. }
  526. return migrateFrom2(db)
  527. }
  528. func migrateFrom2(db *sql.DB) error {
  529. log.Print("Migrating cache database schema: from 2 to 3")
  530. if _, err := db.Exec(migrate2To3AlterMessagesTableQuery); err != nil {
  531. return err
  532. }
  533. if _, err := db.Exec(updateSchemaVersion, 3); err != nil {
  534. return err
  535. }
  536. return migrateFrom3(db)
  537. }
  538. func migrateFrom3(db *sql.DB) error {
  539. log.Print("Migrating cache database schema: from 3 to 4")
  540. if _, err := db.Exec(migrate3To4AlterMessagesTableQuery); err != nil {
  541. return err
  542. }
  543. if _, err := db.Exec(updateSchemaVersion, 4); err != nil {
  544. return err
  545. }
  546. return migrateFrom4(db)
  547. }
  548. func migrateFrom4(db *sql.DB) error {
  549. log.Print("Migrating cache database schema: from 4 to 5")
  550. if _, err := db.Exec(migrate4To5AlterMessagesTableQuery); err != nil {
  551. return err
  552. }
  553. if _, err := db.Exec(updateSchemaVersion, 5); err != nil {
  554. return err
  555. }
  556. return migrateFrom5(db)
  557. }
  558. func migrateFrom5(db *sql.DB) error {
  559. log.Print("Migrating cache database schema: from 5 to 6")
  560. if _, err := db.Exec(migrate5To6AlterMessagesTableQuery); err != nil {
  561. return err
  562. }
  563. if _, err := db.Exec(updateSchemaVersion, 6); err != nil {
  564. return err
  565. }
  566. return nil // Update this when a new version is added
  567. }