1 define_structure :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|
57 if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
58 # The page is text or HTML, so we can try finding a title and, if
59 # requested, the first par.
61 # We act differently depending on whether we want the first par or
62 # not: in the first case we download the initial part and the parse
63 # it; in the second case we only download as much as we need to find
66 if @bot.config['url.first_par']
67 partial = resp.partial_body(@bot.config['http.info_bytes'])
68 title = get_title_from_html(partial)
69 first_par = Utils.ircify_first_html_par(partial, :strip => title)
70 extra << ", #{Bold}text#{Bold}: #{first_par}" unless first_par.empty?
71 return "#{Bold}title#{Bold}: #{title}#{extra}" if title
73 resp.partial_body(@bot.config['http.info_bytes']) { |part|
74 title = get_title_from_html(part)
75 return "#{Bold}title#{Bold}: #{title}" if title
78 # if nothing was found, provide more basic info, as for non-html pages
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})"
102 raise "connecting to site/processing information (#{e.message})"
108 return unless m.kind_of?(PrivMessage)
110 # TODO support multiple urls in one line
111 if m.message =~ /(f|ht)tps?:\/\//
112 if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
114 list = @registry[m.target]
117 if @bot.config['url.display_link_info']
119 debug "Getting title for #{urlstr}..."
121 title = get_title_for_url urlstr
123 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
126 debug "Title not found!"
129 m.reply "Error #{e.message}"
134 # check to see if this url is already listed
135 return if list.find {|u| u.url == urlstr }
137 url = Url.new(m.target, m.sourcenick, Time.new, urlstr, title)
138 debug "#{list.length} urls so far"
139 if list.length > @bot.config['url.max_urls']
142 debug "storing url #{url.url}"
144 debug "#{list.length} urls now"
145 @registry[m.target] = list
150 def reply_urls(opts={})
153 channel = opts[:channel]
155 return unless list and max and m
156 list[0..(max-1)].each do |url|
157 disp = "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
158 if @bot.config['url.info_on_list']
159 title = url.info || get_title_for_url(url.url) rescue nil
160 # If the url info was missing and we now have some, try to upgrade it
161 if channel and title and not url.info
162 ll = @registry[channel]
164 if el = ll.find { |u| u.url == url.url }
166 @registry[channel] = ll
169 disp << " --> #{title}" if title
171 m.reply disp, :overlong => :truncate
176 channel = params[:channel] ? params[:channel] : m.target
177 max = params[:limit].to_i
180 list = @registry[channel]
182 m.reply "no urls seen yet for channel #{channel}"
184 reply_urls :msg => m, :channel => channel, :list => list, :max => max
188 def search(m, params)
189 channel = params[:channel] ? params[:channel] : m.target
190 max = params[:limit].to_i
191 string = params[:string]
194 regex = Regexp.new(string, Regexp::IGNORECASE)
195 list = @registry[channel].find_all {|url|
196 regex.match(url.url) || regex.match(url.nick) ||
197 (@bot.config['url.info_on_list'] && regex.match(url.info))
200 m.reply "no matches for channel #{channel}"
202 reply_urls :msg => m, :channel => channel, :list => list, :max => max
207 plugin = UrlPlugin.new
208 plugin.map 'urls search :channel :limit :string', :action => 'search',
209 :defaults => {:limit => 4},
210 :requirements => {:limit => /^\d+$/},
212 plugin.map 'urls search :limit :string', :action => 'search',
213 :defaults => {:limit => 4},
214 :requirements => {:limit => /^\d+$/},
216 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
217 :requirements => {:limit => /^\d+$/},
219 plugin.map 'urls :limit', :defaults => {:limit => 4},
220 :requirements => {:limit => /^\d+$/},