71 lines
2.0 KiB
Go
71 lines
2.0 KiB
Go
package models
|
|
|
|
import (
|
|
"context"
|
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
|
)
|
|
|
|
func (r *Repository) SourceFeedURLs(ctx context.Context, key string) ([]string, error) {
|
|
if !sourcefeeds.Supported(key) {
|
|
return nil, sourcefeeds.ErrUnsupported
|
|
}
|
|
rows, err := r.db.QueryContext(ctx, `SELECT f.url FROM source_feeds f JOIN sources s ON s.id=f.source_id WHERE s.source_key=$1 ORDER BY f.position LIMIT 6`, key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
values := []string{}
|
|
for rows.Next() {
|
|
var value string
|
|
if err := rows.Scan(&value); err != nil {
|
|
return nil, err
|
|
}
|
|
values = append(values, value)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return sourcefeeds.Validate(key, values)
|
|
}
|
|
|
|
// UpdateSourceConfig replaces configuration and switches in one transaction.
|
|
// Omitted feeds preserve the saved configuration; an empty replacement is invalid.
|
|
func (r *Repository) UpdateSourceConfig(id string, enabled bool, limit *int, feeds *[]string) error {
|
|
if limit != nil && (*limit < 1 || *limit > 200) {
|
|
return sourcefeeds.ErrInvalid
|
|
}
|
|
tx, err := r.db.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
var key *string
|
|
if err := tx.QueryRow(`SELECT source_key FROM sources WHERE id=$1 FOR UPDATE`, id).Scan(&key); err != nil {
|
|
return err
|
|
}
|
|
if key == nil || !SupportedSourceKey(*key) {
|
|
return ErrSourceNotSupported
|
|
}
|
|
var normalized []string
|
|
if feeds != nil {
|
|
normalized, err = sourcefeeds.Validate(*key, *feeds)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if _, err = tx.Exec(`UPDATE sources SET enabled=$1,article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, limit, id); err != nil {
|
|
return err
|
|
}
|
|
if feeds != nil {
|
|
if _, err = tx.Exec(`DELETE FROM source_feeds WHERE source_id=$1`, id); err != nil {
|
|
return err
|
|
}
|
|
for position, value := range normalized {
|
|
if _, err = tx.Exec(`INSERT INTO source_feeds(source_id,position,url) VALUES($1,$2,$3)`, id, position, value); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return tx.Commit()
|
|
}
|