Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/ADDING_A_SITE.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ A direct port makes its request when it is called. It must:
- fail closed: a login page is unauthenticated, and a maintenance, challenge,
or unrecognized response is an error, never an empty result.

A `TorrentSearcher` may also implement `OptionTorrentSearcher` to take
`site.SearchOptions`: a page, a site-defined mode, category IDs, and a
free-only filter, behind `site search --page`, `--mode`, `--category`, and
`--free`. `ValidateSearchOptions` must refuse anything the site cannot honor;
the CLI calls it before the credential is read and turns its error into a
usage error. A site without the port refuses those flags.

The CLI replaces every error from a direct port with a fixed
`site <command> failed` message, keeping only typed cancellation and deadline
causes, so adapter error text never reaches the user.
Expand Down
18 changes: 16 additions & 2 deletions docs/MTEAM_ADAPTER.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ ptctl site status mteam
ptctl site account mteam
ptctl site search mteam "Ubuntu"
ptctl site search --output json mteam "Ubuntu"
ptctl site search --page 2 --category 419,439 --free mteam "Ubuntu"
ptctl site detail mteam REMOTE_ID
ptctl site metafile fetch --acknowledge-site-effect --metafile-store "$PTCTL_STORE" mteam REMOTE_ID
```
Expand Down Expand Up @@ -81,7 +82,7 @@ see [Metafile download](#metafile-download)):
| Command | Request | Body |
|---|---|---|
| `site status`, `site account` | `POST /api/member/profile` | an empty `multipart/form-data` form |
| `site search` | `POST /api/torrent/search` | `{"mode":"normal","keyword":QUERY,"pageNumber":1,"pageSize":50}` |
| `site search` | `POST /api/torrent/search` | `{"mode":"normal","keyword":QUERY,"pageNumber":1,"pageSize":50}`; the options below add `categories` and `discount` and change `mode` and `pageNumber` |
| `site detail` | `POST /api/torrent/detail` | a `multipart/form-data` form with the one field `id` |

The API exposes these reads as POST requests. All three endpoints only read;
Expand Down Expand Up @@ -112,7 +113,20 @@ limiter that spans processes.
counter that is missing or malformed is left absent rather than guessed, but a
profile without a username is an error rather than a partial account.

**Search.** The first page of up to 50 results in normal mode. Each row has the
**Search.** One page of up to 50 results, by default the first page in
normal mode. Options narrow it, still in one request:

| Option | API field | Accepts |
|---|---|---|
| `--page N` | `pageNumber` | 1 to 1000 |
| `--mode MODE` | `mode` | `normal` (films, series, music, and the rest) or `adult`; adult categories need `--mode adult` |
| `--category ID` | `categories` | Category IDs from the table under **Categories**, repeated or comma-separated, at most 32 |
| `--free` | `discount: "FREE"` | Torrents whose download is not counted; rows the API returns with any other promotion are dropped, so a page can hold fewer than 50 rows |

A page past the last one is empty. Invalid options are usage errors (exit 2)
before the key is read or any request is sent.

Each row has the
ref `mteam/ID`, name, size, category ID and name, publish time, seeders,
leechers, completed count, and promotion. The table view adds `SEEDERS`,
`LEECHERS`, `PROMOTION`, and, last, `CATEGORY` columns. A response without a
Expand Down
4 changes: 3 additions & 1 deletion docs/guide/sites.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ if the API does not accept it. Scripts save it with `site login --api-key-stdin
mteam`, or pipe it to a single command with `--api-key-stdin`. `status`,
`account`, `search`, and `detail` each send one read-only POST to M-Team's JSON
API and never retry; search results add seeders, leechers, promotion, and
category-name columns. `site metafile fetch` downloads one `.torrent` into the
category-name columns, and `search` takes `--page N`, `--mode normal|adult`,
`--category ID`, and `--free`. `site metafile fetch` downloads one `.torrent` into the
private store through M-Team's signed link, as described in
[metafiles.md](metafiles.md). Bonus commands are not available for M-Team yet,
and `reconcile` reads live site detail with a cookie only. Setup, results, and
Expand All @@ -171,6 +172,7 @@ ptctl site login mteam
ptctl site status mteam
ptctl site account mteam
ptctl site search mteam "Ubuntu"
ptctl site search --page 2 --free mteam "Ubuntu"
ptctl site detail mteam REMOTE_ID
printf '%s' "$MTEAM_API_KEY" | ptctl site status --api-key-stdin mteam
```
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ Usage:
ptctl site logout [--output table|json] SITE
ptctl site status [--cookie-stdin | --api-key-stdin] [--output table|json] SITE
ptctl site account [--cookie-stdin | --api-key-stdin] [--output table|json] SITE
ptctl site search [--cookie-stdin | --api-key-stdin] [--output table|json] SITE QUERY...
ptctl site search [--cookie-stdin | --api-key-stdin] [--page N] [--mode MODE] [--category ID]... [--free] [--output table|json] SITE QUERY...
ptctl site detail [--cookie-stdin | --api-key-stdin] [--output table|json] SITE REMOTE_ID
ptctl site bonus-catalog [--cookie-stdin] [--output table|json] SITE
ptctl site bonus review [--cookie-stdin] [--output table|json] SITE OPTION
Expand Down
44 changes: 44 additions & 0 deletions internal/cli/site.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cli
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
Expand Down Expand Up @@ -120,6 +121,13 @@ func (a *app) siteRead(command string, args []string) error {
output := fs.String("output", "table", "table or json")
cookieStdin := fs.Bool("cookie-stdin", false, "read session Cookie header value from stdin")
apiKeyStdin := fs.Bool("api-key-stdin", false, "read a site-issued API key from stdin")
var searchOptions site.SearchOptions
if command == "search" {
fs.IntVar(&searchOptions.Page, "page", 0, "result page, from 1 (default: the first page)")
fs.StringVar(&searchOptions.Mode, "mode", "", "site search area, such as normal or adult on M-Team")
fs.Var((*categoryListFlag)(&searchOptions.Categories), "category", "keep only this site category ID; repeat or separate with commas")
fs.BoolVar(&searchOptions.FreeOnly, "free", false, "keep only torrents whose download is not counted")
}
if err := fs.Parse(args); err != nil {
return usageError("site %s: %v", command, err)
}
Expand Down Expand Up @@ -191,6 +199,23 @@ func (a *app) siteRead(command string, args []string) error {
read = func(ctx context.Context, credential site.Credential) (any, error) {
return reader.Search(ctx, credential, query)
}
pageSet := false
fs.Visit(func(flag *flag.Flag) { pageSet = pageSet || flag.Name == "page" })
if pageSet && searchOptions.Page < 1 {
return usageError("--page must be 1 or more")
}
if !searchOptions.IsZero() {
optionReader, ok := adapter.(site.OptionTorrentSearcher)
if !ok {
return usageError("site %q does not support --page, --mode, --category, or --free", descriptor.ID)
}
if err := optionReader.ValidateSearchOptions(searchOptions); err != nil {
return usageError("%v", err)
}
read = func(ctx context.Context, credential site.Credential) (any, error) {
return optionReader.SearchWithOptions(ctx, credential, query, searchOptions)
}
}
case "bonus-catalog":
reader, ok := adapter.(site.BonusCatalogReader)
if !ok {
Expand Down Expand Up @@ -376,3 +401,22 @@ func promotionLabel(promotion *domain.Promotion) string {
}
return label
}

// categoryListFlag collects site category IDs from repeated or
// comma-separated --category values.
type categoryListFlag []string

func (values *categoryListFlag) String() string {
return strings.Join(*values, ",")
}

func (values *categoryListFlag) Set(value string) error {
for _, category := range strings.Split(value, ",") {
category = strings.TrimSpace(category)
if category == "" {
return fmt.Errorf("category must not be empty")
}
*values = append(*values, category)
}
return nil
}
110 changes: 110 additions & 0 deletions internal/cli/site_search_options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package cli

import (
"bytes"
"context"
"errors"
"fmt"
"reflect"
"strings"
"testing"

"github.com/tonycoder-hub/ptctl/internal/domain"
"github.com/tonycoder-hub/ptctl/internal/site"
)

// optionSearchAdapter is an API-key site whose search takes options.
type optionSearchAdapter struct {
apiKeySiteAdapter
options site.SearchOptions
optionCalls int
plainCalls int
validateErr error
validateSeen []site.SearchOptions
}

func (adapter *optionSearchAdapter) Search(ctx context.Context, credential site.Credential, query string) ([]domain.TorrentSummary, error) {
adapter.plainCalls++
return adapter.apiKeySiteAdapter.Search(ctx, credential, query)
}

func (adapter *optionSearchAdapter) ValidateSearchOptions(options site.SearchOptions) error {
adapter.validateSeen = append(adapter.validateSeen, options)
return adapter.validateErr
}

func (adapter *optionSearchAdapter) SearchWithOptions(_ context.Context, credential site.Credential, _ string, options site.SearchOptions) ([]domain.TorrentSummary, error) {
adapter.record(credential)
adapter.optionCalls++
adapter.options = options
return adapter.results, adapter.err
}

func TestSiteSearchPassesOptionsToTheSite(t *testing.T) {
adapter := &optionSearchAdapter{}
var out bytes.Buffer
a := &app{stdin: strings.NewReader(apiKeyCanary), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)}
if err := a.siteRead("search", []string{
"--api-key-stdin", "--page", "2", "--mode", "adult", "--category", "410,424", "--category", " 431 ", "--free", "--output", "json", "api-key-test", "canary",
}); err != nil {
t.Fatal(err)
}
want := site.SearchOptions{Page: 2, Mode: "adult", Categories: []string{"410", "424", "431"}, FreeOnly: true}
if adapter.optionCalls != 1 || adapter.plainCalls != 0 || !reflect.DeepEqual(adapter.options, want) || adapter.secret != apiKeyCanary {
t.Fatalf("option calls=%d plain=%d options=%#v", adapter.optionCalls, adapter.plainCalls, adapter.options)
}

// Without options the site's plain search runs, as before.
adapter = &optionSearchAdapter{}
a = &app{stdin: strings.NewReader(apiKeyCanary), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)}
if err := a.siteRead("search", []string{"--api-key-stdin", "--output", "json", "api-key-test", "canary"}); err != nil {
t.Fatal(err)
}
if adapter.optionCalls != 0 || adapter.plainCalls != 1 || len(adapter.validateSeen) != 0 {
t.Fatalf("option calls=%d plain=%d", adapter.optionCalls, adapter.plainCalls)
}
}

