]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
95ccb5d95dcdc2f8504efc70066cab10d3abf04d
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / url.rb
1 require 'uri'
2
3 Url = Struct.new("Url", :channel, :nick, :time, :url)
4 TITLE_RE = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
5 LINK_INFO = "[Link Info]"
6
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.display_link_info',
12     :default => false,
13     :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)")
14   BotConfig.register BotConfigBooleanValue.new('url.titles_only',
15     :default => false,
16     :desc => "Only show info for links that have <title> tags (in other words, don't display info for jpegs, mpegs, etc.)")
17   BotConfig.register BotConfigBooleanValue.new('url.first_par',
18     :default => false,
19     :desc => "Also try to get the first paragraph of a web page")
20
21   def initialize
22     super
23     @registry.set_default(Array.new)
24   end
25
26   def help(plugin, topic="")
27     "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>"
28   end
29
30   def get_title_from_html(pagedata)
31     return unless TITLE_RE.match(pagedata)
32     $1.ircify_html
33   end
34
35   def get_title_for_url(uri_str)
36
37     url = uri_str.kind_of?(URI) ? uri_str : URI.parse(uri_str)
38     return if url.scheme !~ /https?/
39
40     title = nil
41
42     begin
43       range = @bot.config['http.info_bytes']
44       response = @bot.httputil.get_response(url, :range => "bytes=0-#{range}")
45       if response.code != "206" && response.code != "200"
46         return "Error getting link (#{response.code} - #{response.message})"
47       end
48       extra = String.new
49
50       if response['content-type'] =~ /^text\//
51
52         body = response.body.slice(0, range)
53         title = String.new
54
55         # since the content is 'text/*' and is small enough to
56         # be a webpage, retrieve the title from the page
57         debug "+ getting #{url.request_uri}"
58
59         # we act differently depending on whether we want the first par or not:
60         # in the first case we download the initial part and the parse it; in the second
61         # case we only download as much as we need to find the title
62         if @bot.config['url.first_par']
63           first_par = Utils.ircify_first_html_par(body)
64           extra << "\n#{LINK_INFO} text: #{first_par}" unless first_par.empty?
65           title = get_title_from_html(body)
66           return "title: #{title}#{extra}" if title
67         else
68           title = get_title_from_html(body)
69           return "title: #{title}" if title
70         end
71
72         # if nothing was found, provide more basic info
73       end
74
75       debug response.to_hash.inspect
76       unless @bot.config['url.titles_only']
77         # content doesn't have title, just display info.
78         size = response['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
79         size = size ? ", size: #{size} bytes" : ""
80         return "type: #{response['content-type']}#{size}#{extra}"
81       end
82     rescue Exception => e
83       error e.inspect
84       debug e.backtrace.join("\n")
85       return "Error connecting to site (#{e.message})"
86     end
87   end
88
89   def listen(m)
90     return unless m.kind_of?(PrivMessage)
91     return if m.address?
92     # TODO support multiple urls in one line
93     if m.message =~ /(f|ht)tps?:\/\//
94       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
95         urlstr = $1
96         list = @registry[m.target]
97
98         if @bot.config['url.display_link_info']
99           Thread.start do
100             debug "Getting title for #{urlstr}..."
101             begin
102               title = get_title_for_url urlstr
103               if title
104                 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
105                 debug "Title found!"
106               else
107                 debug "Title not found!"
108               end
109             rescue => e
110               debug "Failed: #{e}"
111             end
112           end
113         end
114
115         # check to see if this url is already listed
116         return if list.find {|u| u.url == urlstr }
117
118         url = Url.new(m.target, m.sourcenick, Time.new, urlstr)
119         debug "#{list.length} urls so far"
120         if list.length > @bot.config['url.max_urls']
121           list.pop
122         end
123         debug "storing url #{url.url}"
124         list.unshift url
125         debug "#{list.length} urls now"
126         @registry[m.target] = list
127       end
128     end
129   end
130
131   def urls(m, params)
132     channel = params[:channel] ? params[:channel] : m.target
133     max = params[:limit].to_i
134     max = 10 if max > 10
135     max = 1 if max < 1
136     list = @registry[channel]
137     if list.empty?
138       m.reply "no urls seen yet for channel #{channel}"
139     else
140       list[0..(max-1)].each do |url|
141         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
142       end
143     end
144   end
145
146   def search(m, params)
147     channel = params[:channel] ? params[:channel] : m.target
148     max = params[:limit].to_i
149     string = params[:string]
150     max = 10 if max > 10
151     max = 1 if max < 1
152     regex = Regexp.new(string, Regexp::IGNORECASE)
153     list = @registry[channel].find_all {|url|
154       regex.match(url.url) || regex.match(url.nick)
155     }
156     if list.empty?
157       m.reply "no matches for channel #{channel}"
158     else
159       list[0..(max-1)].each do |url|
160         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
161       end
162     end
163   end
164 end
165 plugin = UrlPlugin.new
166 plugin.map 'urls search :channel :limit :string', :action => 'search',
167                           :defaults => {:limit => 4},
168                           :requirements => {:limit => /^\d+$/},
169                           :public => false
170 plugin.map 'urls search :limit :string', :action => 'search',
171                           :defaults => {:limit => 4},
172                           :requirements => {:limit => /^\d+$/},
173                           :private => false
174 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
175                           :requirements => {:limit => /^\d+$/},
176                           :public => false
177 plugin.map 'urls :limit', :defaults => {:limit => 4},
178                           :requirements => {:limit => /^\d+$/},
179                           :private => false