4 Url = Struct.new("Url", :channel, :nick, :time, :url)
5 TITLE_RE = /<\s*title\s*>(.+)<\s*\/title\s*>/im
7 class UrlPlugin < Plugin
8 BotConfig.register BotConfigIntegerValue.new('url.max_urls',
9 :default => 100, :validate => Proc.new{|v| v > 0},
10 :desc => "Maximum number of urls to store. New urls replace oldest ones.")
11 BotConfig.register BotConfigBooleanValue.new('url.say_titles',
13 :desc => "Get the title of any links pasted to the channel and display it (Also, tells if the link is broken)")
17 @registry.set_default(Array.new)
20 def help(plugin, topic="")
21 "urls [<max>=4] => list <max> last urls mentioned in current channel, urls search [<max>=4] <regexp> => search for matching urls. In a private message, you must specify the channel to query, eg. urls <channel> [max], urls search <channel> [max] <regexp>"
24 def get_title_from_html(pagedata)
25 return unless TITLE_RE.match(pagedata)
26 title = $1.strip.gsub(/\s*\n+\s*/, " ")
27 title = title[0..255] if title.length > 255
31 def get_title_for_url(uri_str)
32 # This god-awful mess is what the ruby http library has reduced me to.
33 # Python's is so much nicer. :~(
35 puts "+ Getting #{uri_str}"
36 url = URI.parse(uri_str)
37 return if url.scheme !~ /https?/
39 puts "+ connecting to #{url.host}:#{url.port}"
40 title = Net::HTTP.start(url.host, url.port) do |http|
41 url.path = '/' if url.path == ''
42 head = http.request_head(url.path)
44 when Net::HTTPRedirection then
45 # call self recursively if this is a redirect
46 redirect_to = head['location']
47 puts "+ redirect location: #{redirect_to}"
48 absolute_uris = URI.extract redirect_to
49 raise "wtf! redirect = #{redirect_to}" if absolute_uris.size > 1
50 if absolute_uris.size == 1
51 url = URI.parse absolute_uris[0]
53 url.path = redirect_to
55 puts "+ whee, redirect to #{url.to_s}!"
56 title = get_title_for_url(url.to_s)
57 when Net::HTTPSuccess then
58 if head['content-type'] =~ /^text\//
60 # retrieve the title from the page
61 puts "+ getting #{url.path}"
62 response = http.request_get(url.path)
63 return get_title_from_html(response.body)
65 # content isn't 'text/*'... display info about the file.
66 size = head['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2')
67 #lastmod = head['last-modified']
68 return "[Link Info] type: #{head['content-type']}#{size ? ", size: #{size} bytes" : ""}"
70 when Net::HTTPClientError then
71 return "[Title] Error getting link (#{response.code} - #{response.message})"
72 when Net::HTTPServerError then
73 return "[Title] Error getting link (#{response.code} - #{response.message})"
76 rescue SocketError => e
77 return "[Title] Error connecting to site (#{e.message})"
81 return unless m.kind_of?(PrivMessage)
83 # TODO support multiple urls in one line
84 if m.message =~ /(f|ht)tps?:\/\//
85 if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
87 list = @registry[m.target]
89 if @bot.config['url.say_titles']
90 debug "Getting title for #{urlstr}..."
91 title = get_title_for_url urlstr
96 debug "Title not found!"
100 # check to see if this url is already listed
101 return if list.find {|u| u.url == urlstr }
103 url = Url.new(m.target, m.sourcenick, Time.new, urlstr)
104 debug "#{list.length} urls so far"
105 if list.length > @bot.config['url.max_urls']
108 debug "storing url #{url.url}"
110 debug "#{list.length} urls now"
111 @registry[m.target] = list
117 channel = params[:channel] ? params[:channel] : m.target
118 max = params[:limit].to_i
121 list = @registry[channel]
123 m.reply "no urls seen yet for channel #{channel}"
125 list[0..(max-1)].each do |url|
126 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
131 def search(m, params)
132 channel = params[:channel] ? params[:channel] : m.target
133 max = params[:limit].to_i
134 string = params[:string]
137 regex = Regexp.new(string)
138 list = @registry[channel].find_all {|url|
139 regex.match(url.url) || regex.match(url.nick)
142 m.reply "no matches for channel #{channel}"
144 list[0..(max-1)].each do |url|
145 m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
150 plugin = UrlPlugin.new
151 plugin.map 'urls search :channel :limit :string', :action => 'search',
152 :defaults => {:limit => 4},
153 :requirements => {:limit => /^\d+$/},
155 plugin.map 'urls search :limit :string', :action => 'search',
156 :defaults => {:limit => 4},
157 :requirements => {:limit => /^\d+$/},
159 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
160 :requirements => {:limit => /^\d+$/},
162 plugin.map 'urls :limit', :defaults => {:limit => 4},
163 :requirements => {:limit => /^\d+$/},