torrentutils.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package torrentutils
  15. import (
  16. "os"
  17. "github.com/anacrolix/torrent/bencode"
  18. "github.com/anacrolix/torrent/metainfo"
  19. "yunion.io/x/log"
  20. )
  21. func GenerateTorrent(root string, trackers []string, torrentFile string) (*metainfo.MetaInfo, error) {
  22. log.Debugf("generating torrent file ...")
  23. os.Remove(torrentFile)
  24. mi := metainfo.MetaInfo{
  25. AnnounceList: [][]string{},
  26. }
  27. for _, a := range trackers {
  28. mi.AnnounceList = append(mi.AnnounceList, []string{a})
  29. }
  30. mi.SetDefaults()
  31. isPrivate := true
  32. info := metainfo.Info{
  33. PieceLength: 2 * 1024 * 1024,
  34. Private: &isPrivate,
  35. }
  36. err := info.BuildFromFilePath(root)
  37. if err != nil {
  38. return nil, err
  39. }
  40. mi.InfoBytes, err = bencode.Marshal(info)
  41. if err != nil {
  42. return nil, err
  43. }
  44. torrentFp, err := os.Create(torrentFile)
  45. if err != nil {
  46. log.Fatalf("fail to create torrent file %s", err)
  47. }
  48. defer torrentFp.Close()
  49. err = mi.Write(torrentFp)
  50. if err != nil {
  51. return nil, err
  52. }
  53. log.Debugf("generating torrent file %s ...done!", torrentFile)
  54. return &mi, nil
  55. }