Skip to content

Commit

Permalink
Merge branch 'develop' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
hareku committed Nov 22, 2020
2 parents 3d3f8a7 + a929762 commit 0718e72
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
7 changes: 6 additions & 1 deletion pkg/download/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,12 @@ func (c *Client) Run(ctx context.Context) error {
}

for order, img := range images {
if c.isDownloaded(c.makeFileName(post, order, img)) {
downloaded, err := c.isDownloaded(c.makeFileName(post, order, img))
if err != nil {
return fmt.Errorf("failed to check whether does file exist: %w", err)
}

if downloaded {
log.Printf("Already downloaded %dth file of %q.\n", order, post.Title)
if !c.CheckAllPosts {
log.Println("No more new images.")
Expand Down
18 changes: 13 additions & 5 deletions pkg/download/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,29 @@ import (
"net/http"
"os"
"path/filepath"
"regexp"
"time"

"github.com/hareku/fanbox-dl/pkg/api"
)

var invalidFileChar = regexp.MustCompile(`[\/:*?"<>|]`)

func (c *Client) makeFileName(post api.Post, order int, img api.Image) string {
date, err := time.Parse(time.RFC3339, post.PublishedDateTime)
if err != nil {
panic(fmt.Errorf("failed to parse post published date time %s: %w", post.PublishedDateTime, err))
}

title := invalidFileChar.ReplaceAllString(post.Title, "-")

if c.SeparateByPost {
// [SaveDirectory]/[UserID]/2006-01-02-[Post Title]/[Order]-[Image ID].[Image Extension]
return filepath.Join(c.SaveDir, c.UserID, fmt.Sprintf("%s-%s", date.UTC().Format("2006-01-02"), post.Title), fmt.Sprintf("%d-%s.%s", order, img.ID, img.Extension))
return filepath.Join(c.SaveDir, c.UserID, fmt.Sprintf("%s-%s", date.UTC().Format("2006-01-02"), title), fmt.Sprintf("%d-%s.%s", order, img.ID, img.Extension))
}

// [SaveDirectory]/[UserID]/2006-01-02-[Post Title]-[Order]-[Image ID].[Image Extension]
return filepath.Join(c.SaveDir, c.UserID, fmt.Sprintf("%s-%s-%d-%s.%s", date.UTC().Format("2006-01-02"), post.Title, order, img.ID, img.Extension))
return filepath.Join(c.SaveDir, c.UserID, fmt.Sprintf("%s-%s-%d-%s.%s", date.UTC().Format("2006-01-02"), title, order, img.ID, img.Extension))
}

func (c *Client) saveFile(name string, resp *http.Response) error {
Expand Down Expand Up @@ -55,11 +60,14 @@ func (c *Client) saveFile(name string, resp *http.Response) error {
return nil
}

func (c *Client) isDownloaded(name string) bool {
func (c *Client) isDownloaded(name string) (bool, error) {
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false
return false, nil
}
if err != nil {
return false, fmt.Errorf("failed to stat file: %w", err)
}

return true
return true, nil
}

0 comments on commit 0718e72

Please sign in to comment.