class DownloadTV::TorrentAPI

Interfaces with torrentapi.org/apidocs_v2.txt<br>TorrentAPI.org grabber
#

def get_links(s)

def get_links(s)
  @token ||= renew_token
  # Format the url
  search = format(@url, s, @token)
  page = @agent.get(search).content
  obj = JSON.parse(page)
  if obj['error_code'] == 4 # Token expired
    renew_token
    search = format(@url, s, @token)
    page = @agent.get(search).content
    obj = JSON.parse(page)
  end
  while obj['error_code'] == 5 # Violate 1req/2s limit
    sleep(@wait)
    page = @agent.get(search).content
    obj = JSON.parse(page)
  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)
end

def initialize

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

def online?

Specific implementation for TorrentAPI (requires token)
#
def online?
  @agent.read_timeout = 2
  @agent.head(format(@url, 'test', 'test'))
  true
rescue Mechanize::ResponseCodeError, Net::HTTP::Persistent::Error
  false
end

def renew_token

Tokens automatically expire every 15 minutes
Connects to Torrentapi.org and requests a token, returning it
#
def renew_token
  page = @agent.get('https://torrentapi.org/pubapi_v2.php?get_token=get_token&app_id=DownloadTV').content
  obj = JSON.parse(page)
  @token = obj['token']
end