func TestSiteSearchOptionsAreRefusedBeforeStdin(t *testing.T) {
for _, test := range []struct {
name string
adapter site.Adapter
args []string
want string
}{
{name: "site without options", adapter: &apiKeySiteAdapter{}, args: []string{"--page", "2"},
want: `site "api-key-test" does not support --page, --mode, --category, or --free`},
{name: "page zero", adapter: &optionSearchAdapter{}, args: []string{"--page", "0"}, want: "--page must be 1 or more"},
{name: "negative page", adapter: &optionSearchAdapter{}, args: []string{"--page", "-1"}, want: "--page must be 1 or more"},
{name: "empty category", adapter: &optionSearchAdapter{}, args: []string{"--category", "401,"},
want: `site search: invalid value "401," for flag -category: category must not be empty`},
{name: "site rejects", adapter: &optionSearchAdapter{validateErr: errors.New("search mode must be normal or adult")}, args: []string{"--mode", "rss"},
want: "search mode must be normal or adult"},
} {
t.Run(test.name, func(t *testing.T) {
reader := &trackingReader{}
var out bytes.Buffer
a := &app{stdin: reader, stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(test.adapter)}
args := append(append([]string{"--api-key-stdin"}, test.args...), "api-key-test", "canary")
err := a.siteRead("search", args)
var usage *usageErr
if !errors.As(err, &usage) || err.Error() != test.want || reader.read || out.Len() != 0 {
t.Fatalf("err=%v read=%t stdout=%q", err, reader.read, out.String())
}
})
}
}

