From 2d94d4cdd1c6a9e14b8e1941b8f5d6c3f4039fae Mon Sep 17 00:00:00 2001 From: "jinzheng.architect" Date: Fri, 16 Oct 2026 18:21:43 +0800 Subject: [PATCH] Add search paging, mode, category, and free filters for M-Team site search read only the first 50 results in normal mode. A new optional port, site.OptionTorrentSearcher, takes site.SearchOptions (page, mode, category IDs, free-only), and site search exposes it as --page, --mode, --category, and --free. The CLI validates options with the adapter before the credential is read; a site without the port refuses the flags, so TJUPT is unchanged. M-Team sends them in its one search request as pageNumber, mode, categories, and discount FREE, and drops any returned row whose download is counted. Without options the request body is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/ADDING_A_SITE.md | 7 ++ docs/MTEAM_ADAPTER.md | 18 +++- docs/guide/sites.md | 4 +- internal/cli/run.go | 2 +- internal/cli/site.go | 44 +++++++++ internal/cli/site_search_options_test.go | 110 +++++++++++++++++++++++ internal/site/driver.go | 29 ++++++ internal/site/mteam/adapter.go | 28 ------ internal/site/mteam/search.go | 107 ++++++++++++++++++++++ internal/site/mteam/search_test.go | 94 +++++++++++++++++++ 10 files changed, 411 insertions(+), 32 deletions(-) create mode 100644 internal/cli/site_search_options_test.go create mode 100644 internal/site/mteam/search.go create mode 100644 internal/site/mteam/search_test.go diff --git a/docs/ADDING_A_SITE.md b/docs/ADDING_A_SITE.md index d15f73e..d94ae89 100644 --- a/docs/ADDING_A_SITE.md +++ b/docs/ADDING_A_SITE.md @@ -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 failed` message, keeping only typed cancellation and deadline causes, so adapter error text never reaches the user. diff --git a/docs/MTEAM_ADAPTER.md b/docs/MTEAM_ADAPTER.md index 246a014..821d774 100644 --- a/docs/MTEAM_ADAPTER.md +++ b/docs/MTEAM_ADAPTER.md @@ -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 ``` @@ -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; @@ -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 diff --git a/docs/guide/sites.md b/docs/guide/sites.md index 16720d0..15c8f12 100644 --- a/docs/guide/sites.md +++ b/docs/guide/sites.md @@ -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 @@ -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 ``` diff --git a/internal/cli/run.go b/internal/cli/run.go index 15c3747..e874dae 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -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 diff --git a/internal/cli/site.go b/internal/cli/site.go index 07012db..47d9688 100644 --- a/internal/cli/site.go +++ b/internal/cli/site.go @@ -3,6 +3,7 @@ package cli import ( "context" "errors" + "flag" "fmt" "io" "strings" @@ -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) } @@ -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 { @@ -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 +} diff --git a/internal/cli/site_search_options_test.go b/internal/cli/site_search_options_test.go new file mode 100644 index 0000000..9a139fa --- /dev/null +++ b/internal/cli/site_search_options_test.go @@ -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) + } + } + } +} diff --git a/internal/site/driver.go b/internal/site/driver.go index 5162d53..7cef2e3 100644 --- a/internal/site/driver.go +++ b/internal/site/driver.go @@ -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) } diff --git a/internal/site/mteam/adapter.go b/internal/site/mteam/adapter.go index 9d8e14c..c872e50 100644 --- a/internal/site/mteam/adapter.go +++ b/internal/site/mteam/adapter.go @@ -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" @@ -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) { diff --git a/internal/site/mteam/search.go b/internal/site/mteam/search.go new file mode 100644 index 0000000..2e6252a --- /dev/null +++ b/internal/site/mteam/search.go @@ -0,0 +1,107 @@ +package mteam + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "unicode/utf8" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +const ( + // maxSearchPage is the largest pageNumber the API accepts. + maxSearchPage = 1000 + maxSearchCategories = 32 + // freeDiscount asks the API for torrents whose download is not counted. + freeDiscount = "FREE" +) + +// searchModes are the API search areas a caller may pick. "normal" holds +// films, series, music, and the rest; "adult" holds the adult categories. +var searchModes = map[string]bool{"normal": true, "adult": true} + +func (a *Adapter) Search(ctx context.Context, credential site.Credential, query string) ([]domain.TorrentSummary, error) { + return a.SearchWithOptions(ctx, credential, query, site.SearchOptions{}) +} + +// ValidateSearchOptions accepts a page from 1 to 1000, the normal or adult +// mode, and at most 32 distinct category IDs. +func (a *Adapter) ValidateSearchOptions(options site.SearchOptions) error { + if options.Page < 0 || options.Page > maxSearchPage { + return fmt.Errorf("M-Team search page must be from 1 to %d", maxSearchPage) + } + if options.Mode != "" && !searchModes[options.Mode] { + return fmt.Errorf("M-Team search mode must be normal or adult") + } + if len(options.Categories) > maxSearchCategories { + return fmt.Errorf("M-Team search accepts at most %d categories", maxSearchCategories) + } + seen := make(map[string]bool, len(options.Categories)) + for _, category := range options.Categories { + if !canonicalID(category) { + return fmt.Errorf("M-Team search category must be a numeric category ID") + } + if seen[category] { + return fmt.Errorf("M-Team search category %s is repeated", category) + } + seen[category] = true + } + return nil +} + +// SearchWithOptions runs one search request. FreeOnly asks the API for free +// torrents and also drops any returned row whose download is counted, so a +// filtered page can hold fewer rows than an unfiltered one. +func (a *Adapter) SearchWithOptions(ctx context.Context, credential site.Credential, query string, options site.SearchOptions) ([]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) + } + if err := a.ValidateSearchOptions(options); err != nil { + return nil, err + } + request := searchRequest{Mode: "normal", Keyword: query, PageNumber: 1, PageSize: searchPageSize, Categories: options.Categories} + if options.Page > 0 { + request.PageNumber = options.Page + } + if options.Mode != "" { + request.Mode = options.Mode + } + if options.FreeOnly { + request.Discount = freeDiscount + } + body, err := json.Marshal(request) + 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 + } + results, err := parseSearch(data) + if err != nil || !options.FreeOnly { + return results, err + } + free := results[:0] + for _, result := range results { + if result.Promotion != nil && result.Promotion.DownloadFactor == "0" { + free = append(free, result) + } + } + return free, nil +} + +type searchRequest struct { + Mode string `json:"mode"` + Keyword string `json:"keyword"` + PageNumber int `json:"pageNumber"` + PageSize int `json:"pageSize"` + Categories []string `json:"categories,omitempty"` + Discount string `json:"discount,omitempty"` +} diff --git a/internal/site/mteam/search_test.go b/internal/site/mteam/search_test.go new file mode 100644 index 0000000..383e91e --- /dev/null +++ b/internal/site/mteam/search_test.go @@ -0,0 +1,94 @@ +package mteam + +import ( + "context" + "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/tonycoder-hub/ptctl/internal/site" +) + +var _ site.OptionTorrentSearcher = (*Adapter)(nil) + +func TestSearchWithOptionsSendsThemInOneRequest(t *testing.T) { + client := &fakeClient{response: jsonResponse(searchFixture)} + adapter, _ := fakeAdapter(client) + results, err := adapter.SearchWithOptions(context.Background(), apiKey(t), "canary", site.SearchOptions{ + Page: 3, Mode: "adult", Categories: []string{"410", "424"}, + }) + if err != nil || len(results) != 3 { + t.Fatalf("results=%#v err=%v", results, err) + } + if len(client.calls) != 1 || client.calls[0].path != "api/torrent/search" { + t.Fatalf("calls=%#v", client.calls) + } + var sent map[string]any + if err := json.Unmarshal([]byte(client.calls[0].body), &sent); err != nil { + t.Fatal(err) + } + want := map[string]any{ + "mode": "adult", "keyword": "canary", "pageNumber": float64(3), "pageSize": float64(50), + "categories": []any{"410", "424"}, + } + if !reflect.DeepEqual(sent, want) { + t.Fatalf("search body=%s", client.calls[0].body) + } +} + +func TestSearchFreeOnlyAsksForFreeAndDropsCountedRows(t *testing.T) { + client := &fakeClient{response: jsonResponse(searchFixture)} + adapter, _ := fakeAdapter(client) + results, err := adapter.SearchWithOptions(context.Background(), apiKey(t), "canary", site.SearchOptions{FreeOnly: true}) + if err != nil { + t.Fatal(err) + } + var sent map[string]any + if err := json.Unmarshal([]byte(client.calls[0].body), &sent); err != nil { + t.Fatal(err) + } + if sent["discount"] != "FREE" || sent["mode"] != "normal" || sent["pageNumber"] != float64(1) { + t.Fatalf("search body=%s", client.calls[0].body) + } + // The fixture holds one free row, one normal row, and one row with an + // unknown discount; only the free row is certain to be free. + if len(results) != 1 || results[0].Ref.RemoteID != "900001" { + t.Fatalf("results=%#v", results) + } +} + +func TestSearchOptionsAreValidatedBeforeAnyRequest(t *testing.T) { + tooMany := make([]string, maxSearchCategories+1) + for index := range tooMany { + tooMany[index] = fmt.Sprint(401 + index) + } + for _, options := range []site.SearchOptions{ + {Page: -1}, + {Page: maxSearchPage + 1}, + {Mode: "rss"}, + {Mode: "rankings"}, + {Categories: []string{"0"}}, + {Categories: []string{"4O1"}}, + {Categories: []string{"401", "401"}}, + {Categories: tooMany}, + } { + if err := (&Adapter{}).ValidateSearchOptions(options); err == nil { + t.Fatalf("options=%#v were accepted", options) + } + client := &fakeClient{response: jsonResponse(searchFixture)} + adapter, record := fakeAdapter(client) + if _, err := adapter.SearchWithOptions(context.Background(), apiKey(t), "canary", options); err == nil || record.opened != 0 || len(client.calls) != 0 { + t.Fatalf("options=%#v err=%v opened=%d", options, err, record.opened) + } + } + for _, options := range []site.SearchOptions{ + {}, + {Page: 1}, + {Page: maxSearchPage, Mode: "normal", Categories: tooMany[:maxSearchCategories], FreeOnly: true}, + } { + if err := (&Adapter{}).ValidateSearchOptions(options); err != nil { + t.Fatalf("options=%#v: %v", options, err) + } + } +}