This repository has been archived by the owner on Sep 30, 2023. It is now read-only.
/
post.go
103 lines (82 loc) · 2.08 KB
/
post.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
package command
import (
"flag"
"fmt"
"io/fs"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/KleinChiu/fantia-dl/core"
)
type PostParams struct {
postId int
global GlobalParams
}
func NewPostCommand(fs *flag.FlagSet) *PostParams {
cmd := new(PostParams)
addGlobalFlags(fs, &cmd.global)
fs.IntVar(&cmd.postId, "post", 0, "Post ID")
fs.Func("url", "Post url", func(s string) error {
raw, err := url.Parse(s)
if err != nil {
return fmt.Errorf("invalid url")
}
path := strings.Split(raw.Path, "/")
if path[1] != "posts" {
return fmt.Errorf("invalid post url")
}
n, err := strconv.Atoi(path[2])
if err != nil {
return fmt.Errorf("invalid post url")
}
cmd.postId = n
return nil
})
return cmd
}
func (p PostParams) Sanitize() error {
if err := sanitizeGlobalParam(p.global); err != nil {
return err
}
if p.postId == 0 {
return fmt.Errorf("invalid post id %d", p.postId)
}
return nil
}
func (p PostParams) Execute() error {
agent := core.NewAgent(p.global.session)
api, err := core.FetchPost(agent, p.postId)
if err != nil {
return err
}
postRoot := api.JoinBasePath(p.global.dir)
os.MkdirAll(postRoot, fs.ModeDir)
for _, content := range api.PostContents {
root := content.JoinBasePath(postRoot)
os.Mkdir(root, fs.ModeDir)
switch content.Category {
case "file":
if content.DownloadURI == "" {
continue
}
if p.global.dryRun {
fmt.Fprintf(os.Stdout, "Will download file %s from %s\n", content.Filename, api.Title)
continue
}
_, path, _ := core.DownloadContent(agent, root, core.BaseUrl+content.DownloadURI, content.Title, p.global.overwrite)
os.Chtimes(path, time.Now(), content.ParentPost.Date)
case "photo_gallery":
for _, photo := range content.PostContentPhotos {
if p.global.dryRun {
fmt.Fprintf(os.Stdout, "Will download photo %d from %s\n", photo.ID, api.Title)
continue
}
_, path, _ := core.DownloadContent(agent, root, photo.URL.Original, strconv.Itoa(photo.ID), p.global.overwrite)
os.Chtimes(path, time.Now(), content.ParentPost.Date)
}
}
}
return nil
}