Skip to content

Instantly share code, notes, and snippets.

@agarie
Last active July 1, 2022 15:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agarie/5386009 to your computer and use it in GitHub Desktop.
Save agarie/5386009 to your computer and use it in GitHub Desktop.
Utility to download torrent files from tokyotosho.info. It uses a similar heuristic to my own when looking for torrents, but could use some improvements.
#!/usr/bin/env ruby -w
require 'open-uri'
require 'uri'
require 'nokogiri'
DEFAULT_DIR = "/Users/carlosagarie/torrents"
CATEGORY = 1 # Anime.
# Regular expressions and constants for extraction.
RELEVANT_ENTRIES = "table.listing > tr.category_#{CATEGORY}"
MIME_TYPE = "application/x-bittorrent"
SIZE_RE = /Size:\s*([\d.]+)(?:K|M|G)B/
STATS_RE = /^S:\s*(\d+)\s*L:\s*(\d+).*/
# Class used to hold torrents.
Torrent = Struct.new(:name, :link, :size, :seeds, :leechers) do
# Similar to the heuristics I use when looking for a torrent.
def <=>(other)
if self.seeds > 10 || other.seeds > 10
other.seeds <=> self.seeds
else
other.leechers <=> self.leechers
end
end
def to_s
puts name
puts "Size: #{size} | Seeds: #{seeds} | Leechers: #{leechers}"
puts link
end
end
def address(terms, type = CATEGORY)
base_url = "http://tokyotosho.info/search.php?size_min=&size_max=&username="
"#{base_url}&terms=#{terms.split(' ').join('+')}&type=#{type}"
end
url = address(ARGV[0])
page = Nokogiri::HTML(open(url))
# Get the torrent URLs from the main page. Yeah, tokyotosho.info HTML sucks.
results = []
page.css(RELEVANT_ENTRIES).each_slice(2) do |e|
torrent = Torrent.new
links = e[0].css('a').select { |l| l["type"] == MIME_TYPE }
torrent.name = links[0].content
torrent.link = links[0]["href"]
torrent.size = e[1].css('td.desc-bot')[0].content.match(SIZE_RE)[1]
e[1].css('td.stats')[0].content.match(STATS_RE) do |m|
torrent.seeds = m[1].to_i
torrent.leechers = m[2].to_i
end
results << torrent
end
# Download the "best" torrent.
torrent = results.sort.shift
filename = File.join(DEFAULT_DIR, torrent.name + '.torrent')
File.open(filename, 'wb') do |f|
f << open(torrent.link).read
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment