Contains the Concourse pipeline definition for building a line-server container
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.8 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "time"
  8. "github.com/andreimarcu/linx-server/backends"
  9. "github.com/andreimarcu/linx-server/expiry"
  10. "github.com/andreimarcu/linx-server/torrent"
  11. "github.com/zeebo/bencode"
  12. "github.com/zenazn/goji/web"
  13. )
  14. func createTorrent(fileName string, f io.Reader, r *http.Request) ([]byte, error) {
  15. url := getSiteURL(r) + Config.selifPath + fileName
  16. chunk := make([]byte, torrent.TORRENT_PIECE_LENGTH)
  17. t := torrent.Torrent{
  18. Encoding: "UTF-8",
  19. Info: torrent.TorrentInfo{
  20. PieceLength: torrent.TORRENT_PIECE_LENGTH,
  21. Name: fileName,
  22. },
  23. UrlList: []string{url},
  24. }
  25. for {
  26. n, err := io.ReadFull(f, chunk)
  27. if err == io.EOF {
  28. break
  29. } else if err != nil && err != io.ErrUnexpectedEOF {
  30. return []byte{}, err
  31. }
  32. t.Info.Length += n
  33. t.Info.Pieces += string(torrent.HashPiece(chunk[:n]))
  34. }
  35. data, err := bencode.EncodeBytes(&t)
  36. if err != nil {
  37. return []byte{}, err
  38. }
  39. return data, nil
  40. }
  41. func fileTorrentHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  42. fileName := c.URLParams["name"]
  43. metadata, f, err := storageBackend.Get(fileName)
  44. if err == backends.NotFoundErr {
  45. notFoundHandler(c, w, r)
  46. return
  47. } else if err == backends.BadMetadata {
  48. oopsHandler(c, w, r, RespAUTO, "Corrupt metadata.")
  49. return
  50. } else if err != nil {
  51. oopsHandler(c, w, r, RespAUTO, err.Error())
  52. return
  53. }
  54. defer f.Close()
  55. if expiry.IsTsExpired(metadata.Expiry) {
  56. storageBackend.Delete(fileName)
  57. notFoundHandler(c, w, r)
  58. return
  59. }
  60. encoded, err := createTorrent(fileName, f, r)
  61. if err != nil {
  62. oopsHandler(c, w, r, RespHTML, "Could not create torrent.")
  63. return
  64. }
  65. w.Header().Set(`Content-Disposition`, fmt.Sprintf(`attachment; filename="%s.torrent"`, fileName))
  66. http.ServeContent(w, r, "", time.Now(), bytes.NewReader(encoded))
  67. }