github.com/awslabs/clencli@v0.0.0-20210514234156-7ecf17182a20/cobra/aid/unsplash.go (about)

     1  /*
     2  Copyright © 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
     3  Licensed under the Apache License, Version 2.0 (the "License");
     4  you may not use this file except in compliance with the License.
     5  You may obtain a copy of the License at
     6  
     7      http://www.apache.org/licenses/LICENSE-2.0
     8  
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package aid
    17  
    18  import (
    19  	"encoding/json"
    20  	"fmt"
    21  	"io/ioutil"
    22  	"net/http"
    23  
    24  	"github.com/awslabs/clencli/cobra/model"
    25  	"github.com/awslabs/clencli/helper"
    26  	"github.com/sirupsen/logrus"
    27  	"github.com/spf13/cobra"
    28  	"gopkg.in/yaml.v2"
    29  )
    30  
    31  // GetModelFromFlags fills the parameters onto the Unsplash Random Photo Parameters struct
    32  func GetModelFromFlags(cmd *cobra.Command) model.UnsplashRandomPhotoParameters {
    33  	var params model.UnsplashRandomPhotoParameters
    34  
    35  	params.Query, _ = cmd.Flags().GetString("query")
    36  	params.Collections, _ = cmd.Flags().GetString("collections")
    37  	params.Featured, _ = cmd.Flags().GetBool("featured")
    38  	params.Username, _ = cmd.Flags().GetString("username")
    39  	params.Orientation, _ = cmd.Flags().GetString("orientation")
    40  	params.Filter, _ = cmd.Flags().GetString("filter")
    41  	params.Size, _ = cmd.Flags().GetString("size")
    42  
    43  	return params
    44  }
    45  
    46  func buildURL(params model.UnsplashRandomPhotoParameters, cred model.Credential) string {
    47  	clientID := cred.AccessKey
    48  	url := fmt.Sprintf("https://api.unsplash.com/photos/random?client_id=%s", clientID)
    49  
    50  	if len(params.Collections) > 0 {
    51  		url += fmt.Sprintf("&collections=%s", params.Collections)
    52  	}
    53  
    54  	if len(params.Query) > 0 {
    55  		url += fmt.Sprintf("&query=%s", params.Query)
    56  	}
    57  
    58  	url += fmt.Sprintf("&featured=%t", params.Featured)
    59  
    60  	if len(params.Username) > 0 {
    61  		url += fmt.Sprintf("&username=%s", params.Username)
    62  	}
    63  
    64  	if len(params.Orientation) > 0 {
    65  		url += fmt.Sprintf("&orientation=%s", params.Orientation)
    66  	}
    67  
    68  	if len(params.Filter) > 0 {
    69  		url += fmt.Sprintf("&filter=%s", params.Filter)
    70  	}
    71  
    72  	return url
    73  }
    74  
    75  // DownloadPhoto downloads a photo and saves into downloads/unsplash/ folder
    76  // It creates the downloads/ folder if it doesn't exists
    77  func DownloadPhoto(params model.UnsplashRandomPhotoParameters, cred model.Credential, photoSizes []string) error {
    78  	response, err := RequestRandomPhoto(params, cred)
    79  	if err != nil {
    80  		return err
    81  	}
    82  
    83  	dumpUnsplashRandomPhotoResponse(response)
    84  
    85  	dirPath, err := helper.CreateDirectoryNamedPath("downloads/unsplash/" + params.Query)
    86  	if err != nil {
    87  		return err
    88  	}
    89  
    90  	if params.Size == "all" {
    91  		for _, pSize := range photoSizes {
    92  			if pSize != "all" {
    93  				params.Size = pSize
    94  				err = helper.DownloadFile(getPhotoURLBySize(params, response), dirPath, response.ID+"-"+pSize+".jpeg")
    95  				if err != nil {
    96  					return err
    97  				}
    98  			}
    99  		}
   100  	} else {
   101  		err = helper.DownloadFile(getPhotoURLBySize(params, response), dirPath, response.ID+".jpeg")
   102  	}
   103  
   104  	return err
   105  }
   106  
   107  // DownloadPhotoByID TODO ...
   108  func DownloadPhotoByID(r model.UnsplashGetPhotoResponse, size string) error {
   109  	dirPath, err := helper.CreateDirectoryNamedPath("downloads/unsplash/" + r.ID)
   110  	if err != nil {
   111  		return err
   112  	}
   113  
   114  	if size == "raw" || size == "all" {
   115  		err = helper.DownloadFile(r.Urls.Raw, dirPath, r.ID+"-raw.jpeg")
   116  		if err != nil {
   117  			return fmt.Errorf("unable to download photo\n%v", err)
   118  		}
   119  	}
   120  
   121  	if size == "full" || size == "all" {
   122  		err = helper.DownloadFile(r.Urls.Full, dirPath, r.ID+"-full.jpeg")
   123  		if err != nil {
   124  			return fmt.Errorf("unable to download photo\n%v", err)
   125  		}
   126  	}
   127  
   128  	if size == "regular" || size == "all" {
   129  		err = helper.DownloadFile(r.Urls.Regular, dirPath, r.ID+"-regular.jpeg")
   130  		if err != nil {
   131  			return fmt.Errorf("unable to download photo\n%v", err)
   132  		}
   133  	}
   134  
   135  	if size == "small" || size == "all" {
   136  		err = helper.DownloadFile(r.Urls.Small, dirPath, r.ID+"-small.jpeg")
   137  		if err != nil {
   138  			return fmt.Errorf("unable to download photo\n%v", err)
   139  		}
   140  	}
   141  
   142  	if size == "thumb" || size == "all" {
   143  		err = helper.DownloadFile(r.Urls.Thumb, dirPath, r.ID+"-thumb.jpeg")
   144  		if err != nil {
   145  			return fmt.Errorf("unable to download photo\n%v", err)
   146  		}
   147  	}
   148  
   149  	return err
   150  
   151  }
   152  
   153  // GetPhotoURLBySize return the photo URL based on the given size
   154  func getPhotoURLBySize(p model.UnsplashRandomPhotoParameters, r model.UnsplashRandomPhotoResponse) string {
   155  	switch p.Size {
   156  	case "thumb":
   157  		return r.Urls.Thumb
   158  	case "small":
   159  		return r.Urls.Small
   160  	case "regular":
   161  		return r.Urls.Regular
   162  	case "full":
   163  		return r.Urls.Full
   164  	case "raw":
   165  		return r.Urls.Raw
   166  	default:
   167  		return r.Urls.Small
   168  	}
   169  }
   170  
   171  // RequestRandomPhoto retrieves a single random photo, given optional filters.
   172  func RequestRandomPhoto(params model.UnsplashRandomPhotoParameters, cred model.Credential) (model.UnsplashRandomPhotoResponse, error) {
   173  	var response model.UnsplashRandomPhotoResponse
   174  	url := buildURL(params, cred)
   175  
   176  	var client http.Client
   177  	resp, err := client.Get(url)
   178  	if err != nil {
   179  		return response, fmt.Errorf("unexpected error while performing GET on Unsplash API \n%v", err)
   180  	}
   181  	defer resp.Body.Close()
   182  
   183  	if resp.StatusCode == http.StatusOK {
   184  		bodyBytes, err := ioutil.ReadAll(resp.Body)
   185  		if err != nil {
   186  			return response, fmt.Errorf("unexpected error while reading Unsplash response \n%v", err)
   187  		}
   188  
   189  		json.Unmarshal(bodyBytes, &response)
   190  	}
   191  
   192  	return response, err
   193  }
   194  
   195  // GetPhoto TODO..
   196  func GetPhoto(id string, cred model.Credential) (model.UnsplashGetPhotoResponse, error) {
   197  	var response model.UnsplashGetPhotoResponse
   198  
   199  	clientID := cred.AccessKey
   200  	url := fmt.Sprintf("https://api.unsplash.com/photos/%s?client_id=%s", id, clientID)
   201  
   202  	var client http.Client
   203  	resp, err := client.Get(url)
   204  	if err != nil {
   205  		return response, fmt.Errorf("unexpected error while performing GET on Unsplash API \n%v", err)
   206  	}
   207  	defer resp.Body.Close()
   208  
   209  	if resp.StatusCode == http.StatusOK {
   210  		bodyBytes, err := ioutil.ReadAll(resp.Body)
   211  		if err != nil {
   212  			return response, fmt.Errorf("unexpected error while reading Unsplash response \n%v", err)
   213  		}
   214  
   215  		json.Unmarshal(bodyBytes, &response)
   216  	}
   217  
   218  	return response, err
   219  }
   220  
   221  // SaveGetPhotoResult TODO ...
   222  func SaveGetPhotoResult(r model.UnsplashGetPhotoResponse) {
   223  	d, err := yaml.Marshal(r)
   224  	if err != nil {
   225  		logrus.Fatalf("error: %v", err)
   226  	}
   227  	helper.WriteFile("unsplash.yaml", d)
   228  }
   229  
   230  func dumpUnsplashRandomPhotoResponse(r model.UnsplashRandomPhotoResponse) {
   231  	d, err := yaml.Marshal(r)
   232  	if err != nil {
   233  		logrus.Fatalf("error: %v", err)
   234  	}
   235  	helper.WriteFile("unsplash.yaml", d)
   236  }