// NewVideoNoteUpload creates a new video note uploader.
//
// chatID is where to send it, file is a string path to the file,
// FileReader, or FileBytes.
356820
func NewVideoNoteUpload(chatID int64, length int, file interface{}) VideoNoteConfig {
	return VideoNoteConfig{
		BaseFile: BaseFile{
			BaseChat:    BaseChat{ChatID: chatID},
			File:        file,
			UseExisting: false,
		},
		Length: length,
	}
}
521851
func (c *Client) UploadVideoWithProgress(filePath string, cb func(*ProgressInfo)) (VideoInfo, error) {
	return uploadVideo(c.creds, filePath, cb)
}
1057157
func (c *Client) TarUpload(hash string, uploader Uploader, defaultPath string, toEncrypt bool) (string, error) {
	ctx, sp := spancontext.StartSpan(context.Background(), "api.client.tarupload")
	defer sp.Finish()

	var tn time.Time

	reqR, reqW := io.Pipe()
	defer reqR.Close()
	addr := hash

	// If there is a hash already (a manifest), then that manifest will determine if the upload has
	// to be encrypted or not. If there is no manifest then the toEncrypt parameter decides if
	// there is encryption or not.
	if hash == "" && toEncrypt {
		// This is the built-in address for the encrypted upload endpoint
		addr = "encrypt"
	}
	req, err := http.NewRequest("POST", c.Gateway+"/bzz:/"+addr, reqR)
	if err != nil {
		return "", err
	}

	trace := GetClientTrace("swarm api client - upload tar", "api.client.uploadtar", uuid.New()[:8], &tn)

	req = req.WithContext(httptrace.WithClientTrace(ctx, trace))
	transport := http.DefaultTransport

	req.Header.Set("Content-Type", "application/x-tar")
	if defaultPath != "" {
		q := req.URL.Query()
		q.Set("defaultpath", defaultPath)
		req.URL.RawQuery = q.Encode()
	}

	// use 'Expect: 100-continue' so we don't send the request body if
	// the server refuses the request
	req.Header.Set("Expect", "100-continue")

	tw := tar.NewWriter(reqW)

	// define an UploadFn which adds files to the tar stream
	uploadFn := func(file *File) error {
		hdr := &tar.Header{
			Name:    file.Path,
			Mode:    file.Mode,
			Size:    file.Size,
			ModTime: file.ModTime,
			Xattrs: map[string]string{
				"user.swarm.content-type": file.ContentType,
			},
		}
		if err := tw.WriteHeader(hdr); err != nil {
			return err
		}
		_, err = io.Copy(tw, file)
		return err
	}

	// run the upload in a goroutine so we can send the request headers and
	// wait for a '100 Continue' response before sending the tar stream
	go func() {
		err := uploader.Upload(uploadFn)
		if err == nil {
			err = tw.Close()
		}
		reqW.CloseWithError(err)
	}()
	tn = time.Now()
	res, err := transport.RoundTrip(req)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		return "", fmt.Errorf("unexpected HTTP status: %s", res.Status)
	}
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	return string(data), nil
}
1374303
func newUploadRequest(target, username, secret string, headers map[string]string, a *asset) (*h.Request, error) {
	req, err := h.NewRequest(h.MethodPut, target, a.ReadCloser)
	if err != nil {
		return nil, err
	}
	req.ContentLength = a.Size
	req.SetBasicAuth(username, secret)

	for k, v := range headers {
		req.Header.Add(k, v)
	}

	return req, err
}
616114
func (twilio *Twilio) CreateVideoRoom(options *createRoomOptions) (videoResponse *VideoResponse, exception *Exception, err error) {
	twilioUrl := twilio.VideoUrl + "/v1/Rooms"
	formValues := createRoomOptionsToFormValues(options)

	res, err := twilio.post(formValues, twilioUrl)
	if err != nil {
		return videoResponse, exception, err
	}
	defer res.Body.Close()

	responseBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return videoResponse, exception, err
	}

	if res.StatusCode != http.StatusCreated {
		exception = new(Exception)
		err = json.Unmarshal(responseBody, exception)

		// We aren't checking the error because we don't actually care.
		// It's going to be passed to the client either way.
		return videoResponse, exception, err
	}

	videoResponse = new(VideoResponse)
	err = json.Unmarshal(responseBody, videoResponse)
	return videoResponse, exception, err
}
771990
func (v *VideoNote) Send(b *Bot, to Recipient, opt *SendOptions) (*Message, error) {
	params := map[string]string{
		"chat_id": to.Recipient(),
	}

	if v.Duration != 0 {
		params["duration"] = strconv.Itoa(v.Duration)
	}
	if v.Length != 0 {
		params["length"] = strconv.Itoa(v.Length)
	}

	embedSendOptions(params, opt)

	msg, err := b.sendObject(&v.File, "videoNote", params, thumbnailToFilemap(v.Thumbnail))
	if err != nil {
		return nil, err
	}

	msg.VideoNote.File.stealRef(&v.File)
	*v = *msg.VideoNote

	return msg, nil
}
270868
func (b *Bslack) uploadFile(msg *config.Message, channelID string) {
	for _, f := range msg.Extra["file"] {
		fi, ok := f.(config.FileInfo)
		if !ok {
			b.Log.Errorf("Received a file with unexpected content: %#v", f)
			continue
		}
		if msg.Text == fi.Comment {
			msg.Text = ""
		}
		// Because the result of the UploadFile is slower than the MessageEvent from slack
		// we can't match on the file ID yet, so we have to match on the filename too.
		ts := time.Now()
		b.Log.Debugf("Adding file %s to cache at %s with timestamp", fi.Name, ts.String())
		b.cache.Add("filename"+fi.Name, ts)
		initialComment := fmt.Sprintf("File from %s", msg.Username)
		if fi.Comment != "" {
			initialComment += fmt.Sprintf("with comment: %s", fi.Comment)
		}
		res, err := b.sc.UploadFile(slack.FileUploadParameters{
			Reader:          bytes.NewReader(*fi.Data),
			Filename:        fi.Name,
			Channels:        []string{channelID},
			InitialComment:  initialComment,
			ThreadTimestamp: msg.ParentID,
		})
		if err != nil {
			b.Log.Errorf("uploadfile %#v", err)
			return
		}
		if res.ID != "" {
			b.Log.Debugf("Adding file ID %s to cache with timestamp %s", res.ID, ts.String())
			b.cache.Add("file"+res.ID, ts)
		}
	}
}
283721
func NewVideoNoteShare(chatID int64, length int, fileID string) VideoNoteConfig {
	return VideoNoteConfig{
		BaseFile: BaseFile{
			BaseChat:    BaseChat{ChatID: chatID},
			FileID:      fileID,
			UseExisting: true,
		},
		Length: length,
	}
}
695502
func (request *Request) Upload(filename string, filetype string) (response *Response, err error) {
	postRequest, err := request.buildPost(uploadEndpoint, filename, filetype)
	if err != nil {
		return nil, err
	}
	return sendPost(postRequest)
}
1115552
func NewUpdateFulfillHTLC(chanID ChannelID, id uint64,
	preimage [32]byte) *UpdateFulfillHTLC {

	return &UpdateFulfillHTLC{
		ChanID:          chanID,
		ID:              id,
		PaymentPreimage: preimage,
	}
}
1255133
func NewSetChatPhotoUpload(chatID int64, file interface{}) SetChatPhotoConfig {
	return SetChatPhotoConfig{
		BaseFile: BaseFile{
			BaseChat:    BaseChat{ChatID: chatID},
			File:        file,
			UseExisting: false,
		},
	}
}
377690
func newfileUploadRequest(gr *GoReq, params map[string]string, paramName, filePath string) (*bytes.Buffer, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	fileContents, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}
	fi, err := file.Stat()
	if err != nil {
		return nil, err
	}
	file.Close()

	body := new(bytes.Buffer)
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, fi.Name())
	if err != nil {
		return nil, err
	}
	part.Write(fileContents)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}

	gr.Header["Content-Type"] = writer.FormDataContentType()
	return body, nil
}
1182045
func (c *Client) UploadVideo(filePath string) (VideoInfo, error) {
	return uploadVideo(c.creds, filePath, nil)
}
1030116
func (material *Material) ImageUpload(filename string) (url string, err error) {
	var accessToken string
	accessToken, err = material.GetAccessToken()
	if err != nil {
		return
	}

	uri := fmt.Sprintf("%s?access_token=%s", mediaUploadImageURL, accessToken)
	var response []byte
	response, err = util.PostFile("media", filename, uri)
	if err != nil {
		return
	}
	var image resMediaImage
	err = json.Unmarshal(response, &image)
	if err != nil {
		return
	}
	if image.ErrCode != 0 {
		err = fmt.Errorf("UploadImage error : errcode=%v , errmsg=%v", image.ErrCode, image.ErrMsg)
		return
	}
	url = image.URL
	return

}
230855
func (c *MockCommunicator) Upload(path string, input io.Reader) error {
	f, ok := c.Uploads[path]
	if !ok {
		return fmt.Errorf("Path %q not found!", path)
	}

	var buf bytes.Buffer
	buf.ReadFrom(input)
	content := strings.TrimSpace(buf.String())

	f = strings.TrimSpace(f)
	if f != content {
		return fmt.Errorf("expected: %q\n\ngot: %q\n", f, content)
	}

	return nil
}
168476
func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string, fi *config.FileInfo) {
	content := bytes.NewReader(*fi.Data)
	sp := strings.Split(fi.Name, ".")
	mtype := mime.TypeByExtension("." + sp[len(sp)-1])
	if !strings.Contains(mtype, "image") && !strings.Contains(mtype, "video") {
		return
	}
	if fi.Comment != "" {
		_, err := b.mc.SendText(channel, msg.Username+fi.Comment)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	} else {
		// image and video uploads send no username, we have to do this ourself here #715
		_, err := b.mc.SendText(channel, msg.Username)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	}
	b.Log.Debugf("uploading file: %s %s", fi.Name, mtype)
	res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
	if err != nil {
		b.Log.Errorf("file upload failed: %#v", err)
		return
	}

	switch {
	case strings.Contains(mtype, "video"):
		b.Log.Debugf("sendVideo %s", res.ContentURI)
		_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendVideo failed: %#v", err)
		}
	case strings.Contains(mtype, "image"):
		b.Log.Debugf("sendImage %s", res.ContentURI)
		_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendImage failed: %#v", err)
		}
	}
	b.Log.Debugf("result: %#v", res)
}
1372335
func (b *BigIP) Upload(r io.Reader, size int64, path ...string) (*Upload, error) {
	client := &http.Client{
		Transport: b.Transport,
		Timeout:   b.ConfigOptions.APICallTimeout,
	}
	options := &APIRequest{
		Method:      "post",
		URL:         b.iControlPath(path),
		ContentType: "application/octet-stream",
	}
	var format string
	if strings.Contains(options.URL, "mgmt/") {
		format = "%s/%s"
	} else {
		format = "%s/mgmt/%s"
	}
	url := fmt.Sprintf(format, b.Host, options.URL)
	chunkSize := 512 * 1024
	var start, end int64
	for {
		// Read next chunk
		chunk := make([]byte, chunkSize)
		n, err := r.Read(chunk)
		if err != nil {
			return nil, err
		}
		end = start + int64(n)
		// Resize buffer size to number of bytes read
		if n < chunkSize {
			chunk = chunk[:n]
		}
		body := bytes.NewReader(chunk)
		req, _ := http.NewRequest(strings.ToUpper(options.Method), url, body)
		if b.Token != "" {
			req.Header.Set("X-F5-Auth-Token", b.Token)
		} else {
			req.SetBasicAuth(b.User, b.Password)
		}
		req.Header.Add("Content-Type", options.ContentType)
		req.Header.Add("Content-Range", fmt.Sprintf("%d-%d/%d", start, end-1, size))
		// Try to upload chunk
		res, err := client.Do(req)
		if err != nil {
			return nil, err
		}
		data, _ := ioutil.ReadAll(res.Body)
		if res.StatusCode >= 400 {
			if res.Header.Get("Content-Type") == "application/json" {
				return nil, b.checkError(data)
			}

			return nil, fmt.Errorf("HTTP %d :: %s", res.StatusCode, string(data[:]))
		}
		defer res.Body.Close()
		var upload Upload
		err = json.Unmarshal(data, &upload)
		if err != nil {
			return nil, err
		}
		start = end
		if start >= size {
			// Final chunk was uploaded
			return &upload, err
		}
	}
}