1
0
Fork 0
miniflux/internal/reader/opml/handler.go

89 lines
2.2 KiB
Go
Raw Normal View History

// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
2017-11-20 00:10:04 -05:00
package opml // import "miniflux.app/v2/internal/reader/opml"
2017-11-20 00:10:04 -05:00
import (
"fmt"
"io"
"miniflux.app/v2/internal/model"
"miniflux.app/v2/internal/storage"
2017-11-20 00:10:04 -05:00
)
// Handler handles the logic for OPML import/export.
type Handler struct {
2017-11-20 00:10:04 -05:00
store *storage.Storage
}
// Export exports user feeds to OPML.
func (h *Handler) Export(userID int64) (string, error) {
2017-11-28 00:30:04 -05:00
feeds, err := h.store.Feeds(userID)
2017-11-20 00:10:04 -05:00
if err != nil {
2018-04-29 21:56:40 -04:00
return "", err
2017-11-20 00:10:04 -05:00
}
var subscriptions SubcriptionList
for _, feed := range feeds {
subscriptions = append(subscriptions, &Subcription{
Title: feed.Title,
FeedURL: feed.FeedURL,
SiteURL: feed.SiteURL,
CategoryName: feed.Category.Title,
})
}
return Serialize(subscriptions), nil
}
// Import parses and create feeds from an OPML import.
2018-03-14 21:50:06 -04:00
func (h *Handler) Import(userID int64, data io.Reader) error {
2017-11-20 00:10:04 -05:00
subscriptions, err := Parse(data)
if err != nil {
return err
}
for _, subscription := range subscriptions {
if !h.store.FeedURLExists(userID, subscription.FeedURL) {
2017-11-20 00:10:04 -05:00
var category *model.Category
2018-03-14 21:50:06 -04:00
var err error
2017-11-20 00:10:04 -05:00
if subscription.CategoryName == "" {
2017-11-28 00:30:04 -05:00
category, err = h.store.FirstCategory(userID)
2017-11-20 00:10:04 -05:00
if err != nil {
return fmt.Errorf("opml: unable to find first category: %w", err)
2017-11-20 00:10:04 -05:00
}
} else {
2017-11-28 00:30:04 -05:00
category, err = h.store.CategoryByTitle(userID, subscription.CategoryName)
2017-11-20 00:10:04 -05:00
if err != nil {
return fmt.Errorf("opml: unable to search category by title: %w", err)
2017-11-20 00:10:04 -05:00
}
if category == nil {
2021-01-04 01:28:04 -05:00
category, err = h.store.CreateCategory(userID, &model.CategoryRequest{Title: subscription.CategoryName})
2017-11-20 00:10:04 -05:00
if err != nil {
return fmt.Errorf(`opml: unable to create this category: %q`, subscription.CategoryName)
2017-11-20 00:10:04 -05:00
}
}
}
feed := &model.Feed{
UserID: userID,
Title: subscription.Title,
FeedURL: subscription.FeedURL,
SiteURL: subscription.SiteURL,
Category: category,
}
h.store.CreateFeed(feed)
2017-11-20 00:10:04 -05:00
}
}
return nil
}
// NewHandler creates a new handler for OPML files.
func NewHandler(store *storage.Storage) *Handler {
return &Handler{store: store}
2017-11-20 00:10:04 -05:00
}