summary refs log tree commit diff stats
path: root/pkg/unsplash/unsplash.go
diff options
context:
space:
mode:
authorAndinus <andinus@inventati.org>2020-03-14 14:18:30 +0530
committerAndinus <andinus@inventati.org>2020-03-14 14:18:30 +0530
commitdde2d726d5b65e648b99e45538221014562f1a18 (patch)
tree1db38a43964b205a6dcbb0c160c66213fdffd94e /pkg/unsplash/unsplash.go
parent82a53c3c5b5ffd8af9c69c6184134f100f80b89a (diff)
downloadcetus-dde2d726d5b65e648b99e45538221014562f1a18.tar.gz
Add support for random photo as background v0.3.1
Diffstat (limited to 'pkg/unsplash/unsplash.go')
-rw-r--r--pkg/unsplash/unsplash.go43
1 files changed, 43 insertions, 0 deletions
diff --git a/pkg/unsplash/unsplash.go b/pkg/unsplash/unsplash.go
index a284ebc..7cd408a 100644
--- a/pkg/unsplash/unsplash.go
+++ b/pkg/unsplash/unsplash.go
@@ -16,6 +16,8 @@ package unsplash
 
 import (
 	"fmt"
+	"net/http"
+	"time"
 
 	"framagit.org/andinus/cetus/pkg"
 )
@@ -31,12 +33,53 @@ func SetFromID(photoID string, width int, height int) error {
 	return err
 }
 
+// SetRandom sets a random photo as background
+func SetRandom(width int, height int) error {
+	var path string
+	var err error
+
+	path, err = getPathRandom(width, height)
+	if err != nil {
+		return err
+	}
+	err = background.Set(path)
+	return err
+}
+
 func getPathFromID(photoID string) string {
 	var path string
 	path = fmt.Sprintf("%s/%s", "https://source.unsplash.com", photoID)
 	return path
 }
 
+func getPathRandom(width int, height int) (string, error) {
+	var err error
+	var path string
+	var reqPath string
+
+	client := http.Client{
+		Timeout: time.Second * 64,
+	}
+
+	reqPath = "https://source.unsplash.com"
+	reqPath = appendSizeToPath(reqPath, width, height)
+
+	req, err := http.NewRequest(http.MethodGet, reqPath, nil)
+	if err != nil {
+		return "", err
+	}
+
+	res, err := client.Do(req)
+	if err != nil {
+		return "", err
+	}
+	defer res.Body.Close()
+
+	// Unsplash Source redirects to the photo
+	path = res.Request.URL.String()
+	return path, nil
+}
+
 func appendSizeToPath(path string, width int, height int) string {
 	var size string