message_cache.go 16 KB

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