]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
From Chris:
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / url.rb
1 require 'net/http'
2 require 'uri'
3
4 Url = Struct.new("Url", :channel, :nick, :time, :url)
5 TITLE_RE = /<\s*title\s*>(.+)<\s*\/title\s*>/im
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.say_titles',
12     :default => true, 
13     :desc => "Get the title of any links pasted to the channel and display it (Also, tells if the link is broken)")
14   
15   def initialize
16     super
17     @registry.set_default(Array.new)
18   end
19
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>"
22   end
23
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 
28     "[Title] #{title}"
29   end
30
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. :~(
34     
35     puts "+ Getting #{uri_str}"
36     url = URI.parse(uri_str)
37     return if url.scheme !~ /https?/
38     
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)
43       case head
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]
52           else
53             url.path = redirect_to
54           end
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\//
59             # content is '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)
64           else
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" : ""}"
69           end
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})"
74       end
75     end
76   rescue SocketError => e
77     return "[Title] Error connecting to site (#{e.message})"
78   end
79
80   def listen(m)
81     return unless m.kind_of?(PrivMessage)
82     return if m.address?
83     # TODO support multiple urls in one line
84     if m.message =~ /(f|ht)tps?:\/\//
85       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
86         urlstr = $1
87         list = @registry[m.target]
88
89         if @bot.config['url.say_titles']
90           debug "Getting title for #{urlstr}..."
91           title = get_title_for_url urlstr
92           if title
93             m.reply title
94             debug "Title found!"
95           else
96             debug "Title not found!"
97           end        
98         end
99     
100         # check to see if this url is already listed
101         return if list.find {|u| u.url == urlstr }
102         
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']
106           list.pop
107         end
108         debug "storing url #{url.url}"
109         list.unshift url
110         debug "#{list.length} urls now"
111         @registry[m.target] = list
112       end
113     end
114   end
115
116   def urls(m, params)
117     channel = params[:channel] ? params[:channel] : m.target
118     max = params[:limit].to_i
119     max = 10 if max > 10
120     max = 1 if max < 1
121     list = @registry[channel]
122     if list.empty?
123       m.reply "no urls seen yet for channel #{channel}"
124     else
125       list[0..(max-1)].each do |url|
126         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
127       end
128     end
129   end
130
131   def search(m, params)
132     channel = params[:channel] ? params[:channel] : m.target
133     max = params[:limit].to_i
134     string = params[:string]
135     max = 10 if max > 10
136     max = 1 if max < 1
137     regex = Regexp.new(string)
138     list = @registry[channel].find_all {|url|
139       regex.match(url.url) || regex.match(url.nick)
140     }
141     if list.empty?
142       m.reply "no matches for channel #{channel}"
143     else
144       list[0..(max-1)].each do |url|
145         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
146       end
147     end
148   end
149 end
150 plugin = UrlPlugin.new
151 plugin.map 'urls search :channel :limit :string', :action => 'search',
152                           :defaults => {:limit => 4},
153                           :requirements => {:limit => /^\d+$/},
154                           :public => false
155 plugin.map 'urls search :limit :string', :action => 'search',
156                           :defaults => {:limit => 4},
157                           :requirements => {:limit => /^\d+$/},
158                           :private => false
159 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
160                           :requirements => {:limit => /^\d+$/},
161                           :public => false
162 plugin.map 'urls :limit', :defaults => {:limit => 4},
163                           :requirements => {:limit => /^\d+$/},
164                           :private => false
165
166
167
168