Class: Spotlite::Movie

Inherits:
Object
  • Object
show all
Defined in:
lib/spotlite/movie.rb

Overview

Represents a movie on IMDb.com

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(imdb_id, title = nil, year = nil) ⇒ Movie

Initialize a new movie object by its IMDb ID as a string

movie = Spotlite::Movie.new('0133093')

Spotlite::Movie class objects are lazy loading. No HTTP request will be performed upon object initialization. HTTP request will be performed once when you use a method that needs remote data Currently, all data is spread across 6 pages: main movie page, /releaseinfo, /fullcredits, /keywords, /trivia, and /criticreviews



15
16
17
18
19
20
# File 'lib/spotlite/movie.rb', line 15

def initialize(imdb_id, title = nil, year = nil)
  @imdb_id = "%07d" % imdb_id.to_i
  @title   = title
  @year    = year
  @url     = "http://www.imdb.com/title/tt#{@imdb_id}/"
end

Instance Attribute Details

#imdb_idObject

Returns the value of attribute imdb_id.



4
5
6
# File 'lib/spotlite/movie.rb', line 4

def imdb_id
  @imdb_id
end

#responseObject

Returns the value of attribute response.



4
5
6
# File 'lib/spotlite/movie.rb', line 4

def response
  @response
end

#urlObject

Returns the value of attribute url.



4
5
6
# File 'lib/spotlite/movie.rb', line 4

def url
  @url
end

Class Method Details

.find(query) ⇒ Object

Returns a list of movies as an array of Spotlite::Movie objects Takes single parameter and searches for movies by title and alternative titles



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/spotlite/movie.rb', line 24

def self.find(query)
  results = Spotlite::Client.get(
    'http://www.imdb.com/find', query: { q: query, s: 'tt', ttype: 'ft' }
  )
  results.css('.result_text').map do |result|
    imdb_id = result.at('a')['href'].parse_imdb_id
    title   = result.at('a').text.strip
    year    = result.children.take(3).last.text.parse_year

    [imdb_id, title, year]
  end.map do |values|
    self.new(*values)
  end
end

.search(params = {}) ⇒ Object

Returns a list of movies as an array of Spotlite::Movie objects Takes optional parameters as a hash See github.com/defeed/spotlite/wiki/Advanced-movie-search for details



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/spotlite/movie.rb', line 42

def self.search(params = {})
  defaults = {
    title_type: 'feature',
    view: 'simple',
    count: 250,
    start: 1,
    sort: 'moviemeter,asc'
  }
  params = defaults.merge(params)
  results = Spotlite::Client.get(
    'http://www.imdb.com/search/title', query: params
  )
  results.css('td.title').map do |result|
    imdb_id = result.at('a')['href'].parse_imdb_id
    title   = result.at('a').text.strip
    year    = result.at('.year_type').text.parse_year

    [imdb_id, title, year]
  end.map do |values|
    self.new(*values)
  end
end

Instance Method Details

#alternative_titlesObject

Returns a list of movie alternative titles as an array of hashes with keys title (string) and comment (string)



190
191
192
193
194
195
196
197
198
# File 'lib/spotlite/movie.rb', line 190

def alternative_titles
  array = []
  release_info.css('#akas').css('tr').map do |row|
    cells = row.css('td')
    array << { :title => cells.last.text.strip, :comment => cells.first.text.strip }
  end

  array
end

#castObject

Returns a list of actors as an array Spotlite::Person objects



228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/spotlite/movie.rb', line 228

def cast
  full_credits.css('table.cast_list tr').reject do |row|
    # Skip 'Rest of cast' row
    row.children.size == 1
  end.map do |row|
    imdb_id = row.at('td:nth-child(2) a')['href'].parse_imdb_id
    name = row.at('td:nth-child(2) a').text.strip_whitespace
    credits_text = row.last_element_child.text.strip_whitespace

    [imdb_id, name, 'Cast', credits_text]
  end.map do |values|
    Spotlite::Person.new(*values)
  end
end

#content_ratingObject

Returns content rating as a string



113
114
115
# File 'lib/spotlite/movie.rb', line 113

def content_rating
  details.at("div.subtext meta[itemprop='contentRating']")['content'] rescue nil
end

#countriesObject

Returns a list of countries as an array of hashes with keys: code (string) and name (string)



124
125
126
127
128
129
130
131
# File 'lib/spotlite/movie.rb', line 124

def countries
  array = []
  details.css("div.txt-block a[href^='/country/']").each do |node|
    array << {:code => node['href'].clean_href, :name => node.text.strip}
  end

  array
end

#creditsObject

