2015-12-07 04:01:03 +00:00
|
|
|
package src
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
"net/url"
|
|
|
|
)
|
|
|
|
|
|
|
|
// DownloadResponse struct is returned by the API for Download request.
|
|
|
|
type DownloadResponse struct {
|
|
|
|
HRef string `json:"href"`
|
|
|
|
Method string `json:"method"`
|
|
|
|
Templated bool `json:"templated"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// Download will get specified data from Yandex.Disk.
|
|
|
|
func (c *Client) Download(remotePath string) (io.ReadCloser, error) { //io.Writer
|
|
|
|
ur, err := c.DownloadRequest(remotePath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return c.PerformDownload(ur.HRef)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DownloadRequest will make an download request and return a URL to download data to.
|
2015-12-30 13:30:57 +00:00
|
|
|
func (c *Client) DownloadRequest(remotePath string) (ur *DownloadResponse, err error) {
|
2015-12-07 04:01:03 +00:00
|
|
|
values := url.Values{}
|
|
|
|
values.Add("path", remotePath)
|
|
|
|
|
|
|
|
req, err := c.scopedRequest("GET", "/v1/disk/resources/download?"+values.Encode(), nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := c.HTTPClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if err := CheckAPIError(resp); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer CheckClose(resp.Body, &err)
|
|
|
|
|
2015-12-30 13:30:57 +00:00
|
|
|
ur, err = ParseDownloadResponse(resp.Body)
|
2015-12-07 04:01:03 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ur, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParseDownloadResponse tries to read and parse DownloadResponse struct.
|
|
|
|
func ParseDownloadResponse(data io.Reader) (*DownloadResponse, error) {
|
|
|
|
dec := json.NewDecoder(data)
|
|
|
|
var ur DownloadResponse
|
|
|
|
|
|
|
|
if err := dec.Decode(&ur); err == io.EOF {
|
|
|
|
// ok
|
|
|
|
} else if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: check if there is any trash data after JSON and crash if there is.
|
|
|
|
|
|
|
|
return &ur, nil
|
|
|
|
}
|