2018-01-28 14:55:43 +08:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/RadhiFadlillah/go-readability"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
addCmd = &cobra.Command{
|
|
|
|
Use: "add url",
|
2018-01-30 14:31:31 +08:00
|
|
|
Short: "Bookmark the specified URL.",
|
2018-01-28 14:55:43 +08:00
|
|
|
Args: cobra.ExactArgs(1),
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
// Read flag and arguments
|
|
|
|
url := args[0]
|
2018-01-30 15:57:36 +08:00
|
|
|
title, _ := cmd.Flags().GetString("title")
|
|
|
|
excerpt, _ := cmd.Flags().GetString("excerpt")
|
2018-01-28 14:55:43 +08:00
|
|
|
tags, _ := cmd.Flags().GetStringSlice("tags")
|
2018-01-30 15:57:36 +08:00
|
|
|
offline, _ := cmd.Flags().GetBool("offline")
|
2018-01-28 14:55:43 +08:00
|
|
|
|
|
|
|
// Save new bookmark
|
2018-01-30 15:57:36 +08:00
|
|
|
err := addBookmark(url, title, excerpt, tags, offline)
|
2018-01-28 14:55:43 +08:00
|
|
|
if err != nil {
|
|
|
|
cError.Println(err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2018-01-30 15:57:36 +08:00
|
|
|
addCmd.Flags().StringP("title", "i", "", "Custom title for this bookmark.")
|
|
|
|
addCmd.Flags().StringP("excerpt", "e", "", "Custom excerpt for this bookmark.")
|
2018-01-28 14:55:43 +08:00
|
|
|
addCmd.Flags().StringSliceP("tags", "t", []string{}, "Comma-separated tags for this bookmark.")
|
2018-01-30 15:57:36 +08:00
|
|
|
addCmd.Flags().BoolP("offline", "o", false, "Save bookmark without fetching data from internet.")
|
2018-01-28 14:55:43 +08:00
|
|
|
rootCmd.AddCommand(addCmd)
|
|
|
|
}
|
|
|
|
|
2018-01-30 15:57:36 +08:00
|
|
|
func addBookmark(url, title, excerpt string, tags []string, offline bool) (err error) {
|
|
|
|
// Prepare variable
|
|
|
|
defaultArticle := readability.Article{
|
|
|
|
URL: url,
|
|
|
|
Meta: readability.Metadata{
|
|
|
|
Title: "Untitled",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
article := defaultArticle
|
|
|
|
|
|
|
|
// Fetch data from internet
|
|
|
|
if !offline {
|
|
|
|
article, err = readability.Parse(url, 10*time.Second)
|
|
|
|
if err != nil {
|
|
|
|
cError.Println("Failed to fetch article from internet")
|
|
|
|
article = defaultArticle
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set custom value
|
|
|
|
if title != "" {
|
|
|
|
article.Meta.Title = title
|
|
|
|
}
|
|
|
|
|
|
|
|
if excerpt != "" {
|
|
|
|
article.Meta.Excerpt = excerpt
|
2018-01-28 14:55:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
bookmark, err := DB.SaveBookmark(article, tags...)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
printBookmark(bookmark)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|