enclosure.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package storage // import "miniflux.app/storage"
  5. import (
  6. "fmt"
  7. "miniflux.app/model"
  8. )
  9. // GetEnclosures returns all attachments for the given entry.
  10. func (s *Storage) GetEnclosures(entryID int64) (model.EnclosureList, error) {
  11. query := `SELECT
  12. id, user_id, entry_id, url, size, mime_type
  13. FROM enclosures
  14. WHERE entry_id = $1 ORDER BY id ASC`
  15. rows, err := s.db.Query(query, entryID)
  16. if err != nil {
  17. return nil, fmt.Errorf("unable to get enclosures: %v", err)
  18. }
  19. defer rows.Close()
  20. enclosures := make(model.EnclosureList, 0)
  21. for rows.Next() {
  22. var enclosure model.Enclosure
  23. err := rows.Scan(
  24. &enclosure.ID,
  25. &enclosure.UserID,
  26. &enclosure.EntryID,
  27. &enclosure.URL,
  28. &enclosure.Size,
  29. &enclosure.MimeType,
  30. )
  31. if err != nil {
  32. return nil, fmt.Errorf("unable to fetch enclosure row: %v", err)
  33. }
  34. enclosures = append(enclosures, &enclosure)
  35. }
  36. return enclosures, nil
  37. }
  38. // CreateEnclosure creates a new attachment.
  39. func (s *Storage) CreateEnclosure(enclosure *model.Enclosure) error {
  40. query := `
  41. INSERT INTO enclosures
  42. (url, size, mime_type, entry_id, user_id)
  43. VALUES
  44. ($1, $2, $3, $4, $5)
  45. RETURNING id
  46. `
  47. err := s.db.QueryRow(
  48. query,
  49. enclosure.URL,
  50. enclosure.Size,
  51. enclosure.MimeType,
  52. enclosure.EntryID,
  53. enclosure.UserID,
  54. ).Scan(&enclosure.ID)
  55. if err != nil {
  56. return fmt.Errorf("unable to create enclosure %q: %v", enclosure.URL, err)
  57. }
  58. return nil
  59. }
  60. // IsEnclosureExists checks if an attachment exists.
  61. func (s *Storage) IsEnclosureExists(enclosure *model.Enclosure) bool {
  62. var result int
  63. query := `SELECT count(*) as c FROM enclosures WHERE user_id=$1 AND entry_id=$2 AND url=$3`
  64. s.db.QueryRow(query, enclosure.UserID, enclosure.EntryID, enclosure.URL).Scan(&result)
  65. return result >= 1
  66. }
  67. // UpdateEnclosures add missing attachments while updating a feed.
  68. func (s *Storage) UpdateEnclosures(enclosures model.EnclosureList) error {
  69. for _, enclosure := range enclosures {
  70. if !s.IsEnclosureExists(enclosure) {
  71. err := s.CreateEnclosure(enclosure)
  72. if err != nil {
  73. return err
  74. }
  75. }
  76. }
  77. return nil
  78. }