forked from go-shiori/shiori
/
pocket.go
118 lines (100 loc) · 2.48 KB
/
pocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package cmd
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/BonexP/shiori/internal/core"
"github.com/BonexP/shiori/internal/model"
"github.com/spf13/cobra"
)
func pocketCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "pocket source-file",
Short: "Import bookmarks from Pocket's exported HTML file",
Args: cobra.ExactArgs(1),
Run: pocketHandler,
}
return cmd
}
func pocketHandler(cmd *cobra.Command, args []string) {
// Prepare bookmark's ID
bookID, err := db.CreateNewID("bookmark")
if err != nil {
cError.Printf("Failed to create ID: %v\n", err)
return
}
// Open pocket's file
srcFile, err := os.Open(args[0])
if err != nil {
cError.Println(err)
os.Exit(1)
}
defer srcFile.Close()
// Parse pocket's file
bookmarks := []model.Bookmark{}
mapURL := make(map[string]struct{})
doc, err := goquery.NewDocumentFromReader(srcFile)
if err != nil {
cError.Println(err)
os.Exit(1)
}
doc.Find("a").Each(func(_ int, a *goquery.Selection) {
// Get metadata
title := a.Text()
url, _ := a.Attr("href")
strTags, _ := a.Attr("tags")
strModified, _ := a.Attr("time_added")
intModified, _ := strconv.ParseInt(strModified, 10, 64)
modified := time.Unix(intModified, 0)
// Clean up URL
var err error
url, err = core.RemoveUTMParams(url)
if err != nil {
cError.Printf("Skip %s: URL is not valid\n", url)
return
}
// Make sure title is valid Utf-8
title = validateTitle(title, url)
// Check if the URL already exist before, both in bookmark
// file or in database
if _, exist := mapURL[url]; exist {
cError.Printf("Skip %s: URL already exists\n", url)
return
}
if _, exist := db.GetBookmark(0, url); exist {
cError.Printf("Skip %s: URL already exists\n", url)
mapURL[url] = struct{}{}
return
}
// Get bookmark tags
tags := []model.Tag{}
for _, strTag := range strings.Split(strTags, ",") {
if strTag != "" {
tags = append(tags, model.Tag{Name: strTag})
}
}
// Add item to list
bookmark := model.Bookmark{
ID: bookID,
URL: url,
Title: title,
Modified: modified.Format("2006-01-02 15:04:05"),
Tags: tags,
}
bookID++
mapURL[url] = struct{}{}
bookmarks = append(bookmarks, bookmark)
})
// Save bookmark to database
bookmarks, err = db.SaveBookmarks(bookmarks...)
if err != nil {
cError.Printf("Failed to save bookmarks: %v\n", err)
os.Exit(1)
}
// Print imported bookmark
fmt.Println()
printBookmarks(bookmarks...)
}