Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

337 linhas
10 KiB

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