media.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gensupport
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "mime/multipart"
  11. "net/http"
  12. "net/textproto"
  13. "strings"
  14. "google.golang.org/api/googleapi"
  15. )
  16. const sniffBuffSize = 512
  17. func newContentSniffer(r io.Reader) *contentSniffer {
  18. return &contentSniffer{r: r}
  19. }
  20. // contentSniffer wraps a Reader, and reports the content type determined by sniffing up to 512 bytes from the Reader.
  21. type contentSniffer struct {
  22. r io.Reader
  23. start []byte // buffer for the sniffed bytes.
  24. err error // set to any error encountered while reading bytes to be sniffed.
  25. ctype string // set on first sniff.
  26. sniffed bool // set to true on first sniff.
  27. }
  28. func (cs *contentSniffer) Read(p []byte) (n int, err error) {
  29. // Ensure that the content type is sniffed before any data is consumed from Reader.
  30. _, _ = cs.ContentType()
  31. if len(cs.start) > 0 {
  32. n := copy(p, cs.start)
  33. cs.start = cs.start[n:]
  34. return n, nil
  35. }
  36. // We may have read some bytes into start while sniffing, even if the read ended in an error.
  37. // We should first return those bytes, then the error.
  38. if cs.err != nil {
  39. return 0, cs.err
  40. }
  41. // Now we have handled all bytes that were buffered while sniffing. Now just delegate to the underlying reader.
  42. return cs.r.Read(p)
  43. }
  44. // ContentType returns the sniffed content type, and whether the content type was succesfully sniffed.
  45. func (cs *contentSniffer) ContentType() (string, bool) {
  46. if cs.sniffed {
  47. return cs.ctype, cs.ctype != ""
  48. }
  49. cs.sniffed = true
  50. // If ReadAll hits EOF, it returns err==nil.
  51. cs.start, cs.err = ioutil.ReadAll(io.LimitReader(cs.r, sniffBuffSize))
  52. // Don't try to detect the content type based on possibly incomplete data.
  53. if cs.err != nil {
  54. return "", false
  55. }
  56. cs.ctype = http.DetectContentType(cs.start)
  57. return cs.ctype, true
  58. }
  59. // DetermineContentType determines the content type of the supplied reader.
  60. // If the content type is already known, it can be specified via ctype.
  61. // Otherwise, the content of media will be sniffed to determine the content type.
  62. // If media implements googleapi.ContentTyper (deprecated), this will be used
  63. // instead of sniffing the content.
  64. // After calling DetectContentType the caller must not perform further reads on
  65. // media, but rather read from the Reader that is returned.
  66. func DetermineContentType(media io.Reader, ctype string) (io.Reader, string) {
  67. // Note: callers could avoid calling DetectContentType if ctype != "",
  68. // but doing the check inside this function reduces the amount of
  69. // generated code.
  70. if ctype != "" {
  71. return media, ctype
  72. }
  73. // For backwards compatability, allow clients to set content
  74. // type by providing a ContentTyper for media.
  75. if typer, ok := media.(googleapi.ContentTyper); ok {
  76. return media, typer.ContentType()
  77. }
  78. sniffer := newContentSniffer(media)
  79. if ctype, ok := sniffer.ContentType(); ok {
  80. return sniffer, ctype
  81. }
  82. // If content type could not be sniffed, reads from sniffer will eventually fail with an error.
  83. return sniffer, ""
  84. }
  85. type typeReader struct {
  86. io.Reader
  87. typ string
  88. }
  89. // multipartReader combines the contents of multiple readers to creat a multipart/related HTTP body.
  90. // Close must be called if reads from the multipartReader are abandoned before reaching EOF.
  91. type multipartReader struct {
  92. pr *io.PipeReader
  93. pipeOpen bool
  94. ctype string
  95. }
  96. func newMultipartReader(parts []typeReader) *multipartReader {
  97. mp := &multipartReader{pipeOpen: true}
  98. var pw *io.PipeWriter
  99. mp.pr, pw = io.Pipe()
  100. mpw := multipart.NewWriter(pw)
  101. mp.ctype = "multipart/related; boundary=" + mpw.Boundary()
  102. go func() {
  103. for _, part := range parts {
  104. w, err := mpw.CreatePart(typeHeader(part.typ))
  105. if err != nil {
  106. mpw.Close()
  107. pw.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", err))
  108. return
  109. }
  110. _, err = io.Copy(w, part.Reader)
  111. if err != nil {
  112. mpw.Close()
  113. pw.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", err))
  114. return
  115. }
  116. }
  117. mpw.Close()
  118. pw.Close()
  119. }()
  120. return mp
  121. }
  122. func (mp *multipartReader) Read(data []byte) (n int, err error) {
  123. return mp.pr.Read(data)
  124. }
  125. func (mp *multipartReader) Close() error {
  126. if !mp.pipeOpen {
  127. return nil
  128. }
  129. mp.pipeOpen = false
  130. return mp.pr.Close()
  131. }
  132. // CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body.
  133. // It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary.
  134. //
  135. // The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF.
  136. func CombineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType string) (io.ReadCloser, string) {
  137. mp := newMultipartReader([]typeReader{
  138. {body, bodyContentType},
  139. {media, mediaContentType},
  140. })
  141. return mp, mp.ctype
  142. }
  143. func typeHeader(contentType string) textproto.MIMEHeader {
  144. h := make(textproto.MIMEHeader)
  145. if contentType != "" {
  146. h.Set("Content-Type", contentType)
  147. }
  148. return h
  149. }
  150. // PrepareUpload determines whether the data in the supplied reader should be
  151. // uploaded in a single request, or in sequential chunks.
  152. // chunkSize is the size of the chunk that media should be split into.
  153. //
  154. // If chunkSize is zero, media is returned as the first value, and the other
  155. // two return values are nil, true.
  156. //
  157. // Otherwise, a MediaBuffer is returned, along with a bool indicating whether the
  158. // contents of media fit in a single chunk.
  159. //
  160. // After PrepareUpload has been called, media should no longer be used: the
  161. // media content should be accessed via one of the return values.
  162. func PrepareUpload(media io.Reader, chunkSize int) (r io.Reader, mb *MediaBuffer, singleChunk bool) {
  163. if chunkSize == 0 { // do not chunk
  164. return media, nil, true
  165. }
  166. mb = NewMediaBuffer(media, chunkSize)
  167. _, _, _, err := mb.Chunk()
  168. // If err is io.EOF, we can upload this in a single request. Otherwise, err is
  169. // either nil or a non-EOF error. If it is the latter, then the next call to
  170. // mb.Chunk will return the same error. Returning a MediaBuffer ensures that this
  171. // error will be handled at some point.
  172. return nil, mb, err == io.EOF
  173. }
  174. // MediaInfo holds information for media uploads. It is intended for use by generated
  175. // code only.
  176. type MediaInfo struct {
  177. // At most one of Media and MediaBuffer will be set.
  178. media io.Reader
  179. buffer *MediaBuffer
  180. singleChunk bool
  181. mType string
  182. size int64 // mediaSize, if known. Used only for calls to progressUpdater_.
  183. progressUpdater googleapi.ProgressUpdater
  184. }
  185. // NewInfoFromMedia should be invoked from the Media method of a call. It returns a
  186. // MediaInfo populated with chunk size and content type, and a reader or MediaBuffer
  187. // if needed.
  188. func NewInfoFromMedia(r io.Reader, options []googleapi.MediaOption) *MediaInfo {
  189. mi := &MediaInfo{}
  190. opts := googleapi.ProcessMediaOptions(options)
  191. if !opts.ForceEmptyContentType {
  192. r, mi.mType = DetermineContentType(r, opts.ContentType)
  193. }
  194. mi.media, mi.buffer, mi.singleChunk = PrepareUpload(r, opts.ChunkSize)
  195. return mi
  196. }
  197. // NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a
  198. // call. It returns a MediaInfo using the given reader, size and media type.
  199. func NewInfoFromResumableMedia(r io.ReaderAt, size int64, mediaType string) *MediaInfo {
  200. rdr := ReaderAtToReader(r, size)
  201. rdr, mType := DetermineContentType(rdr, mediaType)
  202. return &MediaInfo{
  203. size: size,
  204. mType: mType,
  205. buffer: NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize),
  206. media: nil,
  207. singleChunk: false,
  208. }
  209. }
  210. func (mi *MediaInfo) SetProgressUpdater(pu googleapi.ProgressUpdater) {
  211. if mi != nil {
  212. mi.progressUpdater = pu
  213. }
  214. }
  215. // UploadType determines the type of upload: a single request, or a resumable
  216. // series of requests.
  217. func (mi *MediaInfo) UploadType() string {
  218. if mi.singleChunk {
  219. return "multipart"
  220. }
  221. return "resumable"
  222. }
  223. // UploadRequest sets up an HTTP request for media upload. It adds headers
  224. // as necessary, and returns a replacement for the body and a function for http.Request.GetBody.
  225. func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newBody io.Reader, getBody func() (io.ReadCloser, error), cleanup func()) {
  226. cleanup = func() {}
  227. if mi == nil {
  228. return body, nil, cleanup
  229. }
  230. var media io.Reader
  231. if mi.media != nil {
  232. // This only happens when the caller has turned off chunking. In that
  233. // case, we write all of media in a single non-retryable request.
  234. media = mi.media
  235. } else if mi.singleChunk {
  236. // The data fits in a single chunk, which has now been read into the MediaBuffer.
  237. // We obtain that chunk so we can write it in a single request. The request can
  238. // be retried because the data is stored in the MediaBuffer.
  239. media, _, _, _ = mi.buffer.Chunk()
  240. }
  241. if media != nil {
  242. fb := readerFunc(body)
  243. fm := readerFunc(media)
  244. combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType)
  245. if fb != nil && fm != nil {
  246. getBody = func() (io.ReadCloser, error) {
  247. rb := ioutil.NopCloser(fb())
  248. rm := ioutil.NopCloser(fm())
  249. r, _ := CombineBodyMedia(rb, "application/json", rm, mi.mType)
  250. return r, nil
  251. }
  252. }
  253. cleanup = func() { combined.Close() }
  254. reqHeaders.Set("Content-Type", ctype)
  255. body = combined
  256. }
  257. if mi.buffer != nil && mi.mType != "" && !mi.singleChunk {
  258. reqHeaders.Set("X-Upload-Content-Type", mi.mType)
  259. }
  260. return body, getBody, cleanup
  261. }
  262. // readerFunc returns a function that always returns an io.Reader that has the same
  263. // contents as r, provided that can be done without consuming r. Otherwise, it
  264. // returns nil.
  265. // See http.NewRequest (in net/http/request.go).
  266. func readerFunc(r io.Reader) func() io.Reader {
  267. switch r := r.(type) {
  268. case *bytes.Buffer:
  269. buf := r.Bytes()
  270. return func() io.Reader { return bytes.NewReader(buf) }
  271. case *bytes.Reader:
  272. snapshot := *r
  273. return func() io.Reader { r := snapshot; return &r }
  274. case *strings.Reader:
  275. snapshot := *r
  276. return func() io.Reader { r := snapshot; return &r }
  277. default:
  278. return nil
  279. }
  280. }
  281. // ResumableUpload returns an appropriately configured ResumableUpload value if the
  282. // upload is resumable, or nil otherwise.
  283. func (mi *MediaInfo) ResumableUpload(locURI string) *ResumableUpload {
  284. if mi == nil || mi.singleChunk {
  285. return nil
  286. }
  287. return &ResumableUpload{
  288. URI: locURI,
  289. Media: mi.buffer,
  290. MediaType: mi.mType,
  291. Callback: func(curr int64) {
  292. if mi.progressUpdater != nil {
  293. mi.progressUpdater(curr, mi.size)
  294. }
  295. },
  296. }
  297. }