Class: IRC::Server::Modules::TinyURL

Inherits:
IRC::Server::Module show all
Defined in:
lib/failirc/server/modules/TinyURL.rb

Instance Attribute Summary

Attributes inherited from IRC::Server::Module

#server

Instance Method Summary collapse

Methods inherited from IRC::Server::Module

#finalize

Constructor Details

#initialize(server) ⇒ TinyURL

Returns a new instance of TinyURL.



34
35
36
37
38
39
40
41
42
# File 'lib/failirc/server/modules/TinyURL.rb', line 34

def initialize (server)
    @events = {
        :custom => {
            :message => Event::Callback.new(self.method(:tinyurl), -100),
        }
    }

    super(server)
end

Instance Method Details

#rehashObject



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/failirc/server/modules/TinyURL.rb', line 44

def rehash
    if tmp = @server.config.elements['config/modules/module[@name="TinyURL"]/length']
        @length = tmp.text.to_i
    else
        @length = 42
    end

    if tmp = @server.config.elements['config/modules/module[@name="TinyURL"]/timeout']
        @timeout = tmp.text.to_i
    else
        @timeout = 5
    end
end

#tinyurl(chain, fromRef, toRef, message, level = nil) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/failirc/server/modules/TinyURL.rb', line 58

def tinyurl (chain, fromRef, toRef, message, level=nil)
    if chain != :input
        return
    end

    from = fromRef.value
    to   = toRef.value

    URI.extract(message).each {|uri|
        if uri.length <= @length
            next
        end

        if tiny = tinyurlify(uri) rescue nil
            message.gsub!(/#{Regexp.escape(uri)}/, tiny)
        end
    }
end

#tinyurlify(url) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/failirc/server/modules/TinyURL.rb', line 77

def tinyurlify (url)
    begin
        content = timeout @timeout do
            Net::HTTP.post_form(URI.parse('http://tinyurl.com/create.php'), { 'url' => url }).body
        end
        
        match = content.match('<blockquote><b>(http://tinyurl.com/\w+)</b>')

        if match
            return match[1]
        end
    rescue Timeout::Error
        return nil
    end
end