refactor and update

This commit is contained in:
YouROK
2020-11-11 12:48:02 +03:00
parent 1ce27ef121
commit b4a20760cc
16 changed files with 324 additions and 260 deletions

View File

@@ -8,7 +8,9 @@ import (
"path/filepath"
"time"
"github.com/anacrolix/missinggo/httptoo"
sets "server/settings"
"server/torr"
"server/torr/state"
"server/utils"
@@ -18,21 +20,17 @@ import (
func allPlayList(c *gin.Context) {
_, fromlast := c.GetQuery("fromlast")
stats := listTorrents()
torrs := torr.ListTorrent()
host := "http://" + c.Request.Host
list := "#EXTM3U\n"
for _, stat := range stats {
list += getM3uList(stat, host, fromlast)
hash := ""
for _, tr := range torrs {
list += getM3uList(tr.Status(), host, fromlast)
hash += tr.Hash().HexString()
}
c.Header("Content-Type", "audio/x-mpegurl")
c.Header("Connection", "close")
c.Header("Content-Disposition", `attachment; filename="all.m3u"`)
http.ServeContent(c.Writer, c.Request, "all.m3u", time.Now(), bytes.NewReader([]byte(list)))
c.Status(200)
sendM3U(c, "all.m3u", hash, list)
}
func playList(c *gin.Context) {
@@ -43,34 +41,43 @@ func playList(c *gin.Context) {
return
}
stats := listTorrents()
var stat *state.TorrentStats
for _, st := range stats {
if st.Hash == hash {
stat = st
tors := torr.ListTorrent()
var tor *torr.Torrent
for _, tr := range tors {
if tr.Hash().HexString() == hash {
tor = tr
break
}
}
if stat == nil {
if tor == nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
// TODO проверить
host := "http://" + c.Request.Host
list := getM3uList(stat, host, fromlast)
list := getM3uList(tor.Status(), host, fromlast)
list = "#EXTM3U\n" + list
sendM3U(c, tor.Name()+".m3u", tor.Hash().HexString(), list)
}
func sendM3U(c *gin.Context, name, hash string, m3u string) {
c.Header("Content-Type", "audio/x-mpegurl")
c.Header("Connection", "close")
c.Header("Content-Disposition", `attachment; filename="playlist.m3u"`)
http.ServeContent(c.Writer, c.Request, "playlist.m3u", time.Now(), bytes.NewReader([]byte(list)))
if hash != "" {
c.Header("ETag", httptoo.EncodeQuotedString(fmt.Sprintf("%s/%s", hash, name)))
}
if name == "" {
name = "playlist.m3u"
}
c.Header("Content-Disposition", `attachment; filename="`+name+`"`)
http.ServeContent(c.Writer, c.Request, name, time.Now(), bytes.NewReader([]byte(m3u)))
c.Status(200)
}
func getM3uList(tor *state.TorrentStats, host string, fromLast bool) string {
func getM3uList(tor *state.TorrentStatus, host string, fromLast bool) string {
m3u := ""
from := 0
if fromLast {
@@ -87,15 +94,20 @@ func getM3uList(tor *state.TorrentStats, host string, fromLast bool) string {
fn = f.Path
}
m3u += "#EXTINF:0," + fn + "\n"
// http://127.0.0.1:8090/stream/fname?link=...&index=0&play
m3u += host + "/stream/" + url.QueryEscape(f.Path) + "?link=" + tor.Hash + "&file=" + fmt.Sprint(f.Id) + "\n"
title := filepath.Base(f.Path)
if tor.Title != "" {
title = tor.Title
} else if tor.Name != "" {
title = tor.Name
}
m3u += host + "/stream/" + url.PathEscape(title) + "?link=" + tor.Hash + "&index=" + fmt.Sprint(f.Id) + "&play\n"
}
}
}
return m3u
}
func searchLastPlayed(tor *state.TorrentStats) int {
func searchLastPlayed(tor *state.TorrentStatus) int {
//TODO проверить
viewed := sets.ListViewed(tor.Hash)
for i := len(tor.FileStats); i > 0; i-- {

View File

@@ -22,6 +22,7 @@ func SetupRouteApi(route *gin.Engine, serv *torr.BTServer) {
route.POST("/settings", settings)
route.POST("/torrents", torrents)
route.POST("/torrent/upload", torrentUpload)
route.GET("/stream", stream)
route.GET("/stream/*fname", stream)

View File

@@ -4,6 +4,7 @@ import (
"net/http"
"net/url"
"strconv"
"strings"
"server/torr"
"server/web/api/utils"
@@ -12,12 +13,17 @@ import (
"github.com/pkg/errors"
)
// http://127.0.0.1:8090/stream/fname?link=...&index=1&stat
// get stat
// http://127.0.0.1:8090/stream/fname?link=...&stat
// get m3u
// http://127.0.0.1:8090/stream/fname?link=...&index=1&m3u
// http://127.0.0.1:8090/stream/fname?link=...&index=1&m3u&fromlast
// stream torrent
// http://127.0.0.1:8090/stream/fname?link=...&index=1&play
// http://127.0.0.1:8090/stream/fname?link=...&save&title=...&poster=...
// http://127.0.0.1:8090/stream/fname?link=...&index=1&play&save
// http://127.0.0.1:8090/stream/fname?link=...&index=1&play&save&title=...&poster=...
// only save
// http://127.0.0.1:8090/stream/fname?link=...&save&title=...&poster=...
func stream(c *gin.Context) {
link := c.Query("link")
@@ -26,6 +32,7 @@ func stream(c *gin.Context) {
_, stat := c.GetQuery("stat")
_, save := c.GetQuery("save")
_, m3u := c.GetQuery("m3u")
_, fromlast := c.GetQuery("fromlast")
_, play := c.GetQuery("play")
title := c.Query("title")
poster := c.Query("poster")
@@ -37,10 +44,13 @@ func stream(c *gin.Context) {
if title == "" {
title = c.Param("fname")
title, _ = url.PathUnescape(title)
title = strings.TrimLeft(title, "/")
} else {
title, _ = url.QueryUnescape(title)
}
link, _ = url.QueryUnescape(link)
title, _ = url.QueryUnescape(title)
poster, _ = url.QueryUnescape(poster)
spec, err := utils.ParseLink(link)
@@ -49,43 +59,16 @@ func stream(c *gin.Context) {
return
}
var tor *torr.Torrent
// find torrent in bts
for _, torrent := range bts.ListTorrents() {
if torrent.Hash().HexString() == spec.InfoHash.HexString() {
tor = torrent
}
tor, err := torr.AddTorrent(spec, title, poster)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// find in db
for _, torrent := range utils.ListTorrents() {
if torrent.Hash().HexString() == spec.InfoHash.HexString() {
tor = torrent
}
}
// add torrent to bts
if tor != nil {
tor, err = torr.NewTorrent(tor.TorrentSpec, bts)
} else {
tor, err = torr.NewTorrent(spec, bts)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}
tor.Title = title
tor.Poster = poster
// save to db
if save {
utils.AddTorrent(tor)
c.Status(200)
}
// wait torrent info
if !tor.GotInfo() {
c.AbortWithError(http.StatusInternalServerError, errors.New("timeout torrent get info"))
return
torr.SaveTorrentToDB(tor)
c.Status(200) // only set status, not return
}
// find file
@@ -98,7 +81,7 @@ func stream(c *gin.Context) {
index = ind
}
}
if index == -1 {
if index == -1 && play { // if file index not set and play file exec
c.AbortWithError(http.StatusBadRequest, errors.New("\"index\" is empty or wrong"))
return
}
@@ -107,14 +90,14 @@ func stream(c *gin.Context) {
tor.Preload(index, 0)
}
// return stat if query
if stat || (!m3u && !play) {
c.JSON(200, tor.Stats())
if stat {
c.JSON(200, tor.Status())
return
} else
// return m3u if query
if m3u {
//TODO m3u
c.JSON(200, tor.Stats())
m3ulist := "#EXTM3U\n" + getM3uList(tor.Status(), "http://"+c.Request.Host, fromlast)
sendM3U(c, tor.Name(), tor.Hash().HexString(), m3ulist)
return
} else
// return play if query
@@ -123,96 +106,3 @@ func stream(c *gin.Context) {
return
}
}
/*
func torrentPlay(c echo.Context) error {
link := c.QueryParam("link")
if link == "" {
return echo.NewHTTPError(http.StatusBadRequest, "link should not be empty")
}
if settings.Get().EnableDebug {
fmt.Println("Play:", c.QueryParams()) // mute log flood on play
}
qsave := c.QueryParam("save")
qpreload := c.QueryParam("preload")
qfile := c.QueryParam("file")
qstat := c.QueryParam("stat")
mm3u := c.QueryParam("m3u")
preload := int64(0)
stat := strings.ToLower(qstat) == "true"
if qpreload != "" {
preload, _ = strconv.ParseInt(qpreload, 10, 64)
if preload > 0 {
preload *= 1024 * 1024
}
}
magnet, infoBytes, err := helpers.GetMagnet(link)
if err != nil {
fmt.Println("Error get magnet:", link, err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
tor := bts.GetTorrent(magnet.InfoHash)
if tor == nil {
tor, err = bts.AddTorrent(*magnet, infoBytes, nil)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
}
if stat {
return c.JSON(http.StatusOK, getTorPlayState(tor))
}
if !tor.WaitInfo() {
return echo.NewHTTPError(http.StatusBadRequest, "torrent closed befor get info")
}
if strings.ToLower(qsave) == "true" {
if t, err := settings.LoadTorrentDB(magnet.InfoHash.HexString()); t == nil && err == nil {
torrDb := toTorrentDB(tor)
if torrDb != nil {
torrDb.InfoBytes = infoBytes
settings.SaveTorrentDB(torrDb)
}
}
}
if strings.ToLower(mm3u) == "true" {
mt := tor.Torrent.Metainfo()
m3u := helpers.MakeM3UPlayList(tor.Stats(), mt.Magnet(tor.Name(), tor.Hash()).String(), c.Scheme()+"://"+c.Request().Host)
c.Response().Header().Set("Content-Type", "audio/x-mpegurl")
c.Response().Header().Set("Connection", "close")
name := utils.CleanFName(tor.Name()) + ".m3u"
c.Response().Header().Set("ETag", httptoo.EncodeQuotedString(fmt.Sprintf("%s/%s", tor.Hash().HexString(), name)))
c.Response().Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
http.ServeContent(c.Response(), c.Request(), name, time.Now(), bytes.NewReader([]byte(m3u)))
return c.NoContent(http.StatusOK)
}
files := helpers.GetPlayableFiles(tor.Stats())
if len(files) == 1 {
file := helpers.FindFile(files[0].Id, tor)
if file == nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprint("File", files[0], "not found in torrent", tor.Name()))
}
return bts.Play(tor, file, preload, c)
}
if qfile == "" && len(files) > 1 {
return c.JSON(http.StatusOK, getTorPlayState(tor))
}
fileInd, _ := strconv.Atoi(qfile)
file := helpers.FindFile(fileInd, tor)
if file == nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprint("File index ", fileInd, " not found in torrent ", tor.Name()))
}
return bts.Play(tor, file, preload, c)
}
*/

View File

@@ -8,7 +8,6 @@ import (
"server/torr/state"
"server/web/api/utils"
"github.com/anacrolix/torrent/metainfo"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
@@ -56,6 +55,11 @@ func torrents(c *gin.Context) {
}
func addTorrent(req torrReqJS, c *gin.Context) {
if req.Link == "" {
c.AbortWithError(http.StatusBadRequest, errors.New("link is empty"))
return
}
log.TLogln("add torrent", req.Link)
torrSpec, err := utils.ParseLink(req.Link)
if err != nil {
@@ -64,44 +68,30 @@ func addTorrent(req torrReqJS, c *gin.Context) {
return
}
torr, err := torr.NewTorrent(torrSpec, bts)
tor, err := torr.AddTorrent(torrSpec, req.Title, req.Poster)
if err != nil {
log.TLogln("error add torrent:", err)
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if !torr.GotInfo() {
log.TLogln("error add torrent:", "timeout connection torrent")
c.AbortWithError(http.StatusNotFound, errors.New("timeout connection torrent"))
return
}
torr.Title = req.Title
torr.Poster = req.Poster
if torr.Title == "" {
torr.Title = torr.Name()
}
if req.SaveToDB {
log.TLogln("save to db:", torr.Torrent.InfoHash().HexString())
utils.AddTorrent(torr)
torr.SaveTorrentToDB(tor)
}
st := torr.Stats()
st := tor.Status()
c.JSON(200, st)
}
func getTorrent(req torrReqJS, c *gin.Context) {
hash := metainfo.NewHashFromHex(req.Hash)
tor := bts.GetTorrent(hash)
if tor == nil {
tor = utils.GetTorrent(hash)
if req.Hash == "" {
c.AbortWithError(http.StatusBadRequest, errors.New("hash is empty"))
return
}
tor := torr.GetTorrent(req.Hash)
if tor != nil {
st := tor.Stats()
st := tor.Status()
c.JSON(200, st)
} else {
c.Status(http.StatusNotFound)
@@ -109,44 +99,28 @@ func getTorrent(req torrReqJS, c *gin.Context) {
}
func remTorrent(req torrReqJS, c *gin.Context) {
hash := metainfo.NewHashFromHex(req.Hash)
bts.RemoveTorrent(hash)
utils.RemTorrent(hash)
if req.Hash == "" {
c.AbortWithError(http.StatusBadRequest, errors.New("hash is empty"))
return
}
torr.RemTorrent(req.Hash)
c.Status(200)
}
func listTorrent(req torrReqJS, c *gin.Context) {
stats := listTorrents()
list := torr.ListTorrent()
var stats []*state.TorrentStatus
for _, tr := range list {
stats = append(stats, tr.Status())
}
c.JSON(200, stats)
}
func listTorrents() []*state.TorrentStats {
btlist := bts.ListTorrents()
dblist := utils.ListTorrents()
var stats []*state.TorrentStats
for _, tr := range btlist {
stats = append(stats, tr.Stats())
}
mainloop:
for _, db := range dblist {
for _, tr := range btlist {
if tr.Hash() == db.Hash() {
continue mainloop
}
}
stats = append(stats, db.Stats())
}
return stats
}
func dropTorrent(req torrReqJS, c *gin.Context) {
if req.Hash == "" {
c.AbortWithError(http.StatusBadRequest, errors.New("hash is empty"))
return
}
hash := metainfo.NewHashFromHex(req.Hash)
bts.RemoveTorrent(hash)
torr.DropTorrent(req.Hash)
c.Status(200)
}

View File

@@ -0,0 +1,51 @@
package api
import (
"net/http"
"github.com/gin-gonic/gin"
"server/log"
"server/torr"
"server/torr/state"
"server/web/api/utils"
)
func torrentUpload(c *gin.Context) {
form, err := c.MultipartForm()
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
defer form.RemoveAll()
save := len(form.Value["save"]) > 0
var retList []*state.TorrentStatus
for name, file := range form.File {
log.TLogln("add torrent file", name)
torrFile, err := file[0].Open()
if err != nil {
log.TLogln("error upload torrent:", err)
continue
}
defer torrFile.Close()
spec, err := utils.ParseFile(torrFile)
if err != nil {
log.TLogln("error upload torrent:", err)
continue
}
tor, err := torr.AddTorrent(spec, "", "")
if err != nil {
log.TLogln("error upload torrent:", err)
continue
}
if save {
torr.SaveTorrentToDB(tor)
}
retList = append(retList, tor.Status())
}
c.JSON(200, retList)
}

View File

@@ -1,54 +0,0 @@
package utils
import (
"time"
"server/settings"
"server/torr"
"server/torr/state"
"github.com/anacrolix/torrent/metainfo"
)
func AddTorrent(torr *torr.Torrent) {
t := new(settings.TorrentDB)
t.TorrentSpec = torr.TorrentSpec
t.Title = torr.Title
t.Poster = torr.Poster
t.Timestamp = time.Now().Unix()
t.Files = torr.Stats().FileStats
settings.AddTorrent(t)
}
func GetTorrent(hash metainfo.Hash) *torr.Torrent {
list := settings.ListTorrent()
for _, db := range list {
if hash == db.InfoHash {
torr := new(torr.Torrent)
torr.TorrentSpec = db.TorrentSpec
torr.Title = db.Title
torr.Poster = db.Poster
torr.Status = state.TorrentInDB
return torr
}
}
return nil
}
func RemTorrent(hash metainfo.Hash) {
settings.RemTorrent(hash)
}
func ListTorrents() []*torr.Torrent {
var ret []*torr.Torrent
list := settings.ListTorrent()
for _, db := range list {
torr := new(torr.Torrent)
torr.TorrentSpec = db.TorrentSpec
torr.Title = db.Title
torr.Poster = db.Poster
torr.Status = state.TorrentInDB
ret = append(ret, torr)
}
return ret
}

View File

@@ -3,6 +3,7 @@ package utils
import (
"errors"
"fmt"
"mime/multipart"
"net/http"
"net/url"
"runtime"
@@ -13,6 +14,25 @@ import (
"github.com/anacrolix/torrent/metainfo"
)
func ParseFile(file multipart.File) (*torrent.TorrentSpec, error) {
minfo, err := metainfo.Load(file)
if err != nil {
return nil, err
}
info, err := minfo.UnmarshalInfo()
if err != nil {
return nil, err
}
mag := minfo.Magnet(info.Name, minfo.HashInfoBytes())
return &torrent.TorrentSpec{
InfoBytes: minfo.InfoBytes,
Trackers: [][]string{mag.Trackers},
DisplayName: info.Name,
InfoHash: minfo.HashInfoBytes(),
}, nil
}
func ParseLink(link string) (*torrent.TorrentSpec, error) {
urlLink, err := url.Parse(link)
if err != nil {
@@ -40,9 +60,14 @@ func fromMagnet(link string) (*torrent.TorrentSpec, error) {
return nil, err
}
var trackers [][]string
if len(mag.Trackers) > 0 {
trackers = [][]string{mag.Trackers}
}
return &torrent.TorrentSpec{
InfoBytes: nil,
Trackers: [][]string{mag.Trackers},
Trackers: trackers,
DisplayName: mag.DisplayName,
InfoHash: mag.InfoHash,
}, nil

View File

@@ -7,6 +7,10 @@ import (
sets "server/settings"
)
/*
file index starts from 1
*/
// Action: set, rem, list
type viewedReqJS struct {
requestI