Skip to content

Commit

Permalink
feat: Fetch README as description
Browse files Browse the repository at this point in the history
  • Loading branch information
pojntfx committed Jun 28, 2022
1 parent 77143db commit 33740be
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 47 deletions.
48 changes: 34 additions & 14 deletions cmd/htorrent/cmd/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,17 @@ package cmd

import (
"context"
"encoding/csv"
"errors"
"fmt"
"net/url"
"os"
"regexp"
"strings"
"time"

"github.com/pojntfx/htorrent/pkg/client"
"github.com/pojntfx/htorrent/pkg/server"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)

const (
Expand All @@ -29,6 +27,19 @@ var (
errNoPathMatchesExpression = errors.New("could not find a path that matches the supplied expression")
)

type infoWithStreamURL struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
CreationDate int64 `yaml:"creationDate"`
Files []fileWithStreamURL `yaml:"files"`
}

type fileWithStreamURL struct {
Path string `yaml:"path"`
Length int64 `yaml:"length"`
StreamURL string `yaml:"streamURL"`
}

var infoCmd = &cobra.Command{
Use: "info",
Aliases: []string{"i"},
Expand Down Expand Up @@ -60,33 +71,42 @@ var infoCmd = &cobra.Command{
ctx,
)

files, err := manager.GetInfo(viper.GetString(magnetFlag))
info, err := manager.GetInfo(viper.GetString(magnetFlag))
if err != nil {
return err
}

if strings.TrimSpace(viper.GetString(expressionFlag)) == "" {
w := csv.NewWriter(os.Stdout)
defer w.Flush()

if err := w.Write([]string{"path", "length", "creationTime", "streamURL"}); err != nil {
return err
i := infoWithStreamURL{
Name: info.Name,
Description: info.Description,
CreationDate: info.CreationDate,
Files: []fileWithStreamURL{},
}

for _, f := range files {
for _, f := range info.Files {
streamURL, err := getStreamURL(viper.GetString(raddrFlag), viper.GetString(magnetFlag), f.Path)
if err != nil {
return err
}

if err := w.Write([]string{f.Path, fmt.Sprintf("%v", f.Length), time.Unix(f.CreationDate, 0).Format(time.RFC3339), streamURL}); err != nil {
return err
}
i.Files = append(i.Files, fileWithStreamURL{
Path: f.Path,
Length: f.Length,
StreamURL: streamURL,
})
}

y, err := yaml.Marshal(i)
if err != nil {
return err
}

fmt.Printf("%s", y)
} else {
exp := regexp.MustCompile(viper.GetString(expressionFlag))

for _, f := range files {
for _, f := range info.Files {
if exp.Match([]byte(f.Path)) {
streamURL, err := getStreamURL(viper.GetString(raddrFlag), viper.GetString(magnetFlag), f.Path)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/rs/zerolog v1.27.0
github.com/spf13/cobra v1.4.0
github.com/spf13/viper v1.12.0
gopkg.in/yaml.v3 v3.0.1
)

require (
Expand Down Expand Up @@ -96,5 +97,4 @@ require (
gopkg.in/ini.v1 v1.66.4 // indirect
gopkg.in/square/go-jose.v2 v2.5.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0 // indirect
)
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -823,8 +823,8 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA=
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
12 changes: 9 additions & 3 deletions pkg/api/http/v1/info.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package v1

type Info struct {
Name string `json:"name"`
Description string `json:"description"`
CreationDate int64 `json:"creationDate"`
Files []File `json:"files"`
}

type File struct {
Path string `json:"path"`
Length int64 `json:"length"`
CreationDate int64 `json:"creationTime"`
Path string `json:"path"`
Length int64 `json:"length"`
}
28 changes: 14 additions & 14 deletions pkg/client/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,47 +35,47 @@ func NewManager(
}
}

func (m *Manager) GetInfo(magnetLink string) ([]v1.File, error) {
func (m *Manager) GetInfo(magnetLink string) (v1.Info, error) {
hc := &http.Client{}

baseURL, err := url.Parse(m.url)
if err != nil {
return nil, err
return v1.Info{}, err
}

infoSuffix, err := url.Parse("/info")
if err != nil {
return nil, err
return v1.Info{}, err
}

info := baseURL.ResolveReference(infoSuffix)
infoURL := baseURL.ResolveReference(infoSuffix)

q := info.Query()
q := infoURL.Query()
q.Set("magnet", magnetLink)
info.RawQuery = q.Encode()
infoURL.RawQuery = q.Encode()

req, err := http.NewRequest(http.MethodGet, info.String(), http.NoBody)
req, err := http.NewRequest(http.MethodGet, infoURL.String(), http.NoBody)
if err != nil {
return nil, err
return v1.Info{}, err
}
req.SetBasicAuth(m.username, m.password)

res, err := hc.Do(req)
if err != nil {
return nil, err
return v1.Info{}, err
}
if res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode != http.StatusOK {
return nil, errors.New(res.Status)
return v1.Info{}, errors.New(res.Status)
}

files := []v1.File{}
info := v1.Info{}
dec := json.NewDecoder(res.Body)
if err := dec.Decode(&files); err != nil {
return nil, err
if err := dec.Decode(&info); err != nil {
return v1.Info{}, err
}

return files, nil
return info, nil
}
47 changes: 34 additions & 13 deletions pkg/server/gateway.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package server

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"path"
"strings"
"time"

Expand Down Expand Up @@ -124,22 +127,45 @@ func (g *Gateway) Open() error {
}
<-t.GotInfo()

files := []v1.File{}
info := v1.Info{
Files: []v1.File{},
}
info.Name = t.Info().BestName()
info.CreationDate = t.Metainfo().CreationDate

foundDescription := false
for _, f := range t.Files() {
log.Debug().
Str("magnet", magnetLink).
Str("path", f.Path()).
Msg("Got info")

files = append(files, v1.File{
Path: f.Path(),
Length: f.Length(),
CreationDate: f.Torrent().Metainfo().CreationDate,
info.Files = append(info.Files, v1.File{
Path: f.Path(),
Length: f.Length(),
})

if path.Ext(f.Path()) == ".txt" {
if foundDescription {
continue
}

r := f.NewReader()
defer r.Close()

var description bytes.Buffer
if _, err := io.Copy(&description, r); err != nil {
panic(err)
}

info.Description = description.String()

foundDescription = true
}
}

enc := json.NewEncoder(w)
if err := enc.Encode(files); err != nil {
if err := enc.Encode(info); err != nil {
panic(err)
}
})
Expand All @@ -149,14 +175,8 @@ func (g *Gateway) Open() error {
err := recover()

switch err {
case nil:
fallthrough
case http.StatusUnauthorized:
fallthrough
case http.StatusUnprocessableEntity:
fallthrough
case http.StatusNotFound:
fallthrough
default:
w.WriteHeader(http.StatusInternalServerError)

Expand All @@ -173,7 +193,8 @@ func (g *Gateway) Open() error {

u, p, ok := r.BasicAuth()
if err := auth.Validate(u, p); !ok || err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Header().Set("WWW-Authenticate", `Basic realm="hTorrent"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)

panic(fmt.Errorf("%v", http.StatusUnauthorized))
}
Expand Down

0 comments on commit 33740be

Please sign in to comment.