Returns combined ‘cast` and `crew` as an array of Spotlite::Person objects



270
271
272
# File 'lib/spotlite/movie.rb', line 270

def credits
  cast + crew
end

#crewObject

Combines all crew categories and returns an array of Spotlite::Person objects



265
266
267
# File 'lib/spotlite/movie.rb', line 265

def crew
  crew_categories.map{ |category| parse_crew(category) }.flatten
end

#crew_categoriesObject

Returns available crew categories, e.g. “Art Department”, “Writing Credits”, or “Stunts”, as an array of strings



275
276
277
278
279
280
281
282
# File 'lib/spotlite/movie.rb', line 275

def crew_categories
  array = []
  full_credits.css('h4.dataHeaderWithBorder').reject{ |h| h['id'] == 'cast' }.map do |node|
    array << (node.children.size > 1 ? node.children.first.text.strip_whitespace : node.children.text.strip_whitespace)
  end

  array
end

#critic_reviewsObject

Returns a list of critic reviews as an array of hashes with keys: source (string), author (string), excerpt (string), and score (integer)



313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/spotlite/movie.rb', line 313

def critic_reviews
  array = []
  reviews.css("tr[itemprop='reviews']").map do |review|
    source = review.at("b[itemprop='publisher'] span[itemprop='name']").text
    author = review.at("span[itemprop='author'] span[itemprop='name']").text
    excerpt = review.at("div[itemprop='reviewbody']").text.strip
    score = review.at("span[itemprop='ratingValue']").text.to_i

    array << { :source => source, :author => author, :excerpt => excerpt, :score => score }
  end

  array
end

#descriptionObject

Returns short description as a string



97
98
99
100
# File 'lib/spotlite/movie.rb', line 97

def description
  desc = details.at("div.summary_text[itemprop='description']").text.strip.clean_description rescue nil
  (desc.nil? || desc.empty?) ? nil : desc
end

#directorsObject

Returns a list of directors as an array of Spotlite::Person objects



201
202
203
# File 'lib/spotlite/movie.rb', line 201

def directors
  parse_crew('Directed by')
end

#genresObject

Returns a list of genres as an array of strings



118
119
120
# File 'lib/spotlite/movie.rb', line 118

def genres
  details.css("div.subtext a[href^='/genre/']").map { |genre| genre.text } rescue []
end

#imagesObject

Returns URLs of movie still frames as an array of strings



328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/spotlite/movie.rb', line 328

def images
  array = []
  still_frames.css('#media_index_thumbnail_grid img').map do |image|
    src = image['src'] rescue nil

    if src =~ /^(http:.+@@)/ || src =~ /^(http:.+?)\.[^\/]+$/
      array << $1 + '.jpg'
    end
  end

  array
end

#keywordsObject

Returns a list of keywords as an array of strings



179
180
181
# File 'lib/spotlite/movie.rb', line 179

def keywords
  plot_keywords.css("a[href^='/keyword/']").map { |keyword| keyword.text.strip } rescue []
end

#languagesObject

Returns a list of languages as an array of hashes with keys: code (string) and name (string)



135
136
137
138
139
140
141
142
# File 'lib/spotlite/movie.rb', line 135

def languages
  array = []
  details.css("div.txt-block a[href^='/language/']").each do |node|
    array << {:code => node['href'].clean_href, :name => node.text.strip}
  end

  array
end

#metascoreObject

Returns Metascore rating as an integer



87
88
89
# File 'lib/spotlite/movie.rb', line 87

def metascore
  details.at("div.titleReviewBar a[href^=criticreviews] span").text.to_i rescue nil
end

#original_titleObject

Returns original non-english title as a string



72
73
74
# File 'lib/spotlite/movie.rb', line 72

def original_title
  details.at("div.originalTitle").children.first.text.gsub('"', '').strip rescue nil
end

#parse_crew(category) ⇒ Object

Returns a list of crew members of a certain category as an array Spotlite::Person objects



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/spotlite/movie.rb', line 244

def parse_crew(category)
  table = full_credits.search("[text()^='#{category}']").first.next_element rescue nil
  if table && table.name == 'table'
    table.css('tr').reject do |row|
      # Skip empty table rows with one non-braking space
      row.text.strip.size == 1
    end.map do |row|
      imdb_id = row.first_element_child.at('a')['href'].parse_imdb_id
      name = row.first_element_child.at('a').text.strip_whitespace
      credits_text = row.last_element_child.text.strip_whitespace.clean_credits_text

      [imdb_id, name, category, credits_text]
    end.map do |values|
      Spotlite::Person.new(*values)
    end
  else
    []
  end
end

#poster_urlObject

Returns primary poster URL as a string



150
151
152
153
154
155
156
# File 'lib/spotlite/movie.rb', line 150

def poster_url
  src = details.at('div.poster img')['src'] rescue nil

  if src =~ /^(http:.+@@)/ || src =~ /^(http:.+?)\.[^\/]+$/
    $1 + '.jpg'
  end
end

#producersObject

Returns a list of producers as an array of Spotlite::Person objects



211
212
213
# File 'lib/spotlite/movie.rb', line 211

def producers
  parse_crew('Produced by')
end

#ratingObject

Returns IMDb rating as a float



82
83
84
# File 'lib/spotlite/movie.rb', line 82

def rating
  details.at("div.imdbRating span[itemprop='ratingValue']").text.to_f rescue nil
end

Returns an array of recommended movies as an array of initialized objects of Movie class



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/spotlite/movie.rb', line 159

def recommended_movies
  details.css('.rec-title').reject do |node|
    # reject movies that don't have a release year yet
    node.at('span').nil?
  end.reject do |node|
    # reject everything other than featured film
    /\d{4}-\d{4}/.match(node.at('span').text) ||
      /Series|Episode|Video|Documentary|Movie|Special|Short|Game|Unknown/.match(node.at('span').text)
  end.map do |node|
    imdb_id = node.at("a[href^='/title/tt']")['href'].parse_imdb_id
    title   = node.at('a').text.strip
    year    = node.at('span').text.parse_year

    [imdb_id, title, year]
  end.map do |values|
    Spotlite::Movie.new(*values)
  end
end

#release_dateObject

Returns original release date as a date



307
308
309
# File 'lib/spotlite/movie.rb', line 307

def release_date
  release_dates.first[:date] rescue nil
end

#release_datesObject

Returns a list of regions and corresponding release dates as an array of hashes with keys: region code (string), region name (string), date (date), and comment (string) If day is unknown, 1st day of month is assigned If day and month are unknown, 1st of January is assigned



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/spotlite/movie.rb', line 289

def release_dates
  array = []
  table = release_info.at('#release_dates')
  table.css('tr').map do |row|
    cells = row.css('td')
    code = cells.first.at('a')['href'].clean_href.split('=').last.downcase rescue nil
    region = cells.first.at('a').text rescue nil
    date = cells.at('.release_date').text.strip.parse_date
    comment = cells.last.text.strip.clean_release_comment
    comment = nil if comment.empty?

    array << { :code => code, :region => region, :date => date, :comment => comment }
  end unless table.nil?

  array
end

#runtimeObject

Returns runtime (length) in minutes as an integer



145
146
147
# File 'lib/spotlite/movie.rb', line 145

def runtime
  details.at("div.subtext time[itemprop='duration']")['datetime'].gsub(/[^\d+]/, '').to_i rescue nil
end

#starsObject

Returns a list of starred actors as an array of Spotlite::Person objects



216
217
218
219
220
221
222
223
224
225
# File 'lib/spotlite/movie.rb', line 216

def stars
  details.css("div.plot_summary_wrapper span[itemprop='actors'] a[href^='/name/nm']").map do |node|
    imdb_id = node['href'].parse_imdb_id
    name = node.text.strip

    [imdb_id, name]
  end.map do |values|
    Spotlite::Person.new(*values)
  end
end

#storylineObject

Returns storyline as a string. Often is the same as description



103
104
105
# File 'lib/spotlite/movie.rb', line 103

def storyline
  details.at("#titleStoryLine div[itemprop='description'] p").text.strip.clean_description rescue nil
end

#summariesObject

Returns a list of plot summaries as an array of strings



108
109
110
# File 'lib/spotlite/movie.rb', line 108

def summaries
  plot_summaries.css("p.plotSummary").map { |summary| summary.text.strip }
end

#technicalObject

Returns technical information like film length, aspect ratio, cameras, etc. as a hash of arrays of strings



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/spotlite/movie.rb', line 342

def technical
  hash = {}
  table = technical_info.at_css('#technical_content table') rescue nil

  table.css('tr').map do |row|
    hash[row.css('td').first.text.strip] = row.css('td').last.children.
      map(&:text).
      map(&:strip_whitespace).
      reject(&:empty?).
      reject{|i| i == '|'}.
      slice_before{|i| /^[^\(]/.match i}.
      map{|i| i.join(' ')}
  end unless table.nil?

  hash
end

#titleObject

Returns title as a string



66
67
68
69
# File 'lib/spotlite/movie.rb', line 66

def title
  # strip some non-breaking space at the end
  @title ||= details.at("h1[itemprop='name']").children.first.text.strip.gsub(' ', '') rescue nil
end

#triviaObject

Returns a list of trivia facts as an array of strings



184
185
186
# File 'lib/spotlite/movie.rb', line 184

def trivia
  movie_trivia.css("div.sodatext").map { |node| node.text.strip } rescue []
end

#votesObject

Returns number of votes as an integer



92
93
94
# File 'lib/spotlite/movie.rb', line 92

def votes
  details.at("div.imdbRating span[itemprop='ratingCount']").text.gsub(/[^\d+]/, '').to_i rescue nil
end

#writersObject

Returns a list of writers as an array of Spotlite::Person objects



206
207
208
# File 'lib/spotlite/movie.rb', line 206

def writers
  parse_crew('Writing Credits')
end

#yearObject

Returns year of original release as an integer



77
78
79
# File 'lib/spotlite/movie.rb', line 77

def year
  @year ||= details.at("h1[itemprop='name'] span#titleYear a").text.parse_year rescue nil
end