heimdall/proto.rb

122 lines
2.3 KiB
Ruby

UIDS = {}
module Heimdall
VERSION = "0.1 alpha"
attr_reader :VERSION
class ProtocolError < StandardError
end
class UID
def initialize
@UID_prefix = "abstract" if not @UID_prefix
id = (1..32).map { |x| (rand()*10).floor }.join
while UIDS.has_key? id do
id = (1..32).map { |x| (rand()*10).floor }.join
end
UIDS[@UID_prefix+id] = self
@UID = id
end
attr_reader :UID
end
class UserCache
def initialize
@users = {}
end
def add(user)
@users[user.protoid] = user
end
def get(protoid)
raise ProtocolError, "user not found" if not @users[protoid]
return @users[protoid]
end
def delete(protoid)
@users.delete protoid
end
end
class User < UID
def initialize(data)
@username = data["username"]
@protoid = data["protocol_id"]
@UID_prefix = "user"
@direct = DirectChannel.new
super()
end
attr_reader :username
attr_reader :protoid
attr_reader :direct
end
class Channel < UID
def initialize
@UID_prefix = "channel"
@messages = MsgStack.new
@read = 0
super()
end
def send(msg)
@messages.push(msg)
@read = @read+1
end
def get(n = 1)
raise Heimdall::ProtocolError, "Invalid number of messages" if n < 0
return @messages.pull(n)
end
def read()
messages = @messages.pull(@read)
@read = 0
return messages
end
end
class DirectChannel < Channel
def initialize
@UID_prefix = "dchannel"
super()
end
end
class RoomChannel < Channel
def initialize
@UID_prefix = "schannel"
super()
end
end
class Message < UID
def initialize(data)
@content = data["content"]
@from = data["from"]
@to = data["to"]
@UID_prefix = "message"
super()
end
def to_struct
return {
"content" => @content,
"from" => @from,
"to" => @to
}
end
attr_reader :content
attr_reader :from
attr_reader :to
end
class MsgStack < UID
def initialize
@UID_prefix = "msgstack"
@messages = []
super()
end
def push(msg)
@messages.append(msg)
end
def pull(n)
@messages.last n
end
end
end