]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/url.rb
lastfm plugin: perfectionism run
[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         title = get_title_from_html(body)
60         if @bot.config['url.first_par']
61           first_par = Utils.ircify_first_html_par(body, :strip => title)
62           extra << ", #{Bold}text#{Bold}: #{first_par}" unless first_par.empty?
63           return "#{Bold}title#{Bold}: #{title}#{extra}" if title
64         else
65           return "#{Bold}title#{Bold}: #{title}" if title
66         end
67
68         # if nothing was found, provide more basic info
69       end
70
71       debug response.to_hash.inspect
72       unless @bot.config['url.titles_only']
73         # content doesn't have title, just display info.
74         size = response['content-length'].gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') rescue nil
75         if response.code == '206'
76           if response['content-range'] =~ /bytes\s*[^\/]+\/(\d+)/
77             size = $1.to_s.reverse.scan(/\d{1,3}/).join(',').reverse
78           end
79         end
80         size = size ? ", #{Bold}size#{Bold}: #{size} bytes" : ""
81         return "#{Bold}type#{Bold}: #{response['content-type']}#{size}#{extra}"
82       end
83     rescue Exception => e
84       error e.inspect
85       debug e.backtrace.join("\n")
86       return "Error connecting to site (#{e.message})"
87     end
88   end
89
90   def listen(m)
91     return unless m.kind_of?(PrivMessage)
92     return if m.address?
93     # TODO support multiple urls in one line
94     if m.message =~ /(f|ht)tps?:\/\//
95       if m.message =~ /((f|ht)tps?:\/\/.*?)(?:\s+|$)/
96         urlstr = $1
97         list = @registry[m.target]
98
99         if @bot.config['url.display_link_info']
100           Thread.start do
101             debug "Getting title for #{urlstr}..."
102             begin
103               title = get_title_for_url urlstr
104               if title
105                 m.reply "#{LINK_INFO} #{title}", :overlong => :truncate
106                 debug "Title found!"
107               else
108                 debug "Title not found!"
109               end
110             rescue => e
111               debug "Failed: #{e}"
112             end
113           end
114         end
115
116         # check to see if this url is already listed
117         return if list.find {|u| u.url == urlstr }
118
119         url = Url.new(m.target, m.sourcenick, Time.new, urlstr)
120         debug "#{list.length} urls so far"
121         if list.length > @bot.config['url.max_urls']
122           list.pop
123         end
124         debug "storing url #{url.url}"
125         list.unshift url
126         debug "#{list.length} urls now"
127         @registry[m.target] = list
128       end
129     end
130   end
131
132   def urls(m, params)
133     channel = params[:channel] ? params[:channel] : m.target
134     max = params[:limit].to_i
135     max = 10 if max > 10
136     max = 1 if max < 1
137     list = @registry[channel]
138     if list.empty?
139       m.reply "no urls seen yet for channel #{channel}"
140     else
141       list[0..(max-1)].each do |url|
142         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
143       end
144     end
145   end
146
147   def search(m, params)
148     channel = params[:channel] ? params[:channel] : m.target
149     max = params[:limit].to_i
150     string = params[:string]
151     max = 10 if max > 10
152     max = 1 if max < 1
153     regex = Regexp.new(string, Regexp::IGNORECASE)
154     list = @registry[channel].find_all {|url|
155       regex.match(url.url) || regex.match(url.nick)
156     }
157     if list.empty?
158       m.reply "no matches for channel #{channel}"
159     else
160       list[0..(max-1)].each do |url|
161         m.reply "[#{url.time.strftime('%Y/%m/%d %H:%M:%S')}] <#{url.nick}> #{url.url}"
162       end
163     end
164   end
165 end
166 plugin = UrlPlugin.new
167 plugin.map 'urls search :channel :limit :string', :action => 'search',
168                           :defaults => {:limit => 4},
169                           :requirements => {:limit => /^\d+$/},
170                           :public => false
171 plugin.map 'urls search :limit :string', :action => 'search',
172                           :defaults => {:limit => 4},
173                           :requirements => {:limit => /^\d+$/},
174                           :private => false
175 plugin.map 'urls :channel :limit', :defaults => {:limit => 4},
176                           :requirements => {:limit => /^\d+$/},
177                           :public => false
178 plugin.map 'urls :limit', :defaults => {:limit => 4},
179                           :requirements => {:limit => /^\d+$/},
180                           :private => false