cinebase 5.5.0 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fc2298d0987c599332f671cd0532398aa84df5e623492f480ba8845814713af4
4
- data.tar.gz: 4186770cf7e9a235405f9245f7281c44c62bf0fb0adc83db6ccd6b86168d833d
3
+ metadata.gz: 25f1d3c24d08ce94759a22227a9d47764c194d9c9ace00d91b7daee90eedbc2d
4
+ data.tar.gz: 18f1ee13b3ffdd0274f6eed018cf1fdb834f1e598b99d680255b81d6c425ff94
5
5
  SHA512:
6
- metadata.gz: 9a5309228e4f27451c1a00fecee37b386e8aaabb9131a5447776d1ccdb4bc009c6f4fd7cd379cd204eced5ae2dc6417d41d8bb5f13e6f0e1dddd97e0dc828bfb
7
- data.tar.gz: f6f1b180642f3e65adaa143be1c3f95c25aa73e3788221aaf43f9fb55eb5da65488ca5bf615ff9d5953231c8d76d6fc88350de5a0f4ea0abbe5b575289b55289
6
+ metadata.gz: 49f12f235682b35ce9455b0a81468c8c99518b30271e8355c73560bf9e5af5b580a3476b1aff6bc995b78b70301012f078044c677454aefa65be5a2805589f0d
7
+ data.tar.gz: e5161f9a03d258e22a24dae4653280365633143bc473f61aec603ccbd79b176090da97cff6f9346a16e5b7180f3de44933a93fb232c28e0ddb6201b246abcbc0
data/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
  All notable changes to this project will be documented in this file.