func TestSearchOptionFlagsBelongOnlyToSearch(t *testing.T) {
for _, command := range []string{"status", "account", "bonus-catalog"} {
for _, flag := range []string{"--page=2", "--mode=adult", "--category=401", "--free"} {
reader := &trackingReader{}
a := &app{stdin: reader, stdout: ioDiscard{}, stderr: ioDiscard{}, registry: site.NewRegistry(&optionSearchAdapter{})}
err := a.siteRead(command, []string{"--api-key-stdin", flag, "api-key-test"})
var usage *usageErr
if !errors.As(err, &usage) || !strings.Contains(err.Error(), fmt.Sprintf("flag provided but not defined: -%s", strings.TrimPrefix(strings.SplitN(flag, "=", 2)[0], "--"))) || reader.read {
t.Fatalf("%s %s err=%v read=%t", command, flag, err, reader.read)
}
}
}
}
29 changes: 29 additions & 0 deletions internal/site/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,35 @@ type TorrentSearcher interface {
Search(context.Context, Credential, string) ([]domain.TorrentSummary, error)
}

// SearchOptions narrows one search beyond its query. The zero value asks for
// the site's default first page, the same search TorrentSearcher.Search runs.
type SearchOptions struct {
// Page is 1-based; zero means the first page.
Page int
// Mode is a site-defined search area, such as M-Team's "adult"; empty
// means the site's default area.
Mode string
// Categories keeps only torrents in these site category IDs.
Categories []string
// FreeOnly keeps only torrents whose download is not counted.
FreeOnly bool
}

