This repository has been archived by the owner on Jun 10, 2018. It is now read-only.
/
session.rb
123 lines (101 loc) · 2.64 KB
/
session.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
module Hector
class Session
attr_reader :nickname, :connection, :identity
class << self
def nicknames
sessions.keys
end
def find(nickname)
sessions[normalize(nickname)]
end
def create(nickname, connection, identity)
if find(nickname)
raise NicknameInUse, nickname
else
new(nickname, connection, identity).tap do |session|
sessions[normalize(nickname)] = session
end
end
end
def destroy(nickname)
sessions.delete(normalize(nickname))
end
def normalize(nickname)
if nickname =~ /^\w[\w-]{0,15}$/
nickname.downcase
else
raise ErroneousNickname, nickname
end
end
def reset!
@sessions = nil
end
protected
def sessions
@sessions ||= {}
end
end
def initialize(nickname, connection, identity)
@nickname = nickname
@connection = connection
@identity = identity
end
def receive(request)
@request = request
if respond_to?(request.event_name)
send(request.event_name)
end
ensure
@request = nil
end
def welcome
respond_with("001", nickname, :text => "Welcome to IRC")
respond_with("422", :text => "MOTD File is missing")
end
def on_privmsg
destination, text = request.args.first, request.text
if channel?(destination)
on_channel_privmsg(Channel.find(destination), text)
else
on_session_privmsg(Session.find(destination), text)
end
end
def on_channel_privmsg(channel, text)
if channel.has_session?(self)
channel.broadcast(:privmsg, channel.channel_name, :source => source, :text => text, :except => self)
else
raise CannotSendToChannel, channel.channel_name
end
end
def on_session_privmsg(session, text)
if session
session.respond_with(:privmsg, session.nickname, :source => source, :text => text)
else
raise NoSuchNickOrChannel, session.nickname
end
end
def on_join
Channel.find_or_create(request.args.first).join(self)
end
def on_part
Channel.find(request.args.first).part(self, request.text)
end
def on_quit
connection.close_connection
end
def destroy
self.class.destroy(nickname)
end
def respond_with(*args)
connection.respond_with(*args)
end
def source
"#{nickname}!#{identity.username}@hector"
end
protected
attr_reader :request
def channel?(destination)
destination =~ /^#/
end
end
end