3
3
  This project adheres to [Semantic Versioning](http://semver.org/).
4
4
 
5
+ ## [5.6.0] - 2026-10-31
6
+ ### Added
7
+ - `Cinema#latitude` and `Cinema#longitude`, `nil` by default. Chain gems return Floats in decimal degrees when they know where a cinema is.
8
+ - `Vista::TokenHolder` for chain modules: `token`, `acquire_token!`, `ensure_token!` (fetches only when there is no token or it expires within `RENEWAL_MARGIN`, an hour), `token_expires_at` and `reject_token!`
9
+ - `Vista::GuestToken.expires_at(token)` reads a JWT's `exp` claim
10
+ - `cinebase/boxoffice`, loaded only on request, for chains whose websites run on Webedia's "Movies Pro" theme and sell tickets through Boxoffice, such as Everyman and Showcase. Extracted from `everyman_uk`.
11
+ - `Boxoffice::Client` reads theatres from the website's daily static build and showtimes and films from its `/api/gatsby-source-boxofficeapi/` routes, with no token. It retries dropped connections, and a whole year of one theatre's showtimes is one request.
12
+ - `Boxoffice::Showtime` reads a showtime's start in the theatre's time zone, booking link (the chain's `default` provider first, then any other), dimension (`3d` or `RealD3D` tags), language and variants. `VARIANTS` maps Boxoffice's own tags; chains pass `variants:` with their own tags merged in.
13
+ - `Boxoffice::Cinema` and `Boxoffice::Performance` base classes. A chain defines `Cinema.website` and `#brand`, and `Performance.cinema_class`, `.title_sanitizer` and optionally `.variants`.
14
+
5
15
  ## [5.5.0] - 2026-10-22
6
16
  ### Changed
7
17
  - `Vista::Client` keeps one connection open for all its requests instead of opening a new TLS connection each time, which cost over ten times the request itself. Requests on one client are serialised, so a client can be shared between threads.
data/README.md CHANGED
@@ -37,6 +37,14 @@ module CinemaChainName
37
37
  end
38
38
 
39
39
  # define address methods
40
+
41
+ def latitude
42
+ # Float in decimal degrees, or nil when unknown (the default)
43
+ end
44
+
45
+ def longitude
46
+ # Float in decimal degrees, or nil when unknown (the default)
47
+ end
40
48
  end
41
49
  end
42
50
 
@@ -132,7 +140,32 @@ end
132
140
 
133
141
  `GuestToken#fetch` runs `curl-impersonate` with a Chrome profile, checks the
134
142
  token's declared expiry and raises `Cinebase::Vista::AuthenticationError` when
135
- it cannot get a current token. To ship curl-impersonate inside platform gems,
143
+ it cannot get a current token. `GuestToken.expires_at(token)` reads a token's
144
+ `exp` claim as a `Time`, or `nil` when it cannot.
145
+
146
+ A chain module keeps its token by extending `TokenHolder`:
147
+
148
+ ```ruby
149
+ module CinemaChainName
150
+ extend Cinebase::Vista::TokenHolder
151
+
152
+ def self.guest_token_class
153
+ Internal::GuestToken
154
+ end
155
+ end
156
+
157
+ CinemaChainName.token = guest_jwt # set one you already have
158
+ CinemaChainName.acquire_token! # always fetches a new token
159
+ CinemaChainName.ensure_token! # fetches only when there is no token
160
+ # or it expires within an hour
161
+ CinemaChainName.token_expires_at #=> 2026-10-30 18:00:00 +0000
162
+ CinemaChainName.reject_token!(rejected) # forgets a token the API rejected
163
+ ```
164
+
165
+ API calls never fetch a token themselves. When the API rejects a token, the
166
+ chain gem calls `reject_token!` and re-raises, so the next `ensure_token!`
167
+ fetches a fresh one. `reject_token!` keeps a token set since the rejected
168
+ request. To ship curl-impersonate inside platform gems,
136
169
  add this to the chain gem's Rakefile:
137
170
 
138
171
  ```ruby
@@ -141,6 +174,52 @@ Cinebase::Vista::PackageTask.new('chain_name.gemspec')
141
174
  # rake 'package:native[arm64-darwin]' or rake package:all
142
175
  ```
143
176
 
177
+ ### Boxoffice chains
178
+
179
+ Chains whose websites run on Webedia's "Movies Pro" theme and sell tickets
180
+ through Boxoffice (Everyman, Showcase) share a client and base classes. These
181
+ are not loaded by `require 'cinebase'`:
182
+
183
+ ```ruby
184
+ require 'cinebase/boxoffice'
185
+
186
+ module CinemaChainName
187
+ class Cinema < Cinebase::Boxoffice::Cinema
188
+ def self.website
189
+ 'https://www.example.co.uk'
190
+ end
191
+
192
+ def brand
193
+ 'Example'
194
+ end
195
+ end
196
+
197
+ class Performance < Cinebase::Boxoffice::Performance
198
+ def self.cinema_class
199
+ Cinema
200
+ end
201
+
202
+ def self.title_sanitizer
203
+ Internal::TitleSanitizer
204
+ end
205
+
206
+ # Optional: the chain's own tags, e.g. screen brands
207
+ def self.variants
208
+ super.merge('Internal.Brand.XPlus' => 'xplus')
209
+ end
210
+ end
211
+ end
212
+
213
+ CinemaChainName::Cinema.all # open UK theatres, cached for an hour
214
+ CinemaChainName::Performance.at('X0712', from: Date.today, to: Date.today + 365)
215
+ ```
216
+
217
+ `Cinema` gives `adr`, `name`, `url`, `latitude`, `longitude` and
218
+ `time_zone` from the theatre list in the website's daily build.
219
+ `Performance.at` makes one schedule request for the whole range and one
220
+ request per 50 films. `Cinebase::Boxoffice::Client.new(base_url:)` is the
221
+ underlying client, with `theaters`, `schedule` and `movies`.
222
+
144
223
  ## Contributing
145
224
 
146
225
  1. [Fork it](https://github.com/andycroll/cinebase/fork)
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cinebase
4
+ module Boxoffice
5
+ # Cinema base class for a Boxoffice chain. Subclasses define `.website`
6
+ # and `#brand`.
7
+ class Cinema < Cinebase::Cinema
8
+ # Worker processes outlive a day's listings, so refetch the theatre list
9
+ CACHE_SECONDS = 3600
10
+
11
+ # @return [String] the chain website, e.g. 'https://www.everymancinema.com'
12
+ def self.website
13
+ raise NotImplementedError, "#{self} must define .website"
14
+ end
15
+
16
+ # @return [Cinebase::Boxoffice::Client]
17
+ def self.client
18
+ Client.new(base_url: website)
19
+ end
20
+
21
+ # Every open UK cinema
22
+ # @return [Array<Cinebase::Boxoffice::Cinema>] instances of the subclass
23
+ def self.all
24
+ theaters_hash.keys.map { |id| new(id) }
25
+ end
26
+
27
+ # @param [String] id the Boxoffice theatre id, e.g. 'X0712' or 'x0712'
28
+ def initialize(id)
29
+ @id = id.to_s.upcase
30
+ end
31
+
32
+ # @return [Hash] contains :street_address, :extended_address,
33
+ # :locality, :region, :postal_code, :country_name
34
+ def adr
35
+ location = theater.dig('practicalInfo', 'location') || {}
36
+ {
37
+ street_address: location['address'],
38
+ extended_address: nil,
39
+ locality: location['city'],
40
+ region: nil,
41
+ postal_code: location['zip']&.squeeze(' ')&.upcase,
42
+ country_name: 'United Kingdom'
43
+ }
44
+ end
45
+
46
+ # @return [Float, nil]
47
+ def latitude
48
+ theater.dig('practicalInfo', 'coordinates', 'latitude')
49
+ end
50
+
51
+ # @return [Float, nil]
52
+ def longitude
53
+ theater.dig('practicalInfo', 'coordinates', 'longitude')
54
+ end
55
+
56
+ # @return [String] e.g. 'Baker Street'
57
+ def name
58
+ theater['name'].to_s
59
+ end
60
+
61
+ # @return [String] e.g. 'Europe/London'
62
+ def time_zone
63
+ theater.fetch('timeZone', 'Europe/London')
64
+ end
65
+
66
+ # @return [String] the cinema's page on the chain website
67
+ def url
68
+ self.class.website + theater['path'].to_s
69
+ end
70
+
71
+ def self.theaters_hash
72
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
73
+ if @theaters_hash.nil? || now - @fetched_at > CACHE_SECONDS
74
+ @fetched_at = now
75
+ @theaters_hash = client.theaters.select { |theater| open_in_uk?(theater) }
76
+ .to_h { |theater| [theater.fetch('id'), theater] }
77
+ end
78
+ @theaters_hash
79
+ end
80
+ private_class_method :theaters_hash
81
+
82
+ def self.open_in_uk?(theater)
83
+ theater.dig('country', 'iso31661A2') == 'GB' && !theater.dig('practicalInfo', 'closed')
84
+ end
85
+ private_class_method :open_in_uk?
86
+
87
+ private
88
+
89
+ def theater
90
+ self.class.send(:theaters_hash).fetch(id, {})
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+
6
+ module Cinebase
7
+ module Boxoffice
8
+ # Reads theatres from a chain website's static build and listings from
9
+ # the website's own Boxoffice API routes. No token is needed.
10
+ class Client
11
+ API_PATH = '/api/gatsby-source-boxofficeapi/'
12
+ BUILD_URL = %r{https://cms-assets\.webediamovies\.pro/prod/[\w-]+/\d{4}-\d{2}-\d{2}/public/}
13
+ # The theme's theatre list query, tried before the home page's others
14
+ THEATERS_QUERY = '2506275789'
15
+ # The website asks for the same number of films at once
16
+ MOVIES_PER_REQUEST = 50
17
+ # Listings days run from 3am to 3am, like the website's
18
+ DAY_STARTS_AT = 'T03:00:00'
19
+ RETRIES = 2
20
+ TRANSIENT_ERRORS = [
21
+ EOFError, Errno::ECONNRESET, Errno::ECONNREFUSED, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError
22
+ ].freeze
23
+
24
+ attr_reader :base_url
25
+
26
+ # @param [String] base_url the chain website, e.g. 'https://www.everymancinema.com'
27
+ def initialize(base_url:)
28
+ @base_url = base_url.delete_suffix('/')
29
+ end
30
+
31
+ # @return [Array<Hash>] every theatre in the website's daily build
32
+ def theaters
33
+ build_url = current_build_url
34
+ hashes = page_data(build_url, 'page-data/index/page-data.json').fetch('staticQueryHashes')
35
+ hashes.sort_by { |hash| hash == THEATERS_QUERY ? 0 : 1 }.each do |hash|
36
+ theaters = page_data(build_url, "page-data/sq/d/#{hash}.json").dig('data', 'allTheater', 'nodes')
37
+ return theaters if theaters
38
+ end
39
+ raise "No theatre list in #{build_url}"
40
+ end
41
+
42
+ # @param [String] theater_id e.g. 'X0712'
43
+ # @param [String] time_zone the theatre's, e.g. 'Europe/London'
44
+ # @param [Date] from first listings day
45
+ # @param [Date] to last listings day
46
+ # @return [Hash{String => Hash{String => Array<Hash>}}] showtimes by
47
+ # movie id, then by day
48
+ def schedule(theater_id, time_zone:, from:, to:)
49
+ query = {
50
+ 'from' => from.iso8601 + DAY_STARTS_AT,
51
+ 'to' => (to + 1).iso8601 + DAY_STARTS_AT,
52
+ 'theaters' => JSON.generate('id' => theater_id, 'timeZone' => time_zone)
53
+ }
54
+ api('schedule', query).dig(theater_id, 'schedule') || {}
55
+ end
56
+
57
+ # @param [Array<String>] ids movie ids
58
+ # @return [Array<Hash>] movies
59
+ def movies(ids)
60
+ ids.uniq.each_slice(MOVIES_PER_REQUEST).flat_map { |slice| api('movies', 'ids' => slice) }
61
+ end
62
+
63
+ private
64
+
65
+ def api(path, query)
66
+ JSON.parse(get("#{@base_url}#{API_PATH}#{path}?#{URI.encode_www_form(query)}", accept: 'application/json'))
67
+ end
68
+
69
+ # The build moves to a new dated path every day, and the home page can
70
+ # still link images from an older one
71
+ def current_build_url
72
+ get(@base_url + '/', accept: 'text/html').scan(BUILD_URL).max || raise("No build path on #{@base_url}")
73
+ end
74
+
75
+ def page_data(build_url, path)
76
+ JSON.parse(get(build_url + path, accept: 'application/json'))
77
+ end
78
+
79
+ def get(url, accept:)
80
+ uri = URI(url)
81
+ request = Net::HTTP::Get.new(uri)
82
+ request['Accept'] = accept
83
+ attempts = 0
84
+ begin
85
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
86
+ http.request(request)
87
+ end
88
+ rescue *TRANSIENT_ERRORS
89
+ attempts += 1
90
+ raise if attempts > RETRIES
91
+
92
+ sleep(attempts)
93
+ retry
94
+ end
95
+ # Omit response bodies from errors, and never follow redirects.
96
+ raise "HTTP error #{response.code} from #{uri.host}" unless response.is_a?(Net::HTTPSuccess)
97
+
98
+ response.body
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cinebase
4
+ module Boxoffice
5
+ # Performance base class for a Boxoffice chain. Subclasses define
6
+ # `.cinema_class` and `.title_sanitizer`, and may override `.variants`.
7
+ class Performance < Cinebase::Performance
8
+ # @return [Class] the chain's Cinebase::Boxoffice::Cinema subclass
9
+ def self.cinema_class
10
+ raise NotImplementedError, "#{self} must define .cinema_class"
11
+ end
12
+
13
+ # @return [Class] the chain's Cinebase::TitleSanitizer subclass
14
+ def self.title_sanitizer
15
+ raise NotImplementedError, "#{self} must define .title_sanitizer"
16
+ end
17
+
18
+ # @return [Hash{String => String}] Boxoffice tags and the variants they mean
19
+ def self.variants
20
+ Showtime::VARIANTS
21
+ end
22
+
23
+ # Performances within an inclusive range of listings days, from one
24
+ # schedule request for the whole range and one request per 50 films.
25
+ # @param [String] cinema_id e.g. 'X0712'
26
+ # @param [Date] from first date (defaults to today in London)
27
+ # @param [Date] to last date (defaults to 13 days after from)
28
+ # @return [Array<Cinebase::Boxoffice::Performance>] instances of the subclass
29
+ def self.at(
30
+ cinema_id,
31
+ from: TZInfo::Timezone.get('Europe/London').now.to_date,
32
+ to: from + 13
33
+ )
34
+ raise ArgumentError, 'to must not precede from' if to < from
35
+
36
+ cinema = cinema_class.new(cinema_id)
37
+ client = cinema_class.client
38
+ schedule = client.schedule(cinema.id, time_zone: cinema.time_zone, from: from, to: to)
39
+ movies = client.movies(schedule.keys).to_h { |movie| [movie.fetch('id').to_s, movie] }
40
+
41
+ performances = schedule.flat_map do |movie_id, days|
42
+ title = movies.dig(movie_id.to_s, 'title')
43
+ next [] unless title
44
+
45
+ days.values.flatten.map do |showtime|
46
+ parsed = Showtime.new(showtime, time_zone: cinema.time_zone, variants: variants)
47
+ new(attributes(parsed, title).merge(cinema_id: cinema.id, cinema_name: cinema.name))
48
+ end
49
+ end
50
+ performances.sort_by(&:starting_at)
51
+ end
52
+
53
+ # Release dates are UK releases, so re-releases would get the wrong year;
54
+ # only a year in the title counts.
55
+ def self.attributes(showtime, title)
56
+ starting_at = showtime.starting_at
57
+ {
58
+ booking_url: showtime.booking_url,
59
+ dimension: showtime.dimension,
60
+ festival: Festival.from_title(title, year: starting_at.year),
61
+ film_name: title_sanitizer.new(title).sanitized,
62
+ film_year: TitleSanitizer.film_year(title),
63
+ language: showtime.language || title[/\((#{TitleSanitizer::LANGUAGES.join('|')})\)/i, 1],
64
+ starting_at: starting_at,
65
+ variant: showtime.variant
66
+ }
67
+ end
68
+ private_class_method :attributes
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cinebase
4
+ module Boxoffice
5
+ # Reads one Boxoffice showtime: its start, booking link and tags
6
+ class Showtime
7
+ # Boxoffice's own tags and the variants they mean. Chains label them
8
+ # differently, e.g. KidsFriendly is Everyman's Toddler Club. Chains
9
+ # merge in their own tags, such as screen brands.
10
+ VARIANTS = {
11
+ 'Format.Projection.35mm' => '35mm',
12
+ 'Showtime.Accessibility.AudioDescription' => 'audio_described',
13
+ 'Showtime.Accessibility.AutismFriendly' => 'relaxed',
14
+ 'Showtime.Accessibility.ClosedCaption' => 'subtitled',
15
+ 'Showtime.Accessibility.SensoryFriendly' => 'relaxed',
16
+ 'Showtime.Accessibility.Subtitled' => 'subtitled',
17
+ 'Showtime.Event.QandAEvent' => 'q&a',
18
+ 'Showtime.Event.QandARecorded' => 'q&a',
19
+ 'Showtime.Experience.EncoreShow' => 'arts',
20
+ 'Showtime.Experience.FamilyFriendly' => 'kids',
21
+ 'Showtime.Experience.LiveSatellite' => 'arts',
22
+ 'Showtime.Experience.LiveShow' => 'arts',
23
+ 'Showtime.Restriction.BabyClub' => 'baby',
24
+ 'Showtime.Restriction.KidsFriendly' => 'kids',
25
+ 'Showtime.Restriction.LoyaltyOnly' => 'members',
26
+ 'Showtime.Restriction.Senior' => 'senior',
27
+ 'Showtime.Restriction.SilverScreen' => 'senior'
28
+ }.freeze
29
+
30
+ # Format.Projection.3d, or RealD3D alone on Showcase's XPlus RealD 3D
31
+ THREE_D = /\.(RealD)?3d\z/i
32
+ LANGUAGE = /\ALocalization\.Language\.(\w+)\z/
33
+
34
+ # @param [Hash] showtime one showtime from the schedule
35
+ # @param [String] time_zone the theatre's, e.g. 'Europe/London'
36
+ # @param [Hash{String => String}] variants tags and the variants they mean
37
+ def initialize(showtime, time_zone:, variants: VARIANTS)
38
+ @showtime = showtime
39
+ @time_zone = time_zone
40
+ @variants = variants
41
+ end
42
+
43
+ # Showcase also lists a 'relay' provider, so the chain's own 'default'
44
+ # comes first
45
+ # @return [String, nil] the chain's own booking page
46
+ def booking_url
47
+ ticketing = @showtime.dig('data', 'ticketing') || []
48
+ link = ticketing.find { |entry| entry['provider'] == 'default' } || ticketing.first
49
+ link&.fetch('urls', [])&.first
50
+ end
51
+
52
+ # @return [String] '2d' or '3d'
53
+ def dimension
54
+ tags.any? { |tag| tag.match?(THREE_D) } ? '3d' : '2d'
55
+ end
56
+
57
+ # @return [String, nil] audio language, e.g. 'Korean'
58
+ def language
59
+ tags.filter_map { |tag| tag[LANGUAGE, 1] }.first
60
+ end
61
+
62
+ # startsAt is the theatre's local time, without an offset
63
+ # @return [Time] UTC
64
+ def starting_at
65
+ local = Time.utc(*@showtime.fetch('startsAt').scan(/\d+/).map(&:to_i))
66
+ TZInfo::Timezone.get(@time_zone).local_to_utc(local) { |periods| periods.first }.utc
67
+ end
68
+
69
+ # @return [Array<String>]
70
+ def variant
71
+ tags.filter_map { |tag| @variants[tag] }.uniq
72
+ end
73
+
74
+ private
75
+
76
+ def tags
77
+ @showtime.fetch('tags', [])
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'cinebase'
4
+
5
+ module Cinebase
6
+ # Shared support for chains whose websites run on Webedia's "Movies Pro"
7
+ # Gatsby theme and sell tickets through Boxoffice. Not loaded by
8
+ # `require 'cinebase'`; these gems `require 'cinebase/boxoffice'`.
9
+ module Boxoffice
10
+ end
11
+ end
12
+
13
+ require 'cinebase/boxoffice/client'
14
+ require 'cinebase/boxoffice/showtime'
15
+ require 'cinebase/boxoffice/cinema'
16
+ require 'cinebase/boxoffice/performance'
@@ -40,10 +40,18 @@ module Cinebase
40
40
  @full_name ||= "#{brand} #{name}"
41
41
  end
42
42
 
43
+ def latitude
44
+ nil
45
+ end
46
+
43
47
  def locality
44
48
  adr[:locality].to_s
45
49
  end
46
50
 
51
+ def longitude
52
+ nil
53
+ end
54
+
47
55
  def postal_code
48
56
  adr[:postal_code].to_s
49
57
  end
@@ -2,5 +2,5 @@
2
2
 
3
3
  # Cinebase version
4
4
  module Cinebase
5
- VERSION = '5.5.0'
5
+ VERSION = '5.6.0'
6
6
  end
@@ -15,6 +15,16 @@ module Cinebase
15
15
  @curl = curl || default_curl
16
16
  end
17
17
 
18
+ # @param [String] token a JWT
19
+ # @return [Time, nil] from the token's exp claim; nil when it has none or
20
+ # cannot be read
21
+ def self.expires_at(token)
22
+ payload = token.split('.').fetch(1).tr('-_', '+/').unpack1('m')
23
+ Time.at(Integer(JSON.parse(payload).fetch('exp')))
24
+ rescue JSON::ParserError, ArgumentError, IndexError, TypeError, NoMethodError
25
+ nil
26
+ end
27
+
18
28
  # @return [String] the guest JWT
19
29
  # @raise [Cinebase::Vista::AuthenticationError]
20
30
  def fetch
@@ -66,9 +76,10 @@ module Cinebase
66
76
  end
67
77
 
68
78
  def validate_expiry!(token)
69
- payload = token.split('.').fetch(1).tr('-_', '+/').unpack1('m')
70
- claims = JSON.parse(payload)
71
- if Integer(claims.fetch('exp')) <= Time.now.to_i
79
+ expires_at = self.class.expires_at(token)
80
+ if expires_at.nil?
81
+ raise AuthenticationError, 'Guest token page data is missing or invalid'
82
+ elsif expires_at <= Time.now
72
83
  raise AuthenticationError, 'Guest token supplied by the page has expired'
73
84
  end
74
85
  end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cinebase
4
+ module Vista
5
+ # Keeps a chain's guest token. A chain module extends it and defines
6
+ # .guest_token_class. API calls never fetch a token; callers do, with
7
+ # #acquire_token! or #ensure_token!.
8
+ module TokenHolder
9
+ # A token this close to expiry is renewed, so it outlasts a long import
10
+ RENEWAL_MARGIN = 3600
11
+
12
+ # @return [String, nil] raw guest JWT, without the "Bearer " prefix.
13
+ # Never persisted.
14
+ attr_accessor :token
15
+
16
+ # Fetches a new guest token, whatever the current one
17
+ # @param [String, nil] curl curl-impersonate executable
18
+ # @return [String] the guest JWT
19
+ # @raise [Cinebase::Vista::AuthenticationError]
20
+ def acquire_token!(curl: nil)
21
+ self.token = guest_token_class.new(curl: curl).fetch
22
+ end
23
+
24
+ # Fetches a guest token only when there is none, or the current one is
25
+ # unreadable or expires within RENEWAL_MARGIN
26
+ # @param [String, nil] curl curl-impersonate executable
27
+ # @return [String] the guest JWT
28
+ # @raise [Cinebase::Vista::AuthenticationError]
29
+ def ensure_token!(curl: nil)
30
+ expires_at = token_expires_at
31
+ if expires_at.nil? || expires_at - Time.now <= RENEWAL_MARGIN
32
+ acquire_token!(curl: curl)
33
+ else
34
+ token
35
+ end
36
+ end
37
+
38
+ # Forgets a token the API rejected, so the next #ensure_token! fetches
39
+ # one. A token set since the rejected request is kept.
40
+ # @param [String, nil] rejected the token the API rejected
41
+ def reject_token!(rejected = token)
42
+ self.token = nil if token == rejected
43
+ end
44
+
45
+ # @return [Time, nil] from the token's exp claim; nil without a
46
+ # readable token
47
+ def token_expires_at
48
+ GuestToken.expires_at(token) if token
49
+ end
50
+
51
+ # @return [Class] the chain's Cinebase::Vista::GuestToken subclass
52
+ def guest_token_class
53
+ raise NotImplementedError, "#{self} must define guest_token_class"
54
+ end
55
+ end
56
+ end
57
+ end
@@ -12,3 +12,4 @@ end
12
12
 
13
13
  require 'cinebase/vista/client'
14
14
  require 'cinebase/vista/guest_token'
15
+ require 'cinebase/vista/token_holder'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cinebase
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.5.0
4
+ version: 5.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andy Croll
@@ -143,6 +143,11 @@ files:
143
143
  - bin/setup
144
144
  - cinebase.gemspec
145
145
  - lib/cinebase.rb
146
+ - lib/cinebase/boxoffice.rb
147
+ - lib/cinebase/boxoffice/cinema.rb
148
+ - lib/cinebase/boxoffice/client.rb
149
+ - lib/cinebase/boxoffice/performance.rb
150
+ - lib/cinebase/boxoffice/showtime.rb
146
151
  - lib/cinebase/cinema.rb
147
152
  - lib/cinebase/festival.rb
148
153
  - lib/cinebase/performance.rb
@@ -152,6 +157,7 @@ files:
152
157
  - lib/cinebase/vista/client.rb
153
158
  - lib/cinebase/vista/guest_token.rb
154
159
  - lib/cinebase/vista/package_task.rb
160
+ - lib/cinebase/vista/token_holder.rb
155
161
  homepage: http://github.com/andycroll/cinebase
156
162
  licenses:
157
163
  - MIT