4 # :title: ShortURL plugin for rbot
6 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2007 Giuseppe Bilotta
10 # Plugin to handle ShortURL, merges the funcionality of the old rubyurl and tinyurl plugins
11 # Note that it's called ShortenURLs and not ShortURL, to prevent conflicts with
12 # the actual ruby package used
17 class ShortenURLs < Plugin
18 # starting from about shorturl 0.8.4, the WWW module is not defined
19 include WWW rescue nil
21 Config.register Config::ArrayValue.new('shortenurls.services_blacklist',
22 :default => ['rubyurl', 'shorterlink'],
23 :requires_rescan => true,
24 :desc => "List of nonfunctioning shorturl services")
26 attr_accessor :services
29 @blacklist = @bot.config['shortenurls.services_blacklist'].map { |s| s.intern }
30 # Instead of catering for all the services, we only pick the ones with 'link' or 'url' in the name
31 @services = ShortURL.valid_services.select { |service| service.to_s =~ /(?:link|url)/ } - @blacklist
32 if @services.include?(:rubyurl)
33 @services << :shorturl
37 # return a help string when the bot is asked for help on this plugin
38 def help(plugin, topic="")
39 return "shorten urls. syntax: <service> <your long url> => creates a shortened url using the required service (choose between #{@services.join(', ')}). Example: #{@bot.nick}, tinyurl http://some.long.url/wow-this-is/really-long.html"
42 # do the dirty job. This method can be called by other plugins, in which case you
43 # should set the :called param to true
44 def shorten(m, params)
47 m.reply help(m.plugin) unless params[:called]
51 to_uri = URI.parse(url)
52 # We don't accept 'generic' URLs because almost everything gets in there
53 raise URI::InvalidURIError if to_uri.class == URI::Generic
54 rescue URI::InvalidURIError
55 m.reply "#{url} doesn't look like an URL to me ..." unless params[:called]
59 service = (params[:service] || m.plugin).to_sym
60 service = :rubyurl if service == :shorturl
67 raise InvalidService, "#{service} blacklisted" if @blacklist.include?(service)
68 short = ShortURL.shorten(url, service)
69 raise InvalidService, "#{service} returned an empty string for #{url}" unless short and not short.empty?
71 pool = services - tried
73 m.reply "#{service} failed, and I don't know what else to try next" unless params[:called]
76 service = pool.pick_one
77 m.reply "#{tried.last} failed, I'll try #{service} instead" unless params[:called]
82 m.reply "#{url} shortened to #{short}" unless params[:called]
88 # create an instance of the RubyURL class and register it as a plugin
89 plugin = ShortenURLs.new
91 plugin.services.each { |service|
92 plugin.map "#{service} :url", :action => 'shorten'