Author: Honza Pokorny <honza@redhat.com>
Move cover download logic to a method
pkg/bookends/bookends.go | 92 +++++++++++++++++++++--------------------
diff --git a/pkg/bookends/bookends.go b/pkg/bookends/bookends.go
index e04ae6ff7e4fe7c98c51924085673fa2ebc6ff31..bafec02a594a9aa639c07bce578074f1b184f497 100644
--- a/pkg/bookends/bookends.go
+++ b/pkg/bookends/bookends.go
@@ -90,7 +90,53 @@ localPath := path.Join("cache", fmt.Sprintf("%s.jpg", b.ISBN))
return url.Parse(localPath)
}
-func (b Book) DownloadCover() error {
+func (b Book) DownloadCover(config Config) error {
+ cachePath := path.Join(config.CacheDir, fmt.Sprintf("%s.jpg", b.ISBN))
+
+ if PathExists(cachePath) {
+ return nil
+ }
+
+ coversPath := path.Join(config.CoversDir, fmt.Sprintf("%s.jpg", b.ISBN))
+
+ if PathExists(coversPath) {
+ // Copy the file over
+ err := copy(coversPath, cachePath)
+
+ if err != nil {
+ return err
+ }
+
+ return nil
+
+ }
+
+ coverUrl, err := b.CoverURL()
+
+ if err != nil {
+ return err
+ }
+
+ resp, err := http.Get(coverUrl.String())
+
+ if err != nil {
+ return err
+ }
+
+ if resp.StatusCode > 201 {
+ return errors.New("non 200 response:" + b.Title)
+ }
+
+ destination, err := os.Create(cachePath)
+ if err != nil {
+ return err
+ }
+ defer destination.Close()
+ _, err = io.Copy(destination, resp.Body)
+
+ if err != nil {
+ return err
+ }
return nil
}
@@ -329,49 +375,7 @@ return err
}
for _, book := range books {
- cachePath := path.Join(config.CacheDir, fmt.Sprintf("%s.jpg", book.ISBN))
-
- if PathExists(cachePath) {
- continue
- }
-
- coversPath := path.Join(config.CoversDir, fmt.Sprintf("%s.jpg", book.ISBN))
-
- if PathExists(coversPath) {
- // Copy the file over
- err := copy(coversPath, cachePath)
-
- if err != nil {
- return nil
- }
-
- continue
-
- }
-
- coverUrl, err := book.CoverURL()
-
- if err != nil {
- return err
- }
-
- resp, err := http.Get(coverUrl.String())
-
- if err != nil {
- return err
- }
-
- if resp.StatusCode > 201 {
- return errors.New(" non 200 response:" + book.Title)
- }
-
- destination, err := os.Create(cachePath)
- if err != nil {
- return err
- }
- defer destination.Close()
- _, err = io.Copy(destination, resp.Body)
-
+ err = book.DownloadCover(config)
if err != nil {
return err
}