1 Url = Struct.new("Url", :channel, :nick, :time, :url, :info)
3 class ::UrlLinkError < RuntimeError
6 class UrlPlugin < Plugin
7 TITLE_RE = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
8 LINK_INFO = "[Link Info]"
10 BotConfig.register BotConfigIntegerValue.new('url.max_urls',
11 :default => 100, :validate => Proc.new{|v| v > 0},
12 :desc => "Maximum number of urls to store. New urls replace oldest ones.")
13 BotConfig.register BotConfigBooleanValue.new('url.display_link_info',
15 :desc => "Get the title of any links pasted to the channel and display it (also tells if the link is broken or the site is down)")
16 BotConfig.register BotConfigBooleanValue.new('url.titles_only',
18 :desc => "Only show info for links that have <title> tags (in other words, don't display info for jpegs, mpegs, etc.)")
19 BotConfig.register BotConfigBooleanValue.new('url.first_par',
21 :desc => "Also try to get the first paragraph of a web page")
22 BotConfig.register BotConfigBooleanValue.new('url.info_on_list',
24 :desc => "Show link info when listing/searching for urls")
29 @registry.set_default(Array.new)
32 def help(plugin, topic="")
33 "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>"
36 def get_title_from_html(pagedata)
37 return unless TITLE_RE.match(pagedata)
41 def get_title_for_url(uri_str)
43 url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
44 return if url.scheme !~ /https?/
50 debug "+ getting #{url.request_uri}"
51 @bot.httputil.get_response(url) { |resp|
55 if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
56 # The page is text or HTML, so we can try finding a title and, if
57 # requested, the first par.
59 # We act differently depending on whether we want the first par or
60 # not: in the first case we download the initial part and the parse
61 # it; in the second case we only download as much as we need to find
64 if @bot.config['url.first_par']
65 partial = resp.partial_body(@bot.config['http.info_bytes'])
66 title = get_title_from_html(partial)
67 first_par = Utils.ircify_first_html_par(partial, :strip => title)
68 extra << ", #{Bold}text#{Bold}: #{first_par}" unless first_par.empty?
69 return "#{Bold}title#{Bold}: #{title}#{extra}" if title
71 resp.partial_body(@bot.config['http.info_bytes']) { |part|
72 title = get_title_from_html(part)
73 return "#{Bold}title#{Bold}: #{title}" if title
76 # if nothing was found, provide more basic info, as for non-html pages
79 debug resp.to_hash.inspect
81 enc = resp['content-encoding']
83 extra << ", #{Bold}encoding#{Bold}: #{enc}" if enc
85 unless @bot.config['url.titles_only']
86 # content doesn't have title, just display info.
87 size = resp['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
88 size = size ? ", #{Bold}size#{Bold}: #{size} bytes" : ""
89 return "#{Bold}type#{Bold}: #{resp['content-type']}#{size}#{extra}"
92 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
101 raise "connecting to site/processing information (#{e.message})"
107 return unless m.kind_of?(PrivMessage)
109 # TODO support multiple urls in one line
110 if m.message =~ /(f|ht)tps?:\/\//
111 if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
113 list = @registry[m.target]
116 if @bot.config['url.display_link_info']
118 debug "Getting title for #{urlstr}..."
120 title = get_title_for_url urlstr
122 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
125 debug "Title not found!"
128 m.reply "Error #{e.message}"
133 # check to see if this url is already listed
134 return if list.find {|u| u.url == urlstr }
136 url = Url.new(m.target, m.sourcenick, Time.new, urlstr, title)
137 debug "#{list.length} urls so far"
138 if list.length > @bot.config['url.max_urls']
141 debug "storing url #{url.url}"
143 debug "#{list.length} urls now"
144 @registry[m.target] = list
149 def reply_urls(m, list, max)
150 list[0..(max-1)].each do |url|
151 disp = "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
152 if @bot.config['url.info_on_list']
153 title = url.info || get_title_for_url(url.url) rescue nil
154 if title and not url.info
157 disp << " --> #{title}" if title
159 m.reply disp, :overlong => :truncate
164 channel = params[:channel] ? params[:channel] : m.target
165 max = params[:limit].to_i
168 list = @registry[channel]
170 m.reply "no urls seen yet for channel #{channel}"
172 reply_urls(m, list, max)
176 def search(m, params)
177 channel = params[:channel] ? params[:channel] : m.target
178 max = params[:limit].to_i
179 string = params[:string]
182 regex = Regexp.new(string, Regexp::IGNORECASE)
183 list = @registry[channel].find_all {|url|
184 regex.match(url.url) || regex.match(url.nick)
187 m.reply "no matches for channel #{channel}"
189 reply_urls(m, list, max)
194 plugin = UrlPlugin.new
195 plugin.map 'urls search :channel :limit :string', :action => 'search',
196 :defaults => {:limit => 4},
197 :requirements => {:limit => /^\d+$/},
199 plugin.map 'urls search :limit :string', :action => 'search',
200 :defaults => {:limit => 4},
201 :requirements => {:limit => /^\d+$/},
203 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
204 :requirements => {:limit => /^\d+$/},
206 plugin.map 'urls :limit', :defaults => {:limit => 4},
207 :requirements => {:limit => /^\d+$/},