From e7535eeb85059a5413a86bd0909883d926ce4160 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 02:09:56 +0100 Subject: [PATCH 01/14] Add keys package and struct --- keys/keys.go | 111 ++++++++++++++++++++++++++++++++ keys/keys_test.go | 160 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 271 insertions(+) create mode 100644 keys/keys.go create mode 100644 keys/keys_test.go diff --git a/keys/keys.go b/keys/keys.go new file mode 100644 index 0000000..da9b019 --- /dev/null +++ b/keys/keys.go @@ -0,0 +1,111 @@ +package keys + +import ( + "encoding/json" + "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 { + type 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"` + } + + var unmarshaledKeys keys + err := json.Unmarshal(keysJson, &unmarshaledKeys) + if err != nil { + return fmt.Errorf("failed to unmarshal keys: %w", err) + } + + k.Update( + &unmarshaledKeys.APIKey, + &unmarshaledKeys.UserAgent, + &unmarshaledKeys.ProsopoSiteKey, + &unmarshaledKeys.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 fmt.Errorf("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..167d3e5 --- /dev/null +++ b/keys/keys_test.go @@ -0,0 +1,160 @@ +package keys_test + +import ( + "context" + "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(context.Background(), nil, 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(context.Background(), nil, server.URL, keys.WithURLPollInterval(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 +} From e8ec7bc416f5fd12b269a9e149104e5e1412ba3b Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 02:28:39 +0100 Subject: [PATCH 02/14] Add url watcher --- keys/keys_test.go | 4 +- keys/url.go | 136 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 keys/url.go diff --git a/keys/keys_test.go b/keys/keys_test.go index 167d3e5..76046dc 100644 --- a/keys/keys_test.go +++ b/keys/keys_test.go @@ -30,7 +30,7 @@ func TestLoadKeysFromURL(t *testing.T) { })) defer server.Close() - k, err := keys.LoadKeysFromURL(context.Background(), nil, server.URL) + k, err := keys.LoadKeysFromURL(context.Background(), server.URL) require.NoError(t, err) require.Equal(t, "test-api-key", k.APIKey()) @@ -104,7 +104,7 @@ func TestWatchURL(t *testing.T) { })) defer server.Close() - k, err := keys.LoadKeysFromURL(context.Background(), nil, server.URL, keys.WithURLPollInterval(50*time.Millisecond)) + k, err := keys.LoadKeysFromURL(context.Background(), server.URL, keys.WithURLWatcherPollInterval(50*time.Millisecond)) require.NoError(t, err) err = k.StartWatching() diff --git a/keys/url.go b/keys/url.go new file mode 100644 index 0000000..fc42e1b --- /dev/null +++ b/keys/url.go @@ -0,0 +1,136 @@ +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 { + url string + client *http.Client + pollInterval time.Duration + watchCtx context.Context + + cancel context.CancelFunc + wg sync.WaitGroup +} + +type URLWatcherOpt func(*URLWatcher) + +func WithURLWatcherCtx(ctx context.Context) URLWatcherOpt { + return func(w *URLWatcher) { + w.watchCtx = 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.watchCtx == nil { + watcher.watchCtx = context.Background() + } + + return watcher +} + +func (w *URLWatcher) StartWatching(k *Keys) error { + ctx, cancel := context.WithCancel(w.watchCtx) + w.cancel = cancel + w.wg.Add(1) + go w.watch(k, ctx) + return nil +} + +func (w *URLWatcher) StopWatching() { + if w.cancel != nil { + w.cancel() + } + w.wg.Wait() +} + +func (w *URLWatcher) watch(k *Keys, ctx context.Context) { + defer w.wg.Done() + + ticker := time.NewTicker(w.pollInterval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + + case <-ticker.C: + err := w.fetch(k, ctx) + if err != nil { + slog.Error("failed to fetch keys", "error", err) + } + } + } +} + +func (w *URLWatcher) fetch(k *Keys, ctx context.Context) error { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, w.url, nil) + 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 k.UpdateFromJSON(keysJson) +} + +func LoadKeysFromURL(ctx context.Context, url string, watcherOpts ...URLWatcherOpt) (*Keys, error) { + watcher := NewURLWatcher(url, watcherOpts...) + + keys := &Keys{} + if err := watcher.fetch(keys, ctx); err != nil { + return nil, err + } + + keys.SetWatcher(watcher) + return keys, nil +} From c46666654cca673c9fed3b4bbb4d00fa34090498 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 02:39:10 +0100 Subject: [PATCH 03/14] Minor refactor of url loading --- keys/url.go | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/keys/url.go b/keys/url.go index fc42e1b..bf2577b 100644 --- a/keys/url.go +++ b/keys/url.go @@ -14,11 +14,11 @@ const defaultURLPollInterval = time.Minute // URLWatcher watches a URL for key updates by polling at a regular interval. type URLWatcher struct { - url string client *http.Client + url string pollInterval time.Duration - watchCtx context.Context + ctx context.Context cancel context.CancelFunc wg sync.WaitGroup } @@ -27,7 +27,7 @@ type URLWatcherOpt func(*URLWatcher) func WithURLWatcherCtx(ctx context.Context) URLWatcherOpt { return func(w *URLWatcher) { - w.watchCtx = ctx + w.ctx = ctx } } @@ -57,18 +57,20 @@ func NewURLWatcher(url string, opts ...URLWatcherOpt) *URLWatcher { if watcher.pollInterval <= 0 { watcher.pollInterval = defaultURLPollInterval } - if watcher.watchCtx == nil { - watcher.watchCtx = context.Background() + if watcher.ctx == nil { + watcher.ctx = context.Background() } return watcher } -func (w *URLWatcher) StartWatching(k *Keys) error { - ctx, cancel := context.WithCancel(w.watchCtx) +func (w *URLWatcher) StartWatching(keys *Keys) error { + ctx, cancel := context.WithCancel(w.ctx) w.cancel = cancel w.wg.Add(1) - go w.watch(k, ctx) + + go w.watch(ctx, keys) + return nil } @@ -79,7 +81,7 @@ func (w *URLWatcher) StopWatching() { w.wg.Wait() } -func (w *URLWatcher) watch(k *Keys, ctx context.Context) { +func (w *URLWatcher) watch(ctx context.Context, keys *Keys) { defer w.wg.Done() ticker := time.NewTicker(w.pollInterval) @@ -91,15 +93,18 @@ func (w *URLWatcher) watch(k *Keys, ctx context.Context) { return case <-ticker.C: - err := w.fetch(k, ctx) + err := w.fetch(ctx, keys) if err != nil { - slog.Error("failed to fetch keys", "error", err) + slog.Error( + "failed to fetch keys", + "error", err, + ) } } } } -func (w *URLWatcher) fetch(k *Keys, ctx context.Context) error { +func (w *URLWatcher) fetch(ctx context.Context, keys *Keys) error { request, err := http.NewRequestWithContext(ctx, http.MethodGet, w.url, nil) if err != nil { return fmt.Errorf("failed to create request: %w", err) @@ -120,14 +125,15 @@ func (w *URLWatcher) fetch(k *Keys, ctx context.Context) error { return fmt.Errorf("failed reading keys response: %w", err) } - return k.UpdateFromJSON(keysJson) + return keys.UpdateFromJSON(keysJson) } func LoadKeysFromURL(ctx context.Context, url string, watcherOpts ...URLWatcherOpt) (*Keys, error) { watcher := NewURLWatcher(url, watcherOpts...) keys := &Keys{} - if err := watcher.fetch(keys, ctx); err != nil { + err := watcher.fetch(ctx, keys) + if err != nil { return nil, err } From 78440a5d5177487009efcce0cd76f2a55a1ad49f Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 02:42:18 +0100 Subject: [PATCH 04/14] Remove ref to flaresolverr --- client_test.go | 45 ++++++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/client_test.go b/client_test.go index fcaafc5..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,13 +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, - twigots.WithFlareSolverr("http://0.0.0.0:8191"), - ) + twicketsKeys, err := keys.LoadKeysFromURL(twicketsKeysURL) + require.NoError(t, err) + + twicketsClient, err := twigots.NewClient(twicketsKeys) require.NoError(t, err) // Fetch ticket listings @@ -83,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 @@ -112,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 @@ -154,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 @@ -193,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 @@ -226,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) From 2a7324382b295319b24e5b1e1872d8125a2e7085 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 02:43:16 +0100 Subject: [PATCH 05/14] Add file watcher --- go.mod | 2 +- go.sum | 5 +- keys/file.go | 157 ++++++++++++++++++++++++++++++++++++++++++++++ keys/keys_test.go | 5 +- keys/url.go | 4 +- 5 files changed, 164 insertions(+), 9 deletions(-) create mode 100644 keys/file.go 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_test.go b/keys/keys_test.go index 76046dc..5c9952c 100644 --- a/keys/keys_test.go +++ b/keys/keys_test.go @@ -1,7 +1,6 @@ package keys_test import ( - "context" "net/http" "net/http/httptest" "os" @@ -30,7 +29,7 @@ func TestLoadKeysFromURL(t *testing.T) { })) defer server.Close() - k, err := keys.LoadKeysFromURL(context.Background(), server.URL) + k, err := keys.LoadKeysFromURL(server.URL) require.NoError(t, err) require.Equal(t, "test-api-key", k.APIKey()) @@ -104,7 +103,7 @@ func TestWatchURL(t *testing.T) { })) defer server.Close() - k, err := keys.LoadKeysFromURL(context.Background(), server.URL, keys.WithURLWatcherPollInterval(50*time.Millisecond)) + k, err := keys.LoadKeysFromURL(server.URL, keys.WithURLWatcherPollInterval(50*time.Millisecond)) require.NoError(t, err) err = k.StartWatching() diff --git a/keys/url.go b/keys/url.go index bf2577b..240507e 100644 --- a/keys/url.go +++ b/keys/url.go @@ -128,11 +128,11 @@ func (w *URLWatcher) fetch(ctx context.Context, keys *Keys) error { return keys.UpdateFromJSON(keysJson) } -func LoadKeysFromURL(ctx context.Context, url string, watcherOpts ...URLWatcherOpt) (*Keys, error) { +func LoadKeysFromURL(url string, watcherOpts ...URLWatcherOpt) (*Keys, error) { watcher := NewURLWatcher(url, watcherOpts...) keys := &Keys{} - err := watcher.fetch(ctx, keys) + err := watcher.fetch(watcher.ctx, keys) if err != nil { return nil, err } From 11e8caab8302c489e817b845978ec3e710139ba7 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 10:23:14 +0100 Subject: [PATCH 06/14] Cleanup keys.go --- keys/keys.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/keys/keys.go b/keys/keys.go index da9b019..652ca23 100644 --- a/keys/keys.go +++ b/keys/keys.go @@ -2,6 +2,7 @@ package keys import ( "encoding/json" + "errors" "fmt" "sync" ) @@ -65,24 +66,23 @@ func (k *Keys) Update(apiKey, userAgent, prosopoSiteKey, prosopoIntegrityToken * } func (k *Keys) UpdateFromJSON(keysJson []byte) error { - type keys struct { + 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"` } - var unmarshaledKeys keys - err := json.Unmarshal(keysJson, &unmarshaledKeys) + err := json.Unmarshal(keysJson, &keys) if err != nil { return fmt.Errorf("failed to unmarshal keys: %w", err) } k.Update( - &unmarshaledKeys.APIKey, - &unmarshaledKeys.UserAgent, - &unmarshaledKeys.ProsopoSiteKey, - &unmarshaledKeys.ProsopoIntegrityToken, + &keys.APIKey, + &keys.UserAgent, + &keys.ProsopoSiteKey, + &keys.ProsopoIntegrityToken, ) return nil @@ -98,7 +98,7 @@ func (k *Keys) SetWatcher(watcher Watcher) { func (k *Keys) StartWatching() error { if k.watcher == nil { - return fmt.Errorf("no watcher configured") + return errors.New("no watcher configured") } return k.watcher.StartWatching(k) From b263a12b3796f2be796e81a382983e3c58d4b627 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 10:51:07 +0100 Subject: [PATCH 07/14] Update readme --- README.md | 90 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 72 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 0cf8324..ebc32ec 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,32 @@ ![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) -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) @@ -25,19 +38,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`): + +- `api_key` +- `x-prosopo-site-key` +- `x-prosopo-android-integrity-token` + +These must be supplied to the package via a `keys.json` file that looks like: + +```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. -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: +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) -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. +### Loading Keys -This API key is not provided here due to liability concerns, but it appears to be a fixed, unchanging value. +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 +95,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 +185,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 +202,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 +223,6 @@ 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/) From d7b5b1b5101939c692027561e746bb14bed86348 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 10:51:34 +0100 Subject: [PATCH 08/14] Update example and add .env.example --- .env.example | 1 + example/main.go | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 .env.example 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/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) } From 64fae6075bf571d28144a61450eba06c5c4019d1 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 10:53:01 +0100 Subject: [PATCH 09/14] Update workflow --- .github/workflows/main.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 1b47b3de6bb8d7d20afb6a600040342f5f87d915 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 10:53:13 +0100 Subject: [PATCH 10/14] Run example in taskfile --- Taskfile.yaml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index aa8bb0e..a468ce8 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -1,6 +1,9 @@ # Docs: https://taskfile.dev/#/usage version: "3" +dotenv: + - .env + tasks: format: cmds: @@ -19,6 +22,6 @@ tasks: - go clean -testcache - task: test - run:services: + run:example: cmds: - - docker compose up -d + - go run ./example From a46fd4a8c8066429ae3b0d3ddd59dafbd5ba7fac Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 11:05:54 +0100 Subject: [PATCH 11/14] Update package to use android api --- client.go | 37 +++++++++++++++----------------- client_test.go | 5 ++--- url.go | 58 +++++++++++++------------------------------------- 3 files changed, 34 insertions(+), 66 deletions(-) diff --git a/client.go b/client.go index 825597a..5516f0a 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,11 +86,17 @@ 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{ + "api_key": c.keys.APIKey(), + "User-Agent": c.keys.UserAgent(), + "x-prosopo-site-key": c.keys.ProsopoSiteKey(), + "x-prosopo-android-integrity-token": c.keys.ProsopoIntegrityToken(), + }) + + response, err := request.Get(feedUrl) if err != nil { return nil, nil } @@ -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(keys *keys.Keys) (*Client, error) { + if keys == 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: keys, }, nil } diff --git a/client_test.go b/client_test.go index 24c538c..bcf06bb 100644 --- a/client_test.go +++ b/client_test.go @@ -245,10 +245,9 @@ func getMockUrlAndResponder( interval time.Duration, //nolint:unparam ) (string, httpmock.Responder) { url := fmt.Sprintf( - "https://www.twickets.live/services/catalogue?count=10&maxTime=%d&q=countryCode=%s&api_key=%s", - startTime.UnixMilli(), + "https://www.twickets.live/services/g2/catalogue?countryCode=%s&limit=10&maxTime=%d", twigots.CountryUnitedKingdom.Value, - testAPIKey, + startTime.UnixMilli(), ) response := getMockResponse(events, startTime, interval) diff --git a/url.go b/url.go index 9c1976a..1c9fbcb 100644 --- a/url.go +++ b/url.go @@ -10,12 +10,7 @@ import ( "time" ) -const ( - TwicketsURL = "https://www.twickets.live" - - countryQueryKey = "countryCode" - regionQueryKey = "regionCode" -) +const TwicketsURL = "https://www.twickets.live" var twicketsUrl *url.URL @@ -39,7 +34,6 @@ func ListingURL(listingId string, numTickets int) string { type FeedUrlInput struct { // Required fields - APIKey string Country Country // Optional fields @@ -50,9 +44,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 +58,7 @@ 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/g2/catalogue?countryCode=GB&limit=10 func FeedUrl(input FeedUrlInput) (string, error) { err := input.Validate() if err != nil { @@ -75,14 +66,21 @@ func FeedUrl(input FeedUrlInput) (string, error) { } feedUrl := cloneURL(twicketsUrl) - feedUrl = feedUrl.JoinPath("services", "catalogue") + feedUrl = feedUrl.JoinPath("services", "g2", "catalogue") // Set query params queryParams := feedUrl.Query() - locationQuery := apiLocationQuery(input.Country, input.Regions...) - if locationQuery != "" { - queryParams.Set("q", locationQuery) + queryParams.Set("countryCode", string(input.Country.Value)) + + regionCodes := make([]string, 0, len(input.Regions)) + for _, region := range input.Regions { + if Regions.Contains(region) { + regionCodes = append(regionCodes, string(region.Value)) + } + } + if len(regionCodes) > 0 { + queryParams.Set("regionCodes", strings.Join(regionCodes, ",")) } if !input.BeforeTime.IsZero() { @@ -90,39 +88,13 @@ func FeedUrl(input FeedUrlInput) (string, error) { 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 + queryParams.Set("limit", "10") // limit must always be 10 to not get an error - // Set query - encodedQuery := queryParams.Encode() - encodedQuery = strings.ReplaceAll(encodedQuery, "%3D", "=") - encodedQuery = strings.ReplaceAll(encodedQuery, "%2C", ",") - feedUrl.RawQuery = encodedQuery + feedUrl.RawQuery = queryParams.Encode() return feedUrl.String(), nil } -// apiLocationQuery converts a country and selection of regions to an api query string -func apiLocationQuery(country Country, regions ...Region) string { - if !Countries.Contains(country) { - return "" - } - - queryParts := make([]string, 0, len(regions)+1) - - countryQuery := fmt.Sprintf("%s=%s", countryQueryKey, country.Value) - queryParts = append(queryParts, countryQuery) - - for _, region := range regions { - if Regions.Contains(region) { - regionQuery := fmt.Sprintf("%s=%s", regionQueryKey, region.Value) - queryParts = append(queryParts, regionQuery) - } - } - - return strings.Join(queryParts, ",") -} - // cloneUrl clones a url. Copied directly from net/http internals // See: https://github.com/golang/go/blob/go1.19/src/net/http/clone.go#L22 func cloneURL(u *url.URL) *url.URL { From de3f9761b6ad20ebc655c5f323b051d474168eab Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 11:27:48 +0100 Subject: [PATCH 12/14] Fix url.go --- keys/url.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keys/url.go b/keys/url.go index 240507e..0310e64 100644 --- a/keys/url.go +++ b/keys/url.go @@ -105,7 +105,7 @@ func (w *URLWatcher) watch(ctx context.Context, keys *Keys) { } func (w *URLWatcher) fetch(ctx context.Context, keys *Keys) error { - request, err := http.NewRequestWithContext(ctx, http.MethodGet, w.url, nil) + request, err := http.NewRequestWithContext(ctx, http.MethodGet, w.url, http.NoBody) if err != nil { return fmt.Errorf("failed to create request: %w", err) } From fc59bb8641cb1b7cc9aeaceaaf916da3d29a52a9 Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 12:48:08 +0100 Subject: [PATCH 13/14] Revert back to old api --- client.go | 12 +++++------ client_test.go | 5 +++-- url.go | 55 +++++++++++++++++++++++++++++++++++--------------- 3 files changed, 48 insertions(+), 24 deletions(-) diff --git a/client.go b/client.go index 5516f0a..0d5a564 100644 --- a/client.go +++ b/client.go @@ -90,15 +90,15 @@ func (c *Client) FetchTicketListingsByFeedUrl(ctx context.Context, feedUrl strin request := c.client.R().SetContext(ctx) request.SetHeaders(map[string]string{ - "api_key": c.keys.APIKey(), "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() { @@ -111,7 +111,7 @@ func (c *Client) FetchTicketListingsByFeedUrl(ctx context.Context, feedUrl strin 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) @@ -203,8 +203,8 @@ func processFeedListings( } // NewClient creates a new Twickets client -func NewClient(keys *keys.Keys) (*Client, error) { - if keys == nil { +func NewClient(twicketsKeys *keys.Keys) (*Client, error) { + if twicketsKeys == nil { return nil, errors.New("keys must be set") } @@ -212,6 +212,6 @@ func NewClient(keys *keys.Keys) (*Client, error) { return &Client{ client: client, - keys: keys, + keys: twicketsKeys, }, nil } diff --git a/client_test.go b/client_test.go index bcf06bb..24c538c 100644 --- a/client_test.go +++ b/client_test.go @@ -245,9 +245,10 @@ func getMockUrlAndResponder( interval time.Duration, //nolint:unparam ) (string, httpmock.Responder) { url := fmt.Sprintf( - "https://www.twickets.live/services/g2/catalogue?countryCode=%s&limit=10&maxTime=%d", - twigots.CountryUnitedKingdom.Value, + "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/url.go b/url.go index 1c9fbcb..361744b 100644 --- a/url.go +++ b/url.go @@ -10,7 +10,12 @@ import ( "time" ) -const TwicketsURL = "https://www.twickets.live" +const ( + TwicketsURL = "https://www.twickets.live" + + countryQueryKey = "countryCode" + regionQueryKey = "regionCode" +) var twicketsUrl *url.URL @@ -58,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/g2/catalogue?countryCode=GB&limit=10 +// 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 { @@ -66,35 +73,51 @@ func FeedUrl(input FeedUrlInput) (string, error) { } feedUrl := cloneURL(twicketsUrl) - feedUrl = feedUrl.JoinPath("services", "g2", "catalogue") + feedUrl = feedUrl.JoinPath("services", "catalogue") // Set query params queryParams := feedUrl.Query() - queryParams.Set("countryCode", string(input.Country.Value)) - - regionCodes := make([]string, 0, len(input.Regions)) - for _, region := range input.Regions { - if Regions.Contains(region) { - regionCodes = append(regionCodes, string(region.Value)) - } - } - if len(regionCodes) > 0 { - queryParams.Set("regionCodes", strings.Join(regionCodes, ",")) - } + locationQuery := apiLocationQuery(input.Country, input.Regions...) + queryParams.Set("q", locationQuery) if !input.BeforeTime.IsZero() { maxTime := input.BeforeTime.UnixMilli() queryParams.Set("maxTime", strconv.Itoa(int(maxTime))) } - queryParams.Set("limit", "10") // limit must always be 10 to not get an error + queryParams.Set("count", "10") // count must always be 10 to not get an error - feedUrl.RawQuery = queryParams.Encode() + // Set query + encodedQuery := queryParams.Encode() + encodedQuery = strings.ReplaceAll(encodedQuery, "%3D", "=") + encodedQuery = strings.ReplaceAll(encodedQuery, "%2C", ",") + feedUrl.RawQuery = encodedQuery return feedUrl.String(), nil } +// apiLocationQuery converts a country and selection of regions to an api query string +func apiLocationQuery(country Country, regions ...Region) string { + if !Countries.Contains(country) { + return "" + } + + queryParts := make([]string, 0, len(regions)+1) + + countryQuery := fmt.Sprintf("%s=%s", countryQueryKey, country.Value) + queryParts = append(queryParts, countryQuery) + + for _, region := range regions { + if Regions.Contains(region) { + regionQuery := fmt.Sprintf("%s=%s", regionQueryKey, region.Value) + queryParts = append(queryParts, regionQuery) + } + } + + return strings.Join(queryParts, ",") +} + // cloneUrl clones a url. Copied directly from net/http internals // See: https://github.com/golang/go/blob/go1.19/src/net/http/clone.go#L22 func cloneURL(u *url.URL) *url.URL { From 3d9b4534a2a4781faec659b762d7847e1939599b Mon Sep 17 00:00:00 2001 From: Arran Hobson Sayers Date: Mon, 31 Aug 2026 12:48:15 +0100 Subject: [PATCH 14/14] Update readme bade --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index ebc32ec..9cdc796 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ [![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) [![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) > [!NOTE] > We're back! 💪 @@ -31,6 +32,7 @@ To use this API (and therefore this package), you will need to obtain API keys. - [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 @@ -226,3 +228,15 @@ This is done by: 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!