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