miniflux/storage/enclosure.go

102 lines
2.1 KiB
Go
Raw Normal View History

2017-11-20 06:10:04 +01:00
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
2018-08-25 06:51:50 +02:00
package storage // import "miniflux.app/storage"
2017-11-20 06:10:04 +01:00
import (
"database/sql"
2017-11-20 06:10:04 +01:00
"fmt"
2018-08-25 06:51:50 +02:00
"miniflux.app/model"
2017-11-20 06:10:04 +01:00
)
// GetEnclosures returns all attachments for the given entry.
2017-11-20 06:10:04 +01:00
func (s *Storage) GetEnclosures(entryID int64) (model.EnclosureList, error) {
2019-10-30 06:48:07 +01:00
query := `
SELECT
id,
user_id,
entry_id,
url,
size,
mime_type
FROM
enclosures
WHERE
entry_id = $1
ORDER BY id ASC
`
2017-11-20 06:10:04 +01:00
rows, err := s.db.Query(query, entryID)
if err != nil {
2019-10-30 06:48:07 +01:00
return nil, fmt.Errorf(`store: unable to fetch enclosures: %v`, err)
2017-11-20 06:10:04 +01:00
}
defer rows.Close()
enclosures := make(model.EnclosureList, 0)
for rows.Next() {
var enclosure model.Enclosure
err := rows.Scan(
&enclosure.ID,
&enclosure.UserID,
&enclosure.EntryID,
&enclosure.URL,
&enclosure.Size,
&enclosure.MimeType,
)
if err != nil {
2019-10-30 06:48:07 +01:00
return nil, fmt.Errorf(`store: unable to fetch enclosure row: %v`, err)
2017-11-20 06:10:04 +01:00
}
enclosures = append(enclosures, &enclosure)
}
return enclosures, nil
}
func (s *Storage) createEnclosure(tx *sql.Tx, enclosure *model.Enclosure) error {
2020-01-31 06:08:11 +01:00
if enclosure.URL == "" {
return nil
}
2017-11-20 06:10:04 +01:00
query := `
INSERT INTO enclosures
2019-10-30 06:48:07 +01:00
(url, size, mime_type, entry_id, user_id)
2017-11-20 06:10:04 +01:00
VALUES
2019-10-30 06:48:07 +01:00
($1, $2, $3, $4, $5)
RETURNING
id
2017-11-20 06:10:04 +01:00
`
err := tx.QueryRow(
2017-11-20 06:10:04 +01:00
query,
enclosure.URL,
enclosure.Size,
enclosure.MimeType,
enclosure.EntryID,
enclosure.UserID,
).Scan(&enclosure.ID)
if err != nil {
2019-10-30 06:48:07 +01:00
return fmt.Errorf(`store: unable to create enclosure %q: %v`, enclosure.URL, err)
}
return nil
}
func (s *Storage) updateEnclosures(tx *sql.Tx, userID, entryID int64, enclosures model.EnclosureList) error {
// We delete all attachments in the transaction to keep only the ones visible in the feeds.
if _, err := tx.Exec(`DELETE FROM enclosures WHERE user_id=$1 AND entry_id=$2`, userID, entryID); err != nil {
return err
}
for _, enclosure := range enclosures {
if err := s.createEnclosure(tx, enclosure); err != nil {
return err
}
2017-11-20 06:10:04 +01:00
}
return nil
}