download.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package repo
  7. import (
  8. "gitote/gitote/pkg/context"
  9. "gitote/gitote/pkg/setting"
  10. "gitote/gitote/pkg/tool"
  11. "io"
  12. "path"
  13. "gitlab.com/gitote/git-module"
  14. )
  15. // ServeData download file from io.Reader
  16. func ServeData(c *context.Context, name string, reader io.Reader) error {
  17. buf := make([]byte, 1024)
  18. n, _ := reader.Read(buf)
  19. if n >= 0 {
  20. buf = buf[:n]
  21. }
  22. if !tool.IsTextFile(buf) {
  23. if !tool.IsImageFile(buf) {
  24. c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"")
  25. c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  26. }
  27. } else if !setting.Repository.EnableRawFileRenderMode || !c.QueryBool("render") {
  28. c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  29. }
  30. c.Resp.Write(buf)
  31. _, err := io.Copy(c.Resp, reader)
  32. return err
  33. }
  34. // ServeBlob download a git.Blob
  35. func ServeBlob(c *context.Context, blob *git.Blob) error {
  36. dataRc, err := blob.Data()
  37. if err != nil {
  38. return err
  39. }
  40. return ServeData(c, path.Base(c.Repo.TreePath), dataRc)
  41. }
  42. // SingleDownload download a file by repos path
  43. func SingleDownload(c *context.Context) {
  44. blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath)
  45. if err != nil {
  46. if git.IsErrNotExist(err) {
  47. c.Handle(404, "GetBlobByPath", nil)
  48. } else {
  49. c.Handle(500, "GetBlobByPath", err)
  50. }
  51. return
  52. }
  53. if err = ServeBlob(c, blob); err != nil {
  54. c.Handle(500, "ServeBlob", err)
  55. }
  56. }