diff options
author | Frédéric Guillot <fred@miniflux.net> | 2017-11-19 21:10:04 -0800 |
---|---|---|
committer | Frédéric Guillot <fred@miniflux.net> | 2017-11-19 22:01:46 -0800 |
commit | 8ffb773f43c8dc54801ca1d111854e7e881c93c9 (patch) | |
tree | 38133a2fc612597a75fed1d13e5b4042f58a2b7e /reader/opml/handler.go |
First commit
Diffstat (limited to 'reader/opml/handler.go')
-rw-r--r-- | reader/opml/handler.go | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/reader/opml/handler.go b/reader/opml/handler.go new file mode 100644 index 0000000..6150d91 --- /dev/null +++ b/reader/opml/handler.go @@ -0,0 +1,94 @@ +// 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. + +package opml + +import ( + "errors" + "fmt" + "github.com/miniflux/miniflux2/model" + "github.com/miniflux/miniflux2/storage" + "io" + "log" +) + +type OpmlHandler struct { + store *storage.Storage +} + +func (o *OpmlHandler) Export(userID int64) (string, error) { + feeds, err := o.store.GetFeeds(userID) + if err != nil { + log.Println(err) + return "", errors.New("Unable to fetch feeds.") + } + + 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 +} + +func (o *OpmlHandler) Import(userID int64, data io.Reader) (err error) { + subscriptions, err := Parse(data) + if err != nil { + return err + } + + for _, subscription := range subscriptions { + if !o.store.FeedURLExists(userID, subscription.FeedURL) { + var category *model.Category + + if subscription.CategoryName == "" { + category, err = o.store.GetFirstCategory(userID) + if err != nil { + log.Println(err) + return errors.New("Unable to find first category.") + } + } else { + category, err = o.store.GetCategoryByTitle(userID, subscription.CategoryName) + if err != nil { + log.Println(err) + return errors.New("Unable to search category by title.") + } + + if category == nil { + category = &model.Category{ + UserID: userID, + Title: subscription.CategoryName, + } + + err := o.store.CreateCategory(category) + if err != nil { + log.Println(err) + return fmt.Errorf(`Unable to create this category: "%s".`, subscription.CategoryName) + } + } + } + + feed := &model.Feed{ + UserID: userID, + Title: subscription.Title, + FeedURL: subscription.FeedURL, + SiteURL: subscription.SiteURL, + Category: category, + } + + o.store.CreateFeed(feed) + } + } + + return nil +} + +func NewOpmlHandler(store *storage.Storage) *OpmlHandler { + return &OpmlHandler{store: store} +} |