Class: DownloadTV::TorrentAPI

Inherits:
LinkGrabber show all
Defined in:
lib/download_tv/grabbers/torrentapi.rb

Overview

TorrentAPI.org grabber Interfaces with torrentapi.org/apidocs_v2.txt

Constant Summary collapse

TOKEN_EXPIRED_ERROR =
4
TOO_MANY_REQUESTS_ERROR =

1req/2s

5

Instance Attribute Summary

Attributes inherited from LinkGrabber

#url

Instance Method Summary collapse

Methods inherited from LinkGrabber

#agent

Constructor Details

#initializeTorrentAPI

Returns a new instance of TorrentAPI.



11
12
13
14
15
16
17
# File 'lib/download_tv/grabbers/torrentapi.rb', line 11

def initialize
  super('https://torrentapi.org/pubapi_v2.php?'\
        'mode=search&search_string=%s&token=%s&'\
        'app_id=DownloadTV&sort=seeders')
  @wait = 0.5
  @token = nil
end

Instance Method Details



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/download_tv/grabbers/torrentapi.rb', line 53

def get_links(show)
  renew_token if @token.nil?

  search = format(@url, show, @token)

  obj = request_and_parse(search)

  if obj['error_code'] == TOKEN_EXPIRED_ERROR
    renew_token
    search = format(@url, show, @token)
    obj = request_and_parse(search)
  end

  until obj['error_code'] != TOO_MANY_REQUESTS_ERROR && (obj['rate_limit'].nil? || obj['rate_limit'] == false)
    sleep(@wait)
    obj = request_and_parse(search)
  end

  raise NoTorrentsError if obj['error']

  names = obj['torrent_results'].collect { |i| i['filename'] }
  links = obj['torrent_results'].collect { |i| i['download'] }

  names.zip(links)
rescue Mechanize::ResponseCodeError => e
  if e.response_code == '429'
    sleep(@wait)
    retry
  end
end

#online?Boolean

Specific implementation for TorrentAPI (requires token)

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/download_tv/grabbers/torrentapi.rb', line 21

def online?
  renew_token
  true
rescue Mechanize::ResponseCodeError => e
  if e.response_code == '429'
    sleep(@wait)
    retry
  end
  false
rescue Net::HTTP::Persistent::Error
  false
end

#renew_tokenObject

Connects to Torrentapi.org and requests a token, returning it Tokens automatically expire every 15 minutes



45
46
47
48
49
50
51
# File 'lib/download_tv/grabbers/torrentapi.rb', line 45

def renew_token
  obj = request_and_parse('https://torrentapi.org/pubapi_v2'\
                          '.php?get_token=get_token&app_id='\
                          'DownloadTV')

  @token = obj['token']
end

#request_and_parse(url) ⇒ Object

Makes a get request tp the given url. Returns the JSON response parsed into a hash



37
38
39
40
# File 'lib/download_tv/grabbers/torrentapi.rb', line 37

def request_and_parse(url)
  page = agent.get(url).content
  JSON.parse(page)
end