diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..eb1ef60 --- /dev/null +++ b/.env.example @@ -0,0 +1 @@ +TWICKETS_KEYS_URL= diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 795f96b..8b4728c 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -52,5 +52,5 @@ jobs: - name: Run test run: go test ./... env: - TWICKETS_API_KEY: ${{ secrets.TWICKETS_API_KEY }} + TWICKETS_KEYS_URL: ${{ secrets.TWICKETS_KEYS_URL }} CI: true diff --git a/README.md b/README.md index 0cf8324..9cdc796 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,38 @@ ![twigots](assets/twigots.png) [![Go Reference](https://pkg.go.dev/badge/github.com/ahobsonsayers/twigots.svg)](https://pkg.go.dev/github.com/ahobsonsayers/twigots) -[![Go Report -Card](https://goreportcard.com/badge/github.com/ahobsonsayers/twigots)](https://goreportcard.com/report/github.com/ahobsonsayers/twigots) +[![Go Report Card](https://goreportcard.com/badge/github.com/ahobsonsayers/twigots)](https://goreportcard.com/report/github.com/ahobsonsayers/twigots) [![License - MIT](https://img.shields.io/badge/License-MIT-9C27B0)](LICENSE) +[![Artisan README - Not LLM](https://img.shields.io/static/v1?label=Artisan+README&message=Not+LLM&labelColor=37474F&color=D97757)](#arnl---artisan-readme-not-llm) -A go package to fetch ticket listings from the [Twickets](https://www.twickets.live) Live Feed. +> [!NOTE] +> We're back! 💪 +> +> After Twickets introduced measures to prevent unofficial access to their data - this project was broken for quite a while. +> +> After a significant amount of time and effort tinkering and hitting my head against a wall (more than I care to admit) I have now found a way to bring this project back to life and get it working again! +> +> Enjoy! 🎟️ + +A Go package to fetch ticket listings from the [Twickets](https://www.twickets.live) Live Feed. Includes utilities to help filter the ticket listings and find the ones you want! Powers (the similarly creatively named) [twitchets](https://github.com/ahobsonsayers/twitchets), a tool to watch for event ticket listings on Twickets and notify you so you can snap them up! 🫰 +This package utilises the API used by the Twickets Android app, built via decompiling and reverse engineering its code. + +To use this API (and therefore this package), you will need to obtain API keys. See the [Getting Keys](#getting-keys) section + - [Installation](#installation) -- [Getting an API Key](#getting-an-api-key) +- [Getting Keys](#getting-keys) + - [Loading Keys](#loading-keys) - [Example Usage](#example-usage) - [How does the event name matching/similarity work?](#how-does-the-event-name-matchingsimilarity-work) - [Normalization](#normalization) - [Why the name twigots?](#why-the-name-twigots) +- [AR;NL - Artisan Readme; Not LLM](#arnl---artisan-readme-not-llm) ## Installation @@ -25,19 +40,50 @@ Powers (the similarly creatively named) go get -u github.com/ahobsonsayers/twigots ``` -## Getting an API Key +## Getting Keys + +This package uses the API used by the Android app. To use this API, three keys are required (as well as a valid `User-Agent`): -To use this tool, you will need a Twickets API key. Although Twickets doesn't provide a free API, you can easily obtain a key by following these steps: +- `api_key` +- `x-prosopo-site-key` +- `x-prosopo-android-integrity-token` -1. Visit the [Twickets Live Feed](https://www.twickets.live/app/catalog/browse) -2. Open your browser's Developer Tools (F12) and navigate to the Network tab -3. Look for the GET request to `https://www.twickets.live/services/catalogue` and copy the `api_key` query parameter. You might need to refresh the page first if nothing appears in this tab. +These must be supplied to the package via a `keys.json` file that looks like: -This API key is not provided here due to liability concerns, but it appears to be a fixed, unchanging value. +```json +{ + "api_key": "your_api_key", + "User-Agent": "your_user_agent", + "x-prosopo-site-key": "your_site_key", + "x-prosopo-android-integrity-token": "your_integrity_token" +} +``` + +The first two keys are static, but the third is rotated and can only be obtained from a real (or emulated) Android device, on a scheduled basis. + +Thankfully I built the [`twickets-key-extractor`](https://github.com/ahobsonsayers/twickets-key-extractor) project to do exactly this with an emulator, and regularly extract these keys. + +You can run this yourself, but I have also set up a [community-extracted keys.json here](https://gist.githubusercontent.com/ahobsonsayers/773acb763aafc8a39ac260e12a9b39d5/raw/bc9a19d81a033b89e1368a54ce9c4afd09e757ae/keys.json) + +### Loading Keys + +Once you have a valid source for the `keys.json` you can load them for use in this package in two ways, both of which allow hot reloading + +Load keys from a URL: + +```go +keys, err := keys.LoadKeysFromURL("https://example.com/keys.json") +``` + +Load keys from a file: + +```go +keys, err := keys.LoadKeysFromFile("/path/to/keys.json") +``` ## Example Usage -> [!Warning] +> [!WARNING] > Although this package is functional and ready for use, it is still a work in progress and is subject to change without notice - the API and usage may be modified at any time. > > Use with caution and check for updates regularly. @@ -51,17 +97,27 @@ import ( "context" "log" "log/slog" + "os" "time" "github.com/ahobsonsayers/twigots" "github.com/ahobsonsayers/twigots/filter" + "github.com/ahobsonsayers/twigots/keys" ) func main() { - apiKey := "my_api_key" + keysURL := os.Getenv("TWICKETS_KEYS_URL") + if keysURL == "" { + log.Fatal("TWICKETS_KEYS_URL is not set") + } + + twicketsKeys, err := keys.LoadKeysFromURL(keysURL) + if err != nil { + log.Fatal(err) + } - // Create twickets client (using api key) - client, err := twigots.NewClient(apiKey) + // Create twickets client + client, err := twigots.NewClient(twicketsKeys) if err != nil { log.Fatal(err) } @@ -131,7 +187,7 @@ Event name similarity is calculated using a modified [Smith-Waterman-Gotoh algor If the desired event name appears within the actual event name returned by twickets (as a substring), the event similarity will be 1. Equally, if the desired event name does not appear at all, the similarity will be 0. -Setting a required similarity below, but close to 1, will allow for small inconsistencies due to misspelling etc., but can return false positives. We recommend (and default to) a value of `0.9`. +Setting a required similarity below, but close to 1, will allow for small inconsistencies due to misspellings etc., but can return false positives. We recommend (and default to) a value of `0.9`. False positives can also occur if your desired event name appears in the actual event name, but the event is not the one you want. This can often happen with things like tribute bands - see the example below. @@ -148,10 +204,10 @@ Similarity score: 1 ``` Desired event: Taylor Swift Actual event: Miss Americana: A Tribute to Taylor Swift -Similarity score: 1 <- This is a exact match, but it is probably not the event we want +Similarity score: 1 <- This is an exact match, but it is probably not the event we want ``` -For a more in depth explanation of the string matching algorithm, [see this PR](https://github.com/ahobsonsayers/twigots/pull/2). +For a more in-depth explanation of the string matching algorithm, [see this PR](https://github.com/ahobsonsayers/twigots/pull/2). ### Normalization @@ -169,6 +225,18 @@ This is done by: ## Why the name twigots? -Because its a stupid mash up of Tickets and Go... and also why not? +Because it's a stupid mash up of Tickets and Go... and also why not? [![Hits](https://hits.sh/github.com/ahobsonsayers/twigots.svg?view=today-total&label=Visitors%20Day%20%2F%20Total)](https://hits.sh/github.com/ahobsonsayers/twigots/) + +## AR;NL - Artisan Readme; Not LLM + +In the age of LLMs and coding agents, code is now cheap - for better or for worse. Your time however, is not ⌛ + +Therefore this project, like most of my projects, uses a hand written "artisan" README to ensure it is clear, correct and concise. This makes it easy to read and in my opinion encourages reading and engagement - no one likes AI slop! + +As someone wiser than me once told a colleague: + +"if you can't be bothered to take the time to write these words, then why should I be bothered to read them" + +Enjoy! diff --git a/Taskfile.yaml b/Taskfile.yaml index 4879a05..a468ce8 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -1,6 +1,9 @@ # Docs: https://taskfile.dev/#/usage version: "3" +dotenv: + - .env + tasks: format: cmds: @@ -18,3 +21,7 @@ tasks: cmds: - go clean -testcache - task: test + + run:example: + cmds: + - go run ./example diff --git a/client.go b/client.go index 825597a..0d5a564 100644 --- a/client.go +++ b/client.go @@ -8,13 +8,14 @@ import ( "net/http" "time" + "github.com/ahobsonsayers/twigots/keys" "github.com/imroc/req/v3" "github.com/k3a/html2text" ) type Client struct { client *req.Client - apiKey string + keys *keys.Keys } func (c *Client) Client() *http.Client { @@ -85,13 +86,19 @@ func (f FetchTicketListingsInput) Validate() error { } // FetchTicketListings gets ticket listings using the specified feel url. -func (c *Client) FetchTicketListingsByFeedUrl( - ctx context.Context, - feedUrl string, -) (TicketListings, error) { - response, err := c.client.R().SetContext(ctx).Get(feedUrl) +func (c *Client) FetchTicketListingsByFeedUrl(ctx context.Context, feedUrl string) (TicketListings, error) { + request := c.client.R().SetContext(ctx) + + request.SetHeaders(map[string]string{ + "User-Agent": c.keys.UserAgent(), + "x-prosopo-site-key": c.keys.ProsopoSiteKey(), + "x-prosopo-android-integrity-token": c.keys.ProsopoIntegrityToken(), + }) + request.SetQueryParam("api_key", c.keys.APIKey()) + + response, err := request.Get(feedUrl) if err != nil { - return nil, nil + return nil, fmt.Errorf("failed to get tickets: %w", err) } if !response.IsSuccessState() { @@ -104,7 +111,7 @@ func (c *Client) FetchTicketListingsByFeedUrl( bodyBytes, err := io.ReadAll(response.Body) if err != nil { - return nil, fmt.Errorf("failed ready response body: %w", err) + return nil, fmt.Errorf("failed to read response body: %w", err) } return UnmarshalTwicketsFeedJson(bodyBytes) @@ -130,7 +137,6 @@ func (c *Client) FetchTicketListings( // Get feed url feedUrl, err := FeedUrl(FeedUrlInput{ - APIKey: c.apiKey, Country: input.Country, Regions: input.Regions, BeforeTime: earliestTicketTime, @@ -196,25 +202,16 @@ func processFeedListings( return processedListings, false } -type ClientOpt func(*req.Client) error - // NewClient creates a new Twickets client -func NewClient(apiKey string, opts ...ClientOpt) (*Client, error) { - if apiKey == "" { - return nil, errors.New("api key must be set") +func NewClient(twicketsKeys *keys.Keys) (*Client, error) { + if twicketsKeys == nil { + return nil, errors.New("keys must be set") } client := req.C() - client = client.ImpersonateChrome() - for _, opt := range opts { - err := opt(client) - if err != nil { - return nil, err - } - } return &Client{ client: client, - apiKey: apiKey, + keys: twicketsKeys, }, nil } diff --git a/client_test.go b/client_test.go index 7737b7a..24c538c 100644 --- a/client_test.go +++ b/client_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/ahobsonsayers/twigots" + "github.com/ahobsonsayers/twigots/keys" "github.com/ahobsonsayers/utilopia/testutils" "github.com/davecgh/go-spew/spew" "github.com/jarcoal/httpmock" @@ -20,7 +21,25 @@ import ( "github.com/stretchr/testify/require" ) -const testAPIKey = "test" +const ( + testAPIKey = "test" + testUserAgent = "test-user-agent" + testProsopoSiteKey = "test-site-key" + testProsopoToken = "test-integrity-token" +) + +func testKeys() *keys.Keys { + k := &keys.Keys{} + k.Update( + ptrString(testAPIKey), + ptrString(testUserAgent), + ptrString(testProsopoSiteKey), + ptrString(testProsopoToken), + ) + return k +} + +func ptrString(s string) *string { return &s } var testEvents = []string{ "Adele", @@ -56,10 +75,13 @@ func TestFetchListingsReal(t *testing.T) { projectDirectory := testutils.ProjectDirectory(t) _ = godotenv.Load(filepath.Join(projectDirectory, ".env")) - twicketsAPIKey := os.Getenv("TWICKETS_API_KEY") - require.NotEmpty(t, twicketsAPIKey, "TWICKETS_API_KEY is not set") + twicketsKeysURL := os.Getenv("TWICKETS_KEYS_URL") + require.NotEmpty(t, twicketsKeysURL, "TWICKETS_KEYS_URL is not set") - twicketsClient, err := twigots.NewClient(twicketsAPIKey) + twicketsKeys, err := keys.LoadKeysFromURL(twicketsKeysURL) + require.NoError(t, err) + + twicketsClient, err := twigots.NewClient(twicketsKeys) require.NoError(t, err) // Fetch ticket listings @@ -80,7 +102,7 @@ func TestFetchListings(t *testing.T) { testTime := time.Now().Truncate(time.Millisecond) // Create client - twicketsClient, err := twigots.NewClient(testAPIKey) + twicketsClient, err := twigots.NewClient(testKeys()) require.NoError(t, err) // Setup mock @@ -109,7 +131,7 @@ func TestFetchListingsPaginatedMaxNumber(t *testing.T) { testTime := time.Now().Truncate(time.Millisecond) // Create client - twicketsClient, err := twigots.NewClient(testAPIKey) + twicketsClient, err := twigots.NewClient(testKeys()) require.NoError(t, err) // Setup mock @@ -151,7 +173,7 @@ func TestFetchListingsPaginatedCreatedAfter(t *testing.T) { testTime := time.Now().Truncate(time.Millisecond) // Create client - twicketsClient, err := twigots.NewClient(testAPIKey) + twicketsClient, err := twigots.NewClient(testKeys()) require.NoError(t, err) // Setup mock @@ -190,7 +212,7 @@ func TestFetchListingsCreatedAfterLatestListingReturnsNothing(t *testing.T) { testTime := time.Now().Truncate(time.Millisecond) // Create client - twicketsClient, err := twigots.NewClient(testAPIKey) + twicketsClient, err := twigots.NewClient(testKeys()) require.NoError(t, err) // Setup mock @@ -223,10 +245,10 @@ func getMockUrlAndResponder( interval time.Duration, //nolint:unparam ) (string, httpmock.Responder) { url := fmt.Sprintf( - "https://www.twickets.live/services/catalogue?api_key=%s&count=10&maxTime=%d&q=countryCode=%s", - testAPIKey, + "https://www.twickets.live/services/catalogue?count=10&maxTime=%d&q=countryCode=%s&api_key=%s", startTime.UnixMilli(), twigots.CountryUnitedKingdom.Value, + testAPIKey, ) response := getMockResponse(events, startTime, interval) diff --git a/example/main.go b/example/main.go index 56a25a9..57de7be 100644 --- a/example/main.go +++ b/example/main.go @@ -4,17 +4,27 @@ import ( "context" "log" "log/slog" + "os" "time" "github.com/ahobsonsayers/twigots" "github.com/ahobsonsayers/twigots/filter" + "github.com/ahobsonsayers/twigots/keys" ) func main() { - apiKey := "my_api_key" + keysURL := os.Getenv("TWICKETS_KEYS_URL") + if keysURL == "" { + log.Fatal("TWICKETS_KEYS_URL is not set") + } + + twicketsKeys, err := keys.LoadKeysFromURL(keysURL) + if err != nil { + log.Fatal(err) + } - // Create twickets client (using api key) - client, err := twigots.NewClient(apiKey) + // Create twickets client + client, err := twigots.NewClient(twicketsKeys) if err != nil { log.Fatal(err) } diff --git a/flaresolverr/flaresolverr.go b/flaresolverr/flaresolverr.go deleted file mode 100644 index fe462f7..0000000 --- a/flaresolverr/flaresolverr.go +++ /dev/null @@ -1,147 +0,0 @@ -package flaresolverr - -import ( - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/PuerkitoBio/goquery" - "github.com/imroc/req/v3" - "github.com/tidwall/gjson" -) - -type FlareSolverrOpt func(*req.Client) error - -func WithFlareSolverr(flareSolverrUrl string) FlareSolverrOpt { - return func(client *req.Client) error { - err := ValidateURL(flareSolverrUrl) - if err != nil { - return fmt.Errorf("invalid flaresolverr url: %w", err) - } - - // Ensure url path ends with /v1 - // TODO this could be done better - flareSolverrUrl := strings.TrimSuffix(flareSolverrUrl, "/") - flareSolverrUrl = strings.TrimSuffix(flareSolverrUrl, "/v1") - flareSolverrUrl = fmt.Sprintf("%s/v1", flareSolverrUrl) - - // Apply middleware - flareSolverrMiddleware := getFlareSolverrMiddleware(flareSolverrUrl) - client.WrapRoundTripFunc(flareSolverrMiddleware) - - return nil - } -} - -func getFlareSolverrMiddleware(flareSolverrUrl string) req.RoundTripWrapperFunc { - return func(rt req.RoundTripper) req.RoundTripFunc { - return func(request *req.Request) (*req.Response, error) { - // Before request - err := transformToFlareSolverrRequest(request, flareSolverrUrl) - if err != nil { - return nil, fmt.Errorf( - "failed to transform standard request to flaresolverr request: %w", - err, - ) - } - - // Do request - response, err := rt.RoundTrip(request) - if err != nil { - return response, err - } - - // After request - err = transformFromFlareSolverrResponse(response) - if err != nil { - return response, fmt.Errorf( - "failed to transform flaresolverr response to standard response: %w", - err, - ) - } - - return response, nil - } - } -} - -// transformToFlareSolverrRequest transforms a standard response to a flaresolverr request. -// The passed requests in modified in place -func transformToFlareSolverrRequest(request *req.Request, flareSolverrUrl string) error { - if request.Method != http.MethodGet { - return nil - } - - parsedFlareSolverrUrl, err := url.Parse(flareSolverrUrl) - if err != nil { - return fmt.Errorf("failed to parse flaresolverr url: %w", err) - } - - twicketsRawUrl := request.RawURL - - // Update request to be made to flaresolverr - request.Method = http.MethodPost - request.RawURL = flareSolverrUrl - request.URL = parsedFlareSolverrUrl - request.SetBodyJsonMarshal( - map[string]any{ - "cmd": "request.get", - "url": twicketsRawUrl, - "maxTimeout": "5000", - }) - - return nil -} - -// transformFromFlareSolverrResponse transforms a flaresolverr response to a standard response. -// The passed response in modified in place -func transformFromFlareSolverrResponse(response *req.Response) error { - if response.Err != nil { // you can skip if error occurs. - return nil - } - - proxyBodyBytes, err := io.ReadAll(response.Body) - if err != nil { - return err - } - - // Extract json response from flaresolvarr response - bodyBytesResult := gjson.GetBytes(proxyBodyBytes, "solution.response") - bodyString := bodyBytesResult.String() - bodyReader := strings.NewReader(bodyString) - bodyDoc, err := goquery.NewDocumentFromReader(bodyReader) - if err != nil { - return fmt.Errorf("failed to parse response body: %w", err) - } - bodyJson := bodyDoc.Find("pre").Text() - - response.Body = io.NopCloser(strings.NewReader(bodyJson)) - - return nil -} - -// ValidateURL checks if a url string is a valid. -func ValidateURL(urlString string) error { - if urlString == "" { - return errors.New("url is not set") - } - - parsedURL, err := url.Parse(urlString) - if err != nil { - return fmt.Errorf("url format invalid: %w", err) - } - - if parsedURL.Host == "" { - return errors.New("url hostname missing") - } - - scheme := strings.ToLower(parsedURL.Scheme) - if scheme != "http" && scheme != "https" { - return fmt.Errorf("url scheme unsupported: %v", parsedURL.Scheme) - } - - return nil -} diff --git a/go.mod b/go.mod index c64e16c..98246db 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/PuerkitoBio/goquery v1.10.3 github.com/ahobsonsayers/utilopia v0.2.1 github.com/davecgh/go-spew v1.1.1 + github.com/fsnotify/fsnotify v1.9.0 github.com/hbollon/go-edlib v1.6.0 github.com/imroc/req/v3 v3.54.0 github.com/jarcoal/httpmock v1.4.0 @@ -83,7 +84,6 @@ require ( github.com/fatih/color v1.18.0 // indirect github.com/fatih/structtag v1.2.0 // indirect github.com/firefart/nonamedreturns v1.0.6 // indirect - github.com/fsnotify/fsnotify v1.5.4 // indirect github.com/fzipp/gocyclo v0.6.0 // indirect github.com/ghostiam/protogetter v0.3.17 // indirect github.com/go-critic/go-critic v0.14.2 // indirect diff --git a/go.sum b/go.sum index 5b24baf..3417c83 100644 --- a/go.sum +++ b/go.sum @@ -134,8 +134,8 @@ github.com/firefart/nonamedreturns v1.0.6 h1:vmiBcKV/3EqKY3ZiPxCINmpS431OcE1S47A github.com/firefart/nonamedreturns v1.0.6/go.mod h1:R8NisJnSIpvPWheCq0mNRXJok6D8h7fagJTF8EMEwCo= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= -github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= -github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo= github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= github.com/ghostiam/protogetter v0.3.17 h1:sjGPErP9o7i2Ym+z3LsQzBdLCNaqbYy2iJQPxGXg04Q= @@ -610,7 +610,6 @@ golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211105183446-c75c47738b0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/keys/file.go b/keys/file.go new file mode 100644 index 0000000..8623c94 --- /dev/null +++ b/keys/file.go @@ -0,0 +1,157 @@ +package keys + +import ( + "context" + "fmt" + "log/slog" + "os" + "path/filepath" + "sync" + "time" + + "github.com/fsnotify/fsnotify" +) + +const fileDebounce = 200 * time.Millisecond + +// FileWatcher watches a file for key updates. +type FileWatcher struct { + path string + + watcher *fsnotify.Watcher + + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +type FileWatcherOpt func(*FileWatcher) + +func WithFileWatcherCtx(ctx context.Context) FileWatcherOpt { + return func(w *FileWatcher) { + w.ctx = ctx + } +} + +func NewFileWatcher(path string, opts ...FileWatcherOpt) *FileWatcher { + // Apply options + watcher := &FileWatcher{path: path} + for _, opt := range opts { + opt(watcher) + } + + // Set defaults + if watcher.ctx == nil { + watcher.ctx = context.Background() + } + + return watcher +} + +func (w *FileWatcher) StartWatching(keys *Keys) error { + fsWatcher, err := fsnotify.NewWatcher() + if err != nil { + return fmt.Errorf("failed to create file watcher: %w", err) + } + + fileDirectory := filepath.Dir(w.path) + fileName := filepath.Base(w.path) + + err = fsWatcher.Add(fileDirectory) + if err != nil { + fsWatcher.Close() + return fmt.Errorf("failed to watch directory %q: %w", fileDirectory, err) + } + + w.watcher = fsWatcher + + ctx, cancel := context.WithCancel(w.ctx) + w.cancel = cancel + w.wg.Add(1) + + go w.watch(ctx, keys, fileName) + + return nil +} + +func (w *FileWatcher) StopWatching() { + if w.cancel != nil { + w.cancel() + } + w.wg.Wait() + if w.watcher != nil { + w.watcher.Close() + } +} + +func (w *FileWatcher) watch(ctx context.Context, keys *Keys, targetFileName string) { + defer w.wg.Done() + + var debounce *time.Timer + for { + select { + case <-ctx.Done(): + return + + case event, ok := <-w.watcher.Events: + if !ok { + return + } + + fileName := filepath.Base(event.Name) + if fileName != targetFileName { + continue + } + + if debounce != nil { + debounce.Stop() + } + + debounce = time.AfterFunc( + fileDebounce, + func() { + err := w.load(keys) + if err != nil { + slog.Error( + "failed to reload keys", + "path", w.path, + "error", err, + ) + } + }, + ) + + case err, ok := <-w.watcher.Errors: + if !ok { + return + } + + slog.Error( + "keys file watcher error", + "error", err, + ) + } + } +} + +func (w *FileWatcher) load(keys *Keys) error { + keysJson, err := os.ReadFile(w.path) + if err != nil { + return fmt.Errorf("failed to read keys file: %w", err) + } + + return keys.UpdateFromJSON(keysJson) +} + +func LoadKeysFromFile(path string, watcherOpts ...FileWatcherOpt) (*Keys, error) { + watcher := NewFileWatcher(path, watcherOpts...) + + keys := &Keys{} + err := watcher.load(keys) + if err != nil { + return nil, err + } + + keys.SetWatcher(watcher) + return keys, nil +} diff --git a/keys/keys.go b/keys/keys.go new file mode 100644 index 0000000..652ca23 --- /dev/null +++ b/keys/keys.go @@ -0,0 +1,111 @@ +package keys + +import ( + "encoding/json" + "errors" + "fmt" + "sync" +) + +type Keys struct { + mu sync.RWMutex + + apiKey string + userAgent string + prosopoSiteKey string + prosopoIntegrityToken string + + watcher Watcher +} + +// Watcher watches a keys source for updates. +type Watcher interface { + StartWatching(k *Keys) error + StopWatching() +} + +func (k *Keys) APIKey() string { + k.mu.RLock() + defer k.mu.RUnlock() + return k.apiKey +} + +func (k *Keys) UserAgent() string { + k.mu.RLock() + defer k.mu.RUnlock() + return k.userAgent +} + +func (k *Keys) ProsopoSiteKey() string { + k.mu.RLock() + defer k.mu.RUnlock() + return k.prosopoSiteKey +} + +func (k *Keys) ProsopoIntegrityToken() string { + k.mu.RLock() + defer k.mu.RUnlock() + return k.prosopoIntegrityToken +} + +func (k *Keys) Update(apiKey, userAgent, prosopoSiteKey, prosopoIntegrityToken *string) { + k.mu.Lock() + defer k.mu.Unlock() + if apiKey != nil { + k.apiKey = *apiKey + } + if userAgent != nil { + k.userAgent = *userAgent + } + if prosopoSiteKey != nil { + k.prosopoSiteKey = *prosopoSiteKey + } + if prosopoIntegrityToken != nil { + k.prosopoIntegrityToken = *prosopoIntegrityToken + } +} + +func (k *Keys) UpdateFromJSON(keysJson []byte) error { + var keys struct { + APIKey string `json:"api_key"` + UserAgent string `json:"User-Agent"` + ProsopoSiteKey string `json:"x-prosopo-site-key"` + ProsopoIntegrityToken string `json:"x-prosopo-android-integrity-token"` + } + + err := json.Unmarshal(keysJson, &keys) + if err != nil { + return fmt.Errorf("failed to unmarshal keys: %w", err) + } + + k.Update( + &keys.APIKey, + &keys.UserAgent, + &keys.ProsopoSiteKey, + &keys.ProsopoIntegrityToken, + ) + + return nil +} + +func (k *Keys) HasWatcher() bool { + return k.watcher != nil +} + +func (k *Keys) SetWatcher(watcher Watcher) { + k.watcher = watcher +} + +func (k *Keys) StartWatching() error { + if k.watcher == nil { + return errors.New("no watcher configured") + } + + return k.watcher.StartWatching(k) +} + +func (k *Keys) StopWatching() { + if k.watcher != nil { + k.watcher.StopWatching() + } +} diff --git a/keys/keys_test.go b/keys/keys_test.go new file mode 100644 index 0000000..5c9952c --- /dev/null +++ b/keys/keys_test.go @@ -0,0 +1,159 @@ +package keys_test + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/ahobsonsayers/twigots/keys" + "github.com/stretchr/testify/require" +) + +func sampleRawKeys() []byte { + return []byte(`{ + "api_key": "test-api-key", + "User-Agent": "test-user-agent", + "x-prosopo-site-key": "test-site-key", + "x-prosopo-android-integrity-token": "test-integrity-token" + }`) +} + +func TestLoadKeysFromURL(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(sampleRawKeys()) + })) + defer server.Close() + + k, err := keys.LoadKeysFromURL(server.URL) + require.NoError(t, err) + + require.Equal(t, "test-api-key", k.APIKey()) + require.Equal(t, "test-user-agent", k.UserAgent()) + require.Equal(t, "test-site-key", k.ProsopoSiteKey()) + require.Equal(t, "test-integrity-token", k.ProsopoIntegrityToken()) + require.True(t, k.HasWatcher()) +} + +func TestLoadKeysFromFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "keys.json") + require.NoError(t, os.WriteFile(path, sampleRawKeys(), 0o644)) + + k, err := keys.LoadKeysFromFile(path) + require.NoError(t, err) + + require.Equal(t, "test-api-key", k.APIKey()) + require.Equal(t, "test-user-agent", k.UserAgent()) + require.Equal(t, "test-site-key", k.ProsopoSiteKey()) + require.Equal(t, "test-integrity-token", k.ProsopoIntegrityToken()) + require.True(t, k.HasWatcher()) +} + +func TestUpdateNilLeavesUnchanged(t *testing.T) { + k := &keys.Keys{} + k.Update( + ptr("api"), + ptr("ua"), + ptr("site"), + ptr("token"), + ) + + require.Equal(t, "api", k.APIKey()) + require.Equal(t, "ua", k.UserAgent()) + require.Equal(t, "site", k.ProsopoSiteKey()) + require.Equal(t, "token", k.ProsopoIntegrityToken()) + + k.Update(nil, nil, nil, nil) + + require.Equal(t, "api", k.APIKey()) + require.Equal(t, "ua", k.UserAgent()) + require.Equal(t, "site", k.ProsopoSiteKey()) + require.Equal(t, "token", k.ProsopoIntegrityToken()) + + k.Update(ptr("api2"), nil, ptr("site2"), nil) + + require.Equal(t, "api2", k.APIKey()) + require.Equal(t, "ua", k.UserAgent()) + require.Equal(t, "site2", k.ProsopoSiteKey()) + require.Equal(t, "token", k.ProsopoIntegrityToken()) +} + +func TestGettersAndSourceChecks(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "keys.json") + require.NoError(t, os.WriteFile(path, sampleRawKeys(), 0o644)) + + k, err := keys.LoadKeysFromFile(path) + require.NoError(t, err) + + require.True(t, k.HasWatcher()) +} + +func TestWatchURL(t *testing.T) { + var counter atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + counter.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(sampleRawKeys()) + })) + defer server.Close() + + k, err := keys.LoadKeysFromURL(server.URL, keys.WithURLWatcherPollInterval(50*time.Millisecond)) + require.NoError(t, err) + + err = k.StartWatching() + require.NoError(t, err) + defer k.StopWatching() + + require.Eventually(t, func() bool { + return counter.Load() > 1 + }, 5*time.Second, 20*time.Millisecond) + + require.Equal(t, "test-api-key", k.APIKey()) +} + +func TestWatchFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "keys.json") + require.NoError(t, os.WriteFile(path, sampleRawKeys(), 0o644)) + + k, err := keys.LoadKeysFromFile(path) + require.NoError(t, err) + + err = k.StartWatching() + require.NoError(t, err) + defer k.StopWatching() + + updated := []byte(`{ + "api_key": "updated-api-key", + "User-Agent": "updated-user-agent", + "x-prosopo-site-key": "updated-site-key", + "x-prosopo-android-integrity-token": "updated-integrity-token" + }`) + require.Eventually(t, func() bool { + return os.WriteFile(path, updated, 0o644) == nil + }, 2*time.Second, 20*time.Millisecond) + + require.Eventually(t, func() bool { + return k.APIKey() == "updated-api-key" + }, 5*time.Second, 20*time.Millisecond) + + require.Equal(t, "updated-user-agent", k.UserAgent()) + require.Equal(t, "updated-site-key", k.ProsopoSiteKey()) + require.Equal(t, "updated-integrity-token", k.ProsopoIntegrityToken()) +} + +func TestWatchWithoutSourceErrors(t *testing.T) { + k := &keys.Keys{} + err := k.StartWatching() + require.Error(t, err) +} + +func ptr(s string) *string { + return &s +} diff --git a/keys/url.go b/keys/url.go new file mode 100644 index 0000000..0310e64 --- /dev/null +++ b/keys/url.go @@ -0,0 +1,142 @@ +package keys + +import ( + "context" + "fmt" + "io" + "log/slog" + "net/http" + "sync" + "time" +) + +const defaultURLPollInterval = time.Minute + +// URLWatcher watches a URL for key updates by polling at a regular interval. +type URLWatcher struct { + client *http.Client + url string + pollInterval time.Duration + + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +type URLWatcherOpt func(*URLWatcher) + +func WithURLWatcherCtx(ctx context.Context) URLWatcherOpt { + return func(w *URLWatcher) { + w.ctx = ctx + } +} + +func WithURLWatcherHTTPClient(client *http.Client) URLWatcherOpt { + return func(w *URLWatcher) { + w.client = client + } +} + +func WithURLWatcherPollInterval(d time.Duration) URLWatcherOpt { + return func(w *URLWatcher) { + w.pollInterval = d + } +} + +func NewURLWatcher(url string, opts ...URLWatcherOpt) *URLWatcher { + // Apply options + watcher := &URLWatcher{url: url} + for _, opt := range opts { + opt(watcher) + } + + // Set defaults + if watcher.client == nil { + watcher.client = http.DefaultClient + } + if watcher.pollInterval <= 0 { + watcher.pollInterval = defaultURLPollInterval + } + if watcher.ctx == nil { + watcher.ctx = context.Background() + } + + return watcher +} + +func (w *URLWatcher) StartWatching(keys *Keys) error { + ctx, cancel := context.WithCancel(w.ctx) + w.cancel = cancel + w.wg.Add(1) + + go w.watch(ctx, keys) + + return nil +} + +func (w *URLWatcher) StopWatching() { + if w.cancel != nil { + w.cancel() + } + w.wg.Wait() +} + +func (w *URLWatcher) watch(ctx context.Context, keys *Keys) { + defer w.wg.Done() + + ticker := time.NewTicker(w.pollInterval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + + case <-ticker.C: + err := w.fetch(ctx, keys) + if err != nil { + slog.Error( + "failed to fetch keys", + "error", err, + ) + } + } + } +} + +func (w *URLWatcher) fetch(ctx context.Context, keys *Keys) error { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, w.url, http.NoBody) + if err != nil { + return fmt.Errorf("failed to create request: %w", err) + } + + response, err := w.client.Do(request) + if err != nil { + return fmt.Errorf("failed to fetch keys: %w", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status fetching keys: %s", response.Status) + } + + keysJson, err := io.ReadAll(response.Body) + if err != nil { + return fmt.Errorf("failed reading keys response: %w", err) + } + + return keys.UpdateFromJSON(keysJson) +} + +func LoadKeysFromURL(url string, watcherOpts ...URLWatcherOpt) (*Keys, error) { + watcher := NewURLWatcher(url, watcherOpts...) + + keys := &Keys{} + err := watcher.fetch(watcher.ctx, keys) + if err != nil { + return nil, err + } + + keys.SetWatcher(watcher) + return keys, nil +} diff --git a/url.go b/url.go index 9c1976a..361744b 100644 --- a/url.go +++ b/url.go @@ -39,7 +39,6 @@ func ListingURL(listingId string, numTickets int) string { type FeedUrlInput struct { // Required fields - APIKey string Country Country // Optional fields @@ -50,9 +49,6 @@ type FeedUrlInput struct { // Validate the input struct used to get the feed url. // This is used internally to check the input, but can also be used externally. func (f FeedUrlInput) Validate() error { - if f.APIKey == "" { - return errors.New("api key must be set") - } if f.Country.Value == "" { return errors.New("country must be set") } @@ -67,7 +63,9 @@ func (f FeedUrlInput) Validate() error { // There may be any number of additional delisted ticket listings. // // Format is: -// https://www.twickets.live/services/catalogue?q=countryCode=GB&count=10&api_key= +// https://www.twickets.live/services/catalogue?q=countryCode=GB&count=10&maxTime= +// +// Note: The `api_key` query param will be added to the url by the client on request. func FeedUrl(input FeedUrlInput) (string, error) { err := input.Validate() if err != nil { @@ -81,16 +79,13 @@ func FeedUrl(input FeedUrlInput) (string, error) { queryParams := feedUrl.Query() locationQuery := apiLocationQuery(input.Country, input.Regions...) - if locationQuery != "" { - queryParams.Set("q", locationQuery) - } + queryParams.Set("q", locationQuery) if !input.BeforeTime.IsZero() { maxTime := input.BeforeTime.UnixMilli() queryParams.Set("maxTime", strconv.Itoa(int(maxTime))) } - queryParams.Set("api_key", input.APIKey) queryParams.Set("count", "10") // count must always be 10 to not get an error // Set query