// IsZero reports whether the options ask for nothing beyond the default
// first page.
func (options SearchOptions) IsZero() bool {
return options.Page == 0 && options.Mode == "" && len(options.Categories) == 0 && !options.FreeOnly
}

// OptionTorrentSearcher is a TorrentSearcher that also takes SearchOptions.
// ValidateSearchOptions runs before any credential is read, so an option the
// site cannot honor is refused without a request.
type OptionTorrentSearcher interface {
TorrentSearcher
ValidateSearchOptions(SearchOptions) error
SearchWithOptions(context.Context, Credential, string, SearchOptions) ([]domain.TorrentSummary, error)
}

type BonusCatalogReader interface {
BonusCatalog(context.Context, Credential) (domain.BonusCatalog, error)
}
Expand Down
28 changes: 0 additions & 28 deletions internal/site/mteam/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"unicode/utf8"

"github.com/tonycoder-hub/ptctl/internal/domain"
"github.com/tonycoder-hub/ptctl/internal/site"
Expand Down Expand Up @@ -126,32 +124,6 @@ func (a *Adapter) Account(ctx context.Context, credential site.Credential) (doma
return profile, nil
}

func (a *Adapter) Search(ctx context.Context, credential site.Credential, query string) ([]domain.TorrentSummary, error) {
query = strings.TrimSpace(query)
if query == "" {
return nil, fmt.Errorf("search query is empty")
}
if len(query) > maxQueryBytes || !utf8.ValidString(query) || hasControlRune(query) {
return nil, fmt.Errorf("M-Team search query must be at most %d bytes of printable UTF-8", maxQueryBytes)
}
body, err := json.Marshal(searchRequest{Mode: "normal", Keyword: query, PageNumber: 1, PageSize: searchPageSize})
if err != nil {
return nil, fmt.Errorf("encode M-Team search request failed")
}
data, err := a.call(ctx, credential, searchPath, jsonMediaType, body)
if err != nil {
return nil, err
}
return parseSearch(data)
}

type searchRequest struct {
Mode string `json:"mode"`
Keyword string `json:"keyword"`
PageNumber int `json:"pageNumber"`
PageSize int `json:"pageSize"`
}

// call performs exactly one API request on a fresh client and returns the
// envelope's data member when the API reports success.
func (a *Adapter) call(ctx context.Context, credential site.Credential, path, contentType string, body []byte) (json.RawMessage, error) {
Expand Down
Loading
Loading