// Download is a handler will return a specific file
960482
func (filebox *Filebox) Download(w http.ResponseWriter, req *http.Request) {
	var (
		currentUser qor.CurrentUser
		filePath    = strings.TrimPrefix(req.URL.Path, filebox.prefix)
		context     = &admin.Context{Context: &qor.Context{Request: req, Writer: w}}
	)

	if auth := filebox.Auth; auth != nil {
		currentUser = auth.GetCurrentUser(context)
	}

	matchedRoles := roles.MatchedRoles(req, currentUser)

	file := filebox.AccessFile(filePath, matchedRoles...)
	if reader, err := file.Read(); err == nil {
		fileName := filepath.Base(file.FilePath)

		w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
		w.Header().Set("Content-Type", req.Header.Get("Content-Type"))
		http.ServeContent(w, req, fileName, time.Now(), reader)
	} else if err == roles.ErrPermissionDenied && filebox.Auth != nil {
		http.Redirect(w, req, filebox.Auth.LoginURL(context), http.StatusFound)
	} else {
		http.NotFound(w, req)
	}
}
189122
func (a *basicDownloadAdapter) downloadFilename(t *Transfer) string {
	// Not a temp file since we will be resuming it
	return filepath.Join(a.tempDir(), t.Oid+".tmp")
}
842001
func Download(method, endpoint string, destination interface{}) (r *Requester, err error) {
	r, err = Request(method, endpoint)
	if err != nil {
		return
	}
	r.IsDownload = true
	r.Destination(destination)
	return
}
1178086
func (d *downloader) Download(url *url.URL, targetFile string) (*git.SourceInfo, error) {
	r := d.schemeReaders[url.Scheme]
	info := &git.SourceInfo{}
	if r == nil {
		glog.Errorf("No URL handler found for %s", url.String())
		return nil, s2ierr.NewURLHandlerError(url.String())
	}

	reader, err := r.Read(url)
	if err != nil {
		return nil, err
	}
	defer reader.Close()

	out, err := os.Create(targetFile)
	defer out.Close()

	if err != nil {
		glog.Errorf("Unable to create target file %s (%v)", targetFile, err)
		return nil, err
	}

	if _, err = io.Copy(out, reader); err != nil {
		os.Remove(targetFile)
		glog.Warningf("Skipping file %s due to error copying from source: %v", targetFile, err)
		return nil, err
	}

	glog.V(2).Infof("Downloaded '%s'", url.String())
	info.Location = url.String()
	return info, nil
}
1033967
func (m *Metadata) DownloadURL() (*url.URL, error) {
	if m.BaseURL == "" {
		m.BaseURL = imagemetadata.UbuntuCloudImagesURL
	}
	u, err := url.Parse(m.BaseURL + "/" + m.Path)
	if err != nil {
		return nil, errors.Annotate(err, "failed to create url")
	}
	return u, nil
}
1200836
func (d *downloader) Download(u *url.URL, out writeSyncer) error {
	client, err := d.Session.Client()
	if err != nil {
		return err
	}
	req, err := d.Session.Request(u)
	if err != nil {
		return err
	}
	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	if stopNow, err := d.Session.HandleStatus(res); stopNow || err != nil {
		return err
	}

	reader, err := d.Session.BodyReader(res)
	if err != nil {
		return err
	}
	if _, err := io.Copy(out, reader); err != nil {
		return errwrap.Wrap(fmt.Errorf("failed to download %q", u.String()), err)
	}

	if err := out.Sync(); err != nil {
		return errwrap.Wrap(fmt.Errorf("failed to sync data from %q to disk", u.String()), err)
	}

	return nil
}
1366319
func (s *storageImpl) download(ctx context.Context, url string, output io.WriteSeeker, h hash.Hash) error {
	var prevProgress int64
	var prevOffset int64
	var prevReportTs time.Time
	var lastSpeed string

	// reportProgress print the download progress, throttling the reports rate.
	reportProgress := func(read int64, total int64) {
		now := clock.Now(ctx)
		progress := read * 100 / total
		if progress < prevProgress || read == total || now.Sub(prevReportTs) > downloadReportInterval {
			// Calculate instantaneous speed only over sufficiently long intervals,
			// otherwise it may appear to fluctuate wildly.
			if !prevReportTs.IsZero() {
				if dt := now.Sub(prevReportTs); dt > time.Second {
					kbps := float64(read-prevOffset) / dt.Seconds() / 1000.0
					lastSpeed = fmt.Sprintf("%.1f", kbps)
				}
			}
			logging.Infof(ctx, "cipd: fetching - %d%% (%s KB/s)", progress, lastSpeed)
			prevProgress = progress
			prevOffset = read
			prevReportTs = now
		}
	}

	// resetProgress resets the progress counter.
	resetProgress := func(total int64) {
		prevProgress = 1000 // > 100%, to trigger first initial progress report
		prevOffset = 0
		prevReportTs = time.Time{}
		lastSpeed = "??"
		reportProgress(0, total)
	}

	// download is a separate function to be able to use deferred close.
	download := func(out io.Writer, src io.ReadCloser, totalLen int64) error {
		defer src.Close()
		logging.Infof(ctx, "cipd: about to fetch %.1f MB", float32(totalLen)/1000.0/1000.0)
		resetProgress(totalLen)
		_, err := io.Copy(out, &readerWithProgress{
			reader:   src,
			callback: func(read int64) { reportProgress(read, totalLen) },
		})
		return err
	}

	// reportTransientError logs the error and sleep few seconds.
	reportTransientError := func(msg string, args ...interface{}) {
		if err := ctx.Err(); err != nil {
			return
		}
		logging.Warningf(ctx, msg, args...)
		clock.Sleep(ctx, 2*time.Second)
	}

	// Download the actual data (several attempts).
	for attempt := 0; attempt < downloadMaxAttempts; attempt++ {
		// Context canceled?
		if err := ctx.Err(); err != nil {
			return err
		}

		// Rewind output to zero offset.
		h.Reset()
		_, err := output.Seek(0, os.SEEK_SET)
		if err != nil {
			return err
		}

		// Send the request.
		logging.Infof(ctx, "cipd: initiating the fetch")
		var req *http.Request
		var resp *http.Response
		req, err = http.NewRequest("GET", url, nil)
		if err != nil {
			return err
		}
		req.Header.Set("User-Agent", s.userAgent)
		resp, err = ctxhttp.Do(ctx, s.client, req)
		if err != nil {
			if isTemporaryNetError(err) {
				reportTransientError("cipd: failed to initiate the fetch - %s", err)
				continue
			}
			return err
		}

		// Transient error, retry.
		if isTemporaryHTTPError(resp.StatusCode) {
			resp.Body.Close()
			reportTransientError("cipd: transient HTTP error %d while fetching the file", resp.StatusCode)
			continue
		}

		// Fatal error, abort.
		if resp.StatusCode >= 400 {
			resp.Body.Close()
			return fmt.Errorf("server replied with HTTP code %d", resp.StatusCode)
		}

		// Try to fetch (will close resp.Body when done).
		err = download(io.MultiWriter(output, h), resp.Body, resp.ContentLength)
		if err != nil {
			reportTransientError("cipd: transient error fetching the file: %s", err)
			continue
		}

		// Success.
		return nil
	}

	return ErrDownloadError
}
120677
func (ctx *Context) Download(fpath string) error {
	f, err := os.Open(fpath)
	if err != nil {
		return err
	}
	defer f.Close()

	fName := filepath.Base(fpath)
	ctx.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%v\"", fName))
	_, err = io.Copy(ctx, f)
	return err
}
57487
func (c *Client) Download(ctx context.Context, u *url.URL, param *Download) (io.ReadCloser, int64, error) {
	res, err := c.DownloadRequest(ctx, u, param)
	if err != nil {
		return nil, 0, err
	}

	switch res.StatusCode {
	case http.StatusOK:
	default:
		err = errors.New(res.Status)
	}

	if err != nil {
		return nil, 0, err
	}

	r := res.Body

	return r, res.ContentLength, nil
}
1264567
func (d *downloader) DownloadFile(url string) (int64, string, error) {
	c := http.Client{
		CheckRedirect: func(r *http.Request, via []*http.Request) error {
			r.URL.Opaque = r.URL.Path

			//some redirect return '/' as url
			if strings.Trim(r.URL.Opaque, "/") != "" {
				url = r.URL.Opaque
			}

			return nil
		},
	}

	r, err := c.Get(url)

	if err != nil {
		return 0, "", err
	}
	defer r.Body.Close()

	if r.StatusCode == 200 {
		d.filename = getFilenameFromHeader(r.Header.Get("Content-Disposition"))

		if d.filename == "" {
			d.filename = getFilenameFromURL(url)
		}

		f, err := os.Create(filepath.Join(d.saveDir, d.filename))
		if err != nil {
			return 0, "", err
		}
		defer f.Close()

		size, err := io.Copy(f, r.Body)
		if err != nil {
			return 0, "", err
		}

		d.downloaded = true
		return size, d.filename, nil

	}
	return 0, "", fmt.Errorf("Error downloading file from %s", url)
}
1144056
func (c *C) Download(status int, v []byte) {
	c.Writer.Header().Set(contentType, "application/octet-stream; charset=UTF-8")
	c.Writer.WriteHeader(status)
	c.Writer.Write(v)
}
1165054
func (c *Context) Download(name string) (string, error) {
	deps := &contextDeps{
		APIClient: c.apiClient,
		name:      name,
		dataDir:   c.dataDir,
	}
	path, err := internal.ContextDownload(deps)
	if err != nil {
		return "", errors.Trace(err)
	}
	return path, nil
}
901917
func (at *DownloadableAsset) Download(out io.Writer) (int64, error) {
	return DownloadAsset(at, out)
}
1019780
func (c *Context) DownloadURL(url string) (filePath string, err error) {

	ext := filepath.Ext(url)
	out, err := ioutil.TempFile("", fmt.Sprintf("%d_%d", c.Bot().ID, c.Chat.ID))

	if err != nil {
		return "", err
	}

	out.Close()
	os.Rename(out.Name(), out.Name()+ext)

	out, err = os.OpenFile(out.Name()+ext, os.O_RDWR, 0666)
	if err != nil {
		return "", err
	}
	defer out.Close()

	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		return "", errors.New("non 2xx resp status")
	}
	defer resp.Body.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return "", err
	}

	return out.Name(), nil
}
489426
func (o *httpOps) DownloadImage(u *url.URL) (readSeekCloser, *cacheData, error) {
	ensureLogger(o.Debug)
	image, cd, err := o.DownloadImageWithETag(u, "")
	if err != nil {
		return nil, nil, err
	}
	if cd.UseCached {
		return nil, nil, fmt.Errorf("asked to use cached image even if not asked for that")
	}
	return image, cd, nil
}
429307
func (n *Node) Download(ctx *cli.Context) ([]string, error) {
	for _, s := range services {
		if !strings.HasPrefix(n.DownloadURL, s.prefix) {
			continue
		}

		m := s.pattern.FindStringSubmatch(n.DownloadURL)
		if m == nil {
			if s.prefix != "" {
				return nil, errors.New("Cannot match package service prefix by given path")
			}
			continue
		}

		match := map[string]string{"downloadURL": n.DownloadURL}
		for i, n := range s.pattern.SubexpNames() {
			if n != "" {
				match[n] = m[i]
			}
		}
		return s.get(HttpClient, match, n, ctx)

	}

	if n.ImportPath != n.DownloadURL {
		return nil, errors.New("Didn't find any match service")
	}

	log.Info("Cannot match any service, getting dynamic...")
	return n.getDynamic(HttpClient, ctx)
}
651752
func (d Datastore) DownloadFile(ctx context.Context, path string, file string, param *soap.Download) error {
	u, p, err := d.downloadTicket(ctx, path, param)
	if err != nil {
		return err
	}
	return d.Client().DownloadFile(ctx, file, u, p)
}