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]"
9 OUR_UNSAFE = Regexp.new("[^#{URI::PATTERN::UNRESERVED}#{URI::PATTERN::RESERVED}%# ]", false, 'N')
11 BotConfig.register BotConfigIntegerValue.new('url.max_urls',
12 :default => 100, :validate => Proc.new{|v| v > 0},
13 :desc => "Maximum number of urls to store. New urls replace oldest ones.")
14 BotConfig.register BotConfigBooleanValue.new('url.display_link_info',
16 :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)")
17 BotConfig.register BotConfigBooleanValue.new('url.titles_only',
19 :desc => "Only show info for links that have <title> tags (in other words, don't display info for jpegs, mpegs, etc.)")
20 BotConfig.register BotConfigBooleanValue.new('url.first_par',
22 :desc => "Also try to get the first paragraph of a web page")
23 BotConfig.register BotConfigBooleanValue.new('url.info_on_list',
25 :desc => "Show link info when listing/searching for urls")
30 @registry.set_default(Array.new)
33 def help(plugin, topic="")
34 "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>"
37 def get_title_from_html(pagedata)
38 return unless TITLE_RE.match(pagedata)
42 def get_title_for_url(uri_str, nick = nil, channel = nil)
44 url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
45 return if url.scheme !~ /https?/
48 logopts[:nick] = nick if nick
49 logopts[:channel] = channel if channel
55 debug "+ getting #{url.request_uri}"
56 @bot.httputil.get_response(url) { |resp|
62 if resp['content-type'] =~ /^text\/|(?:x|ht)ml/
63 # The page is text or HTML, so we can try finding a title and, if
64 # requested, the first par.
66 # We act differently depending on whether we want the first par or
67 # not: in the first case we download the initial part and the parse
68 # it; in the second case we only download as much as we need to find
71 if @bot.config['url.first_par']
72 partial = resp.partial_body(@bot.config['http.info_bytes'])
73 logopts[:title] = title = get_title_from_html(partial)
74 if url.fragment and not url.fragment.empty?
75 fragreg = /.*?<a\s+[^>]*name=["']?#{url.fragment}["']?.*?>/im
76 partial.sub!(fragreg,'')
78 first_par = Utils.ircify_first_html_par(partial, :strip => title)
79 unless first_par.empty?
80 logopts[:extra] = first_par
81 extra << ", #{Bold}text#{Bold}: #{first_par}"
83 call_event(:url_added, url.to_s, logopts)
84 return "#{Bold}title#{Bold}: #{title}#{extra}" if title
86 resp.partial_body(@bot.config['http.info_bytes']) { |part|
87 logopts[:title] = title = get_title_from_html(part)
88 call_event(:url_added, url.to_s, logopts)
89 return "#{Bold}title#{Bold}: #{title}" if title
92 # if nothing was found, provide more basic info, as for non-html pages
97 enc = resp['content-encoding']
98 logopts[:extra] = String.new
99 logopts[:extra] << "Content Type: #{resp['content-type']}"
101 logopts[:extra] << ", encoding: #{enc}"
102 extra << ", #{Bold}encoding#{Bold}: #{enc}"
105 unless @bot.config['url.titles_only']
106 # content doesn't have title, just display info.
107 size = resp['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
109 logopts[:extra] << ", size: #{size} bytes"
110 size = ", #{Bold}size#{Bold}: #{size} bytes"
112 call_event(:url_added, url.to_s, logopts)
113 return "#{Bold}type#{Bold}: #{resp['content-type']}#{size}#{extra}"
115 call_event(:url_added, url.to_s, logopts)
117 raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
121 rescue Exception => e
127 raise "connecting to site/processing information (#{e.message})"
133 return unless m.kind_of?(PrivMessage)
136 escaped = URI.escape(m.message, OUR_UNSAFE)
137 urls = URI.extract(escaped)
138 return if urls.empty?
139 debug "found urls #{urls.inspect}"
140 list = @registry[m.target]
142 debug "working on #{urlstr}"
143 next unless urlstr =~ /^https?:/
145 if @bot.config['url.display_link_info']
147 debug "Getting title for #{urlstr}..."
149 title = get_title_for_url urlstr, m.source.nick, m.channel
151 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
154 debug "Title not found!"
157 m.reply "Error #{e.message}"
162 # check to see if this url is already listed
163 next if list.find {|u| u.url == urlstr }
165 url = Url.new(m.target, m.sourcenick, Time.new, urlstr, title)
166 debug "#{list.length} urls so far"
167 if list.length > @bot.config['url.max_urls']
170 debug "storing url #{url.url}"
172 debug "#{list.length} urls now"
174 @registry[m.target] = list
177 def reply_urls(opts={})
180 channel = opts[:channel]
182 return unless list and max and m
183 list[0..(max-1)].each do |url|
184 disp = "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
185 if @bot.config['url.info_on_list']
186 title = url.info || get_title_for_url(url.url, url.nick, channel) rescue nil
187 # If the url info was missing and we now have some, try to upgrade it
188 if channel and title and not url.info
189 ll = @registry[channel]
191 if el = ll.find { |u| u.url == url.url }
193 @registry[channel] = ll
196 disp << " --> #{title}" if title
198 m.reply disp, :overlong => :truncate
203 channel = params[:channel] ? params[:channel] : m.target
204 max = params[:limit].to_i
207 list = @registry[channel]
209 m.reply "no urls seen yet for channel #{channel}"
211 reply_urls :msg => m, :channel => channel, :list => list, :max => max
215 def search(m, params)
216 channel = params[:channel] ? params[:channel] : m.target
217 max = params[:limit].to_i
218 string = params[:string]
221 regex = Regexp.new(string, Regexp::IGNORECASE)
222 list = @registry[channel].find_all {|url|
223 regex.match(url.url) || regex.match(url.nick) ||
224 (@bot.config['url.info_on_list'] && regex.match(url.info))
227 m.reply "no matches for channel #{channel}"
229 reply_urls :msg => m, :channel => channel, :list => list, :max => max
234 plugin = UrlPlugin.new
235 plugin.map 'urls search :channel :limit :string', :action => 'search',
236 :defaults => {:limit => 4},
237 :requirements => {:limit => /^\d+$/},
239 plugin.map 'urls search :limit :string', :action => 'search',
240 :defaults => {:limit => 4},
241 :requirements => {:limit => /^\d+$/},
243 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
244 :requirements => {:limit => /^\d+$/},
246 plugin.map 'urls :limit', :defaults => {:limit => 4},
247 :requirements => {:limit => /^\d+$/},