1
0
mirror of https://github.com/ShadowNinja/LuaIRC.git synced 2025-07-20 16:40:26 +02:00

3 Commits

11 changed files with 302 additions and 653 deletions

3
.gitignore vendored
View File

@ -1,3 +0,0 @@
/gh-pages/
*~

View File

@ -1,15 +0,0 @@
language: lua
notifications:
email: false
env:
global:
- secure: "kFhU+DZjhq/KbDt0DIDWnlskXMa12miNelmhhy30fQGgVIdiibDGKMNGyLahWp8CnPu1DARb5AZWK2TDfARdnURT2pgcsG83M7bYIY6cR647BWjL7oAhJ6CYEzTWJTBjeUjpN/o4vIgfXSDR0c7vboDi7Xz8ilfrBujPL2Oi/og="
install:
- sudo apt-get -y update
- sudo apt-get -y install lua5.1 luadoc
script:
- ./push-luadoc.sh

View File

@ -1,8 +1,7 @@
[![Build Status](https://travis-ci.org/JakobOvrum/LuaIRC.svg?branch=master)](https://travis-ci.org/JakobOvrum/LuaIRC)
LuaIRC
============
IRC client library for Lua.
IRC library for Lua.
Dependencies
-------------

View File

@ -1,15 +1,15 @@
local msgs = require("irc.messages")
local table = table
local assert = assert
local select = select
local meta = {}
module "irc"
local meta = _META
function meta:send(msg, ...)
if type(msg) == "table" then
msg = msg:toRFC1459()
else
if select("#", ...) > 0 then
msg = msg:format(...)
end
end
self:invoke("OnSend", msg)
local bytes, err = self.socket:send(msg .. "\r\n")
@ -21,10 +21,6 @@ function meta:send(msg, ...)
end
end
function meta:queue(msg)
table.insert(self.messageQueue, msg)
end
local function verify(str, errLevel)
if str:find("^:") or str:find("%s%z") then
error(("malformed parameter '%s' to irc command"):format(str), errLevel)
@ -36,26 +32,28 @@ end
function meta:sendChat(target, msg)
-- Split the message into segments if it includes newlines.
for line in msg:gmatch("([^\r\n]+)") do
self:queue(msgs.privmsg(verify(target, 3), line))
self:send("PRIVMSG %s :%s", verify(target, 3), line)
end
end
function meta:sendNotice(target, msg)
-- Split the message into segments if it includes newlines.
for line in msg:gmatch("([^\r\n]+)") do
self:queue(msgs.notice(verify(target, 3), line))
self:send("NOTICE %s :%s", verify(target, 3), line)
end
end
function meta:join(channel, key)
self:queue(msgs.join(
verify(channel, 3),
key and verify(key, 3) or nil))
if key then
self:send("JOIN %s :%s", verify(channel, 3), verify(key, 3))
else
self:send("JOIN %s", verify(channel, 3))
end
end
function meta:part(channel, reason)
function meta:part(channel)
channel = verify(channel, 3)
self:queue(msgs.part(channel, reason))
self:send("PART %s", channel)
if self.track_users then
self.channels[channel] = nil
end
@ -85,8 +83,5 @@ function meta:setMode(t)
mode = table.concat{mode, "-", verify(rem, 3)}
end
self:queue(msgs.mode(verify(target, 3), mode))
self:send("MODE %s %s", verify(target, 3), mode)
end
return meta

View File

@ -1,7 +1,7 @@
--- LuaIRC is a low-level IRC library for Lua.
-- All functions raise Lua exceptions on error.
--
-- Use <code>new</code> to create a new Connection object.<br/>
-- Use <code>new</code> to create a new IRC object.<br/>
-- Example:<br/><br/>
--<code>
--require "irc"<br/>
@ -24,12 +24,11 @@
module "irc"
--- Create a new Connection object. Use <code>irc:connect</code> to connect to a server.
--- Create a new IRC object. Use <code>irc:connect</code> to connect to a server.
-- @param user Table with fields <code>nick</code>, <code>username</code> and <code>realname</code>.
-- The <code>nick</code> field is required.
--
-- @return Returns a new Connection object.
-- @see Connection
-- @return Returns a new <code>irc</code> object.
function new(user)
--- Hook a function to an event.
@ -47,10 +46,10 @@ function irc:unhook(name, id)
--- Connect <code>irc</code> to an IRC server.
-- @param host Host address.
-- @param port Server port. [default 6667]
function irc:connect(host, port)
function irc:connect(server, port)
-- @param table Table of connection details
-- @see ConnectOptions
-- @see Connection
function irc:connect(table)
--- Disconnect <code>irc</code> from the server.
@ -71,28 +70,24 @@ function irc:whois(nick)
-- @param channel Channel to query.
function irc:topic(channel)
--- Send a IRC message to the server.
-- @param msg Message or raw line to send, excluding newline characters.
--- Send a raw line of IRC to the server.
-- @param msg Line to be sent, excluding newline characters.
-- @param ... Format parameters for <code>msg</code>, with <code>string.format</code> semantics. [optional]
function irc:send(msg, ...)
--- Queue Message to be sent to the server.
-- @param msg Message to be sent.
function irc:queue(msg)
--- Send a message to a channel or user.
-- @param target Nick or channel to send to.
-- @param message Message text.
-- @param message Message to send.
function irc:sendChat(target, message)
--- Send a notice to a channel or user.
-- @param target Nick or channel to send to.
-- @param message Notice text.
-- @param message Notice to send.
function irc:sendNotice(target, message)
--- Join a channel.
-- @param channel Channel to join.
-- @param key Channel key. [optional]
-- @param key Channel password. [optional]
function irc:join(channel, key)
--- Leave a channel.
@ -113,51 +108,25 @@ function irc:setMode(t)
--internal
function irc:invoke(name, ...)
function irc:handle(msg)
function irc:handle(prefix, cmd, params)
function irc:shutdown()
--- Table with connection information.
-- @name ConnectOptions
-- @class table
-- @field host Server host name.
-- @field port Server port. [defaults to <code>6667</code>]
-- @field timeout Connect timeout. [defaults to <code>30</code>]
-- @field password Server password.
-- @field secure Boolean to enable TLS connection, pass a params table (described, [luasec]) to control
-- <ul>
-- <li><code>host</code> - Server host name.</li>
-- <li><code>port</code> - Server port. [defaults to <code>6667</code>]</li>
-- <li><code>timeout</code> - Connect timeout. [defaults to <code>30</code>]</li>
-- <li><code>password</code> - Server password.</li>
-- <li><code>secure</code> - Boolean to enable TLS connection, pass a params table (described, [luasec]) to control</li>
-- </ul>
-- [luasec]: http://www.inf.puc-rio.br/~brunoos/luasec/reference.html
--- Class representing a connection.
-- @name Connection
-- @class table
-- @field authed Boolean indicating whether the connection has completed registration.
-- @field connected Whether the connection is currently connected.
-- @field motd The server's message of the day. Can be nil.
-- @field nick The current nickname.
-- @field realname The real name sent to the server.
-- @field username The username/ident sent to the server.
-- @field socket Raw socket used by the library.
-- @field supports What the server claims to support in it's ISUPPORT message.
--- Class representing an IRC message.
-- @name Message
-- @class table
-- @field args A list of the command arguments
-- @field command The IRC command
-- @field prefix The prefix of the message
-- @field raw A raw IRC line for this message
-- @field tags A table of IRCv3 tags
-- @field user A User object describing the sender of the message
-- Fields may be missing.
-- Messages have the following methods:
--- List of hooks you can use with irc:hook. The parameter list describes the parameters passed to the callback function.
-- <ul>
-- <li><code>toRFC1459()</code> - Returns the message serialized in RFC 1459 format.</li>
-- </ul>
--- List of hooks you can use with irc:hook.
-- The parameter list describes the parameters passed to the callback function.
-- <ul>
-- <li><code>PreRegister()</code> - Usefull for requesting capabilities.</li>
-- <li><code>OnRaw(line)</code> - Any non false/nil return value assumes line handled and will not be further processed.</li>
-- <li><code>PreRegister(connection)</code>Useful for CAP commands and SASL.</li>
-- <li><code>OnRaw(line) - (any non false/nil return value assumes line handled and will not be further processed)</code></li>
-- <li><code>OnSend(line)</code></li>
-- <li><code>OnDisconnect(message, errorOccurred)</code></li>
-- <li><code>OnChat(user, channel, message)</code></li>
@ -173,10 +142,7 @@ function irc:shutdown()
-- <li><code>OnUserMode(modes)</code></li>
-- <li><code>OnChannelMode(user, channel, modes)</code></li>
-- <li><code>OnModeChange(user, target, modes, ...)</code>* ('...' contains mode options such as banmasks)</li>
-- <li><code>OnCapabilityList(caps)</code></li>
-- <li><code>OnCapabilityAvailable(cap, value)</code> Called only when a capability becomes available or changes.</li>
-- <li><code>OnCapabilitySet(cap, enabled)</code>*</li>
-- <li><code>DoX(msg)</code>* - 'X' is any IRC command or numeric with the first letter capitalized (eg, DoPing and Do001)</li>
-- <li><code>DoX(user, ...)</code>'X' is any IRC command or numeric with the first letter capitalized (eg, DoPing and Do001)</li>
-- </ul>
-- * Event also invoked for yourself.
-- <20> Channel passed only when user tracking is enabled
@ -185,14 +151,12 @@ function irc:shutdown()
--- Table with information about a user.
-- <ul>
-- <li><code>server</code> - Server name.</li>
-- <li><code>nick</code> - User nickname.</li>
-- <li><code>nick</code> - User nickname. Always present.</li>
-- <li><code>username</code> - User username.</li>
-- <li><code>host</code> - User hostname.</li>
-- <li><code>realname</code> - User real name.</li>
-- <li><code>access</code> - User access, available in channel-oriented callbacks. A table containing boolean fields for each access mode that the server supports. Eg: 'o', and 'v'.</li>
-- </ul>
-- Fields may be missing. To fill them in, enable user tracking and use irc:whois.
-- Apart from <code>nick</code>, fields may be missing. To fill them in, enable user tracking and use irc:whois.
-- @name User
-- @class table

View File

@ -1,144 +1,83 @@
local util = require("irc.util")
local msgs = require("irc.messages")
local Message = msgs.Message
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
local handlers = {}
module "irc"
handlers["PING"] = function(conn, msg)
conn:send(Message({command="PONG", args=msg.args}))
handlers = {}
handlers["PING"] = function(o, user, query)
o:send("PONG :%s", query)
end
local function requestWanted(conn, wanted)
local args = {}
for cap, value in pairs(wanted) do
if type(value) == "string" then
cap = cap .. "=" .. value
end
if not conn.capabilities[cap] then
table.insert(args, cap)
end
end
conn:queue(Message({
command = "CAP",
args = {"REQ", table.concat(args, " ")}
})
)
handlers["001"] = function(o, user, me)
o.authed = true
o.nick = me
end
handlers["CAP"] = function(conn, msg)
local cmd = msg.args[2]
if not cmd then
return
handlers["PRIVMSG"] = function(o, user, channel, message)
o:invoke("OnChat", user, channel, message)
end
if cmd == "LS" then
local list = msg.args[3]
local last = false
if list == "*" then
list = msg.args[4]
handlers["NOTICE"] = function(o, user, channel, message)
o:invoke("OnNotice", user, channel, message)
end
handlers["JOIN"] = function(o, user, channel)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = {users = {}}
else
last = true
o.channels[channel].users[user.nick] = user
end
local avail = conn.availableCapabilities
local wanted = conn.wantedCapabilities
for item in list:gmatch("(%S+)") do
local eq = item:find("=", 1, true)
local k, v
if eq then
k, v = item:sub(1, eq - 1), item:sub(eq + 1)
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, user, channel, reason)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
k, v = item, true
end
if not avail[k] or avail[k] ~= v then
wanted[k] = conn:invoke("OnCapabilityAvailable", k, v)
end
avail[k] = v
end
if last then
if next(wanted) then
requestWanted(conn, wanted)
end
conn:invoke("OnCapabilityList", conn.availableCapabilities)
end
elseif cmd == "ACK" then
for item in msg.args[3]:gmatch("(%S+)") do
local enabled = (item:sub(1, 1) ~= "-")
local name = enabled and item or item:sub(2)
conn:invoke("OnCapabilitySet", name, enabled)
conn.capabilities[name] = enabled
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["001"] = function(conn, msg)
conn.authed = true
conn.nick = msg.args[1]
handlers["QUIT"] = function(o, user, msg)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["PRIVMSG"] = function(conn, msg)
conn:invoke("OnChat", msg.user, msg.args[1], msg.args[2])
end
handlers["NOTICE"] = function(conn, msg)
conn:invoke("OnNotice", msg.user, msg.args[1], msg.args[2])
end
handlers["JOIN"] = function(conn, msg)
local channel = msg.args[1]
if conn.track_users then
if msg.user.nick == conn.nick then
conn.channels[channel] = {users = {}}
else
conn.channels[channel].users[msg.user.nick] = msg.user
end
end
conn:invoke("OnJoin", msg.user, msg.args[1])
end
handlers["PART"] = function(conn, msg)
local channel = msg.args[1]
if conn.track_users then
if msg.user.nick == conn.nick then
conn.channels[channel] = nil
else
conn.channels[channel].users[msg.user.nick] = nil
end
end
conn:invoke("OnPart", msg.user, msg.args[1], msg.args[2])
end
handlers["QUIT"] = function(conn, msg)
if conn.track_users then
for chanName, chan in pairs(conn.channels) do
chan.users[msg.user.nick] = nil
end
end
conn:invoke("OnQuit", msg.user, msg.args[1], msg.args[2])
end
handlers["NICK"] = function(conn, msg)
local newNick = msg.args[1]
if conn.track_users then
for chanName, chan in pairs(conn.channels) do
local users = chan.users
local oldinfo = users[msg.user.nick]
handlers["NICK"] = function(o, user, newnick)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newNick] = oldinfo
users[msg.user.nick] = nil
conn:invoke("NickChange", msg.user, newNick, chanName)
users[newnick] = oldinfo
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
conn:invoke("NickChange", msg.user, newNick)
o:invoke("NickChange", user, newnick)
end
if msg.user.nick == conn.nick then
conn.nick = newNick
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(conn, msg)
local newnick = conn.nickGenerator(msg.args[2])
conn:queue(irc.msgs.nick(newnick))
local function needNewNick(o, user, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
@ -147,131 +86,101 @@ handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
-- ERR_UNAVAILRESOURCE
handlers["437"] = function(conn, msg)
if not conn.authed then
needNewNick(conn, msg)
end
end
-- RPL_ISUPPORT
handlers["005"] = function(conn, msg)
local arglen = #msg.args
-- Skip first and last parameters (nick and info)
for i = 2, arglen - 1 do
local item = msg.args[i]
handlers["005"] = function(o, prefix, nick, ...)
local list = {...}
local listlen = #list
-- Skip last parameter (info)
for i = 1, listlen - 1 do
local item = list[i]
local pos = item:find("=")
if pos then
conn.supports[item:sub(1, pos - 1)] = item:sub(pos + 1)
o.supports[item:sub(1, pos - 1)] = item:sub(pos + 1)
else
conn.supports[item] = true
o.supports[item] = true
end
end
end
-- RPL_MOTDSTART
handlers["375"] = function(conn, msg)
conn.motd = ""
end
-- RPL_MOTD
handlers["372"] = function(conn, msg)
-- MOTD lines have a "- " prefix, strip it.
conn.motd = conn.motd .. msg.args[2]:sub(3) .. '\n'
end
--NAMES list
handlers["353"] = function(conn, msg)
local chanType = msg.args[2]
local channel = msg.args[3]
local names = msg.args[4]
if conn.track_users then
conn.channels[channel] = conn.channels[channel] or {users = {}, type = chanType}
handlers["353"] = function(o, user, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = conn.channels[channel].users
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = util.parseNick(conn, nick)
local access, name = parseNick(o, nick)
users[name] = {access = access}
end
end
end
-- End of NAMES list
handlers["366"] = function(conn, msg)
if conn.track_users then
conn:invoke("NameList", msg.args[2], msg.args[3])
--end of NAMES
handlers["366"] = function(o, user, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
-- No topic
handlers["331"] = function(conn, msg)
conn:invoke("OnTopic", msg.args[2], nil)
--no topic
handlers["331"] = function(o, user, me, channel)
o:invoke("OnTopic", channel, nil)
end
handlers["TOPIC"] = function(conn, msg)
conn:invoke("OnTopic", msg.args[1], msg.args[2])
--new topic
handlers["TOPIC"] = function(o, user, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(conn, msg)
conn:invoke("OnTopic", msg.args[2], msg.args[3])
handlers["332"] = function(o, user, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
-- Topic creation info
handlers["333"] = function(conn, msg)
conn:invoke("OnTopicInfo", msg.args[2], msg.args[3], tonumber(msg.args[4]))
--topic creation info
handlers["333"] = function(o, user, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(conn, msg)
conn:invoke("OnKick", msg.args[1], msg.args[2], msg.user, msg.args[3])
handlers["KICK"] = function(o, user, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, user, reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(conn, msg)
conn:invoke("OnUserMode", msg.args[2])
handlers["221"] = function(o, user, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(conn, msg)
conn:invoke("OnChannelMode", msg.args[2], msg.args[3])
handlers["324"] = function(o, user, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(conn, msg)
local target = msg.args[1]
local modes = msg.args[2]
local optList = {}
for i = 3, #msg.args do
table.insert(optList, msg.args[i])
end
if conn.track_users and target ~= conn.nick then
handlers["MODE"] = function(o, user, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local argNum = 1
util.updatePrefixModes(conn)
local optList = {...}
updatePrefixModes(o)
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif conn.modeprefix[c] then
local nick = optList[argNum]
argNum = argNum + 1
local user = conn.channels[target].users[nick]
user.access = user.access or {}
local access = user.access
access[c] = add
elseif o.modeprefix[c] then
local nick = table.remove(optList, 1)
local access = o.channels[target].users[nick].access
access[o.modeprefix[c]] = add
if c == "o" then access.op = add
elseif c == "v" then access.voice = add
end
end
end
end
conn:invoke("OnModeChange", msg.user, target, modes, unpack(optList))
o:invoke("OnModeChange", user, target, modes, ...)
end
handlers["ERROR"] = function(conn, msg)
conn:invoke("OnDisconnect", msg.args[1], true)
conn:shutdown()
error(msg.args[1], 3)
handlers["ERROR"] = function(o, user, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
return handlers

116
init.lua
View File

@ -1,47 +1,47 @@
local socket = require("socket")
local util = require("irc.util")
local handlers = require("irc.handlers")
local msgs = require("irc.messages")
local Message = msgs.Message
local socket = require "socket"
local error = error
local setmetatable = setmetatable
local rawget = rawget
local unpack = unpack
local pairs = pairs
local assert = assert
local require = require
local tonumber = tonumber
local type = type
local pcall = pcall
module "irc"
local meta = {}
meta.__index = meta
_META = meta
for k, v in pairs(require("irc.asyncoperations")) do
meta[k] = v
end
require "irc.util"
require "irc.asyncoperations"
require "irc.handlers"
local meta_preconnect = {}
function meta_preconnect.__index(o, k)
local v = rawget(meta_preconnect, k)
if v == nil and meta[k] ~= nil then
if not v and meta[k] then
error(("field '%s' is not accessible before connecting"):format(k), 2)
end
return v
end
meta.connected = true
meta_preconnect.connected = false
function new(data)
local o = {
nick = assert(data.nick, "Field 'nick' is required");
username = data.username or "lua";
realname = data.realname or "Lua owns";
nickGenerator = data.nickGenerator or util.defaultNickGenerator;
nickGenerator = data.nickGenerator or defaultNickGenerator;
hooks = {};
track_users = true;
supports = {};
messageQueue = {};
lastThought = 0;
recentMessages = 0;
availableCapabilities = {};
wantedCapabilities = {};
capabilities = {};
}
assert(util.checkNick(o.nick), "Erroneous nickname passed to irc.new")
assert(checkNick(o.nick), "Erroneous nickname passed to irc.new")
return setmetatable(o, meta_preconnect)
end
@ -68,9 +68,8 @@ function meta:invoke(name, ...)
local hooks = self.hooks[name]
if hooks then
for id,f in pairs(hooks) do
local ret = f(...)
if ret then
return ret
if f(...) then
return true
end
end
end
@ -112,7 +111,7 @@ function meta_preconnect:connect(_host, _port)
end
s = ssl.wrap(s, params)
local success, errmsg = s:dohandshake()
success, errmsg = s:dohandshake()
if not success then
error(("could not make secure connection: %s"):format(errmsg), 2)
end
@ -121,14 +120,17 @@ function meta_preconnect:connect(_host, _port)
self.socket = s
setmetatable(self, meta)
self:send("CAP REQ multi-prefix")
self:invoke("PreRegister", self)
self:send("CAP END")
if password then
self:queue(Message({command="PASS", args={password}}))
self:send("PASS %s", password)
end
self:queue(msgs.nick(self.nick))
self:queue(Message({command="USER", args={self.username, "0", "*", self.realname}}))
self:send("NICK %s", self.nick)
self:send("USER %s 0 * :%s", self.username, self.realname)
self.channels = {}
@ -136,7 +138,6 @@ function meta_preconnect:connect(_host, _port)
repeat
self:think()
socket.sleep(0.1)
until self.authed
end
@ -144,14 +145,14 @@ function meta:disconnect(message)
message = message or "Bye!"
self:invoke("OnDisconnect", message, false)
self:send(msgs.quit(message))
self:send("QUIT :%s", message)
self:shutdown()
end
function meta:shutdown()
self.socket:close()
setmetatable(self, meta_preconnect)
setmetatable(self, nil)
end
local function getline(self, errlevel)
@ -171,35 +172,23 @@ function meta:think()
local line = getline(self, 3)
if line and #line > 0 then
if not self:invoke("OnRaw", line) then
self:handle(Message({raw=line}))
self:handle(parse(line))
end
else
break
end
end
-- Handle outgoing message queue
local diff = socket.gettime() - self.lastThought
self.recentMessages = self.recentMessages - (diff * 2)
if self.recentMessages < 0 then
self.recentMessages = 0
end
for i = 1, #self.messageQueue do
if self.recentMessages > 4 then
break
end
self:send(table.remove(self.messageQueue, 1))
self.recentMessages = self.recentMessages + 1
end
self.lastThought = socket.gettime()
end
function meta:handle(msg)
local handler = handlers[msg.command]
local handlers = handlers
function meta:handle(prefix, cmd, params)
local user = parsePrefix(prefix)
local handler = handlers[cmd]
if handler then
handler(self, msg)
handler(self, user, unpack(params))
end
self:invoke("Do" .. util.capitalize(msg.command), msg)
self:invoke("Do"..capitalize(cmd), user, unpack(params))
end
local whoisHandlers = {
@ -211,22 +200,22 @@ local whoisHandlers = {
}
function meta:whois(nick)
self:send(msgs.whois(nick))
self:send("WHOIS %s", nick)
local result = {}
while true do
local line = getline(self, 3)
if line then
local msg = Message({raw=line})
local prefix, cmd, args = parse(line)
local handler = whoisHandlers[msg.command]
local handler = whoisHandlers[cmd]
if handler then
result[handler] = msg.args
elseif msg.command == "318" then
result[handler] = args
elseif cmd == "318" then
break
else
self:handle(msg)
self:handle(prefix, cmd, args)
end
end
end
@ -241,17 +230,6 @@ function meta:whois(nick)
end
function meta:topic(channel)
self:queue(msgs.topic(channel))
self:send("TOPIC %s", channel)
end
return {
new = new;
Message = Message;
msgs = msgs;
color = util.color;
bold = util.bold;
underline = util.underline;
}

View File

@ -1,207 +0,0 @@
-- Module table
local m = {}
local msg_meta = {}
msg_meta.__index = msg_meta
local function Message(opts)
opts = opts or {}
setmetatable(opts, msg_meta)
if opts.raw then
opts:fromRFC1459(opts.raw)
end
return opts
end
m.Message = Message
local tag_escapes = {
[";"] = "\\:",
[" "] = "\\s",
["\0"] = "\\0",
["\\"] = "\\\\",
["\r"] = "\\r",
["\n"] = "\\n",
}
local tag_unescapes = {}
for x, y in pairs(tag_escapes) do tag_unescapes[y] = x end
function msg_meta:toRFC1459()
local s = ""
if self.tags then
s = s.."@"
for key, value in pairs(self.tags) do
s = s..key
if value ~= true then
value = value:gsub("[; %z\\\r\n]", tag_escapes)
s = s.."="..value
end
s = s..";"
end
-- Strip trailing semicolon
s = s:sub(1, -2)
s = s.." "
end
s = s..self.command
local argnum = self.args and #self.args or 0
for i = 1, argnum do
local arg = self.args[i]
local startsWithColon = (arg:sub(1, 1) == ":")
local hasSpace = arg:find(" ")
if i == argnum and (hasSpace or startsWithColon) then
s = s.." :"
else
assert(not hasSpace and not startsWithColon,
"Message arguments can not be "
.."serialized to RFC1459 format")
s = s.." "
end
s = s..arg
end
return s
end
local function parsePrefix(prefix)
local user = {}
user.nick, user.username, user.host = prefix:match("^(.+)!(.+)@(.+)$")
if not user.nick and prefix:find(".", 1, true) then
user.server = prefix
end
return user
end
function msg_meta:fromRFC1459(line)
-- IRCv3 tags
if line:sub(1, 1) == "@" then
self.tags = {}
local space = line:find(" ", 1, true)
-- For each semicolon-delimited section from after
-- the @ character to before the space character.
for tag in line:sub(2, space - 1):gmatch("([^;]+)") do
local eq = tag:find("=", 1, true)
if eq then
self.tags[tag:sub(1, eq - 1)] =
tag:sub(eq + 1):gsub("\\([:s0\\rn])", tag_unescapes)
else
self.tags[tag] = true
end
end
line = line:sub(space + 1)
end
if line:sub(1, 1) == ":" then
local space = line:find(" ", 1, true)
self.prefix = line:sub(2, space - 1)
self.user = parsePrefix(self.prefix)
line = line:sub(space + 1)
end
local pos
self.command, pos = line:match("(%S+)()")
line = line:sub(pos)
self.args = self.args or {}
for pos, param in line:gmatch("()(%S+)") do
if param:sub(1, 1) == ":" then
param = line:sub(pos + 1)
table.insert(self.args, param)
break
end
table.insert(self.args, param)
end
end
function m.privmsg(to, text)
return Message({command="PRIVMSG", args={to, text}})
end
function m.notice(to, text)
return Message({command="NOTICE", args={to, text}})
end
function m.action(to, text)
return Message({command="PRIVMSG", args={to, ("\x01ACTION %s\x01"):format(text)}})
end
function m.ctcp(command, to, args)
s = "\x01"..command
if args then
s = ' '..args
end
s = s..'\x01'
return Message({command="PRIVMSG", args={to, s}})
end
function m.kick(channel, target, reason)
return Message({command="KICK", args={channel, target, reason}})
end
function m.join(channel, key)
return Message({command="JOIN", args={channel, key}})
end
function m.part(channel, reason)
return Message({command="PART", args={channel, reason}})
end
function m.quit(reason)
return Message({command="QUIT", args={reason}})
end
function m.kill(target, reason)
return Message({command="KILL", args={target, reason}})
end
function m.kline(time, mask, reason, operreason)
local args = nil
if time then
args = {time, mask, reason..'|'..operreason}
else
args = {mask, reason..'|'..operreason}
end
return Message({command="KLINE", args=args})
end
function m.whois(nick, server)
local args = nil
if server then
args = {server, nick}
else
args = {nick}
end
return Message({command="WHOIS", args=args})
end
function m.topic(channel, text)
return Message({command="TOPIC", args={channel, text}})
end
function m.invite(channel, target)
return Message({command="INVITE", args={channel, target}})
end
function m.nick(nick)
return Message({command="NICK", args={nick}})
end
function m.mode(target, modes)
-- We have to split the modes parameter because the mode string and
-- each parameter are seperate arguments (The first command is incorrect)
-- MODE foo :+ov Nick1 Nick2
-- MODE foo +ov Nick1 Nick2
local mt = util.split(modes)
return Message({command="MODE", args={target, unpack(mt)}})
end
function m.cap(cmd, ...)
return Message({command="CAP", args={cmd, ...}})
end
return m

View File

@ -1,19 +0,0 @@
#!/bin/bash
if [ "$TRAVIS_REPO_SLUG" == "JakobOvrum/LuaIRC" ] && [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_BRANCH" == "master" ]; then
echo -e "Generating luadoc...\n"
git config --global user.email "travis@travis-ci.org"
git config --global user.name "travis-ci"
git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG} gh-pages > /dev/null
cd gh-pages
git rm -rf ./doc
sh ./generate.sh
git add -f ./doc
git commit -m "Lastest documentation on successful travis build $TRAVIS_BUILD_NUMBER auto-pushed to gh-pages"
git push -fq origin gh-pages > /dev/null
echo -e "Published luadoc to gh-pages.\n"
fi

16
set.lua
View File

@ -1,10 +1,17 @@
local select = require("socket").select
local select = require "socket".select
local setmetatable = setmetatable
local insert = table.insert
local remove = table.remove
local ipairs = ipairs
local error = error
module "irc.set"
local m = {}
local set = {}
set.__index = set
function m.new(t)
function new(t)
t.connections = {}
t.sockets = {}
return setmetatable(t, set)
@ -47,6 +54,3 @@ function set:poll()
local read, err = self:select()
return err == "timeout" and self.connections or read
end
return m

148
util.lua
View File

@ -1,8 +1,83 @@
local setmetatable = setmetatable
local sub = string.sub
local byte = string.byte
local char = string.char
local table = table
local assert = assert
local tostring = tostring
local type = type
local random = math.random
-- Module table
local m = {}
module "irc"
function m.updatePrefixModes(conn)
--protocol parsing
function parse(line)
local prefix
local lineStart = 1
if line:sub(1,1) == ":" then
local space = line:find(" ")
prefix = line:sub(2, space-1)
lineStart = space
end
local _, trailToken = line:find("%s+:", lineStart)
local lineStop = line:len()
local trailing
if trailToken then
trailing = line:sub(trailToken + 1)
lineStop = trailToken - 2
end
local params = {}
local _, cmdEnd, cmd = line:find("(%S+)", lineStart)
local pos = cmdEnd + 1
while true do
local _, stop, param = line:find("(%S+)", pos)
if not param or stop > lineStop then
break
end
pos = stop + 1
params[#params + 1] = param
end
if trailing then
params[#params + 1] = trailing
end
return prefix, cmd, params
end
function parseNick(conn, nick)
local access = {}
updatePrefixModes(conn)
local namestart = 1
for i = 1, #nick - 1 do
local c = nick:sub(i, i)
if conn.prefixmode[c] then
access[conn.prefixmode[c]] = true
else
namestart = i
break
end
end
access.op = access.o
access.voice = access.v
local name = nick:sub(namestart)
return access, name
end
function parsePrefix(prefix)
local user = {}
if prefix then
user.nick, user.username, user.host = prefix:match("^(.+)!(.+)@(.+)$")
end
return user
end
function updatePrefixModes(conn)
if conn.prefixmode and conn.modeprefix then
return
end
@ -22,27 +97,8 @@ function m.updatePrefixModes(conn)
end
end
function m.parseNick(conn, nick)
local access = {}
m.updatePrefixModes(conn)
local namestart = 1
for i = 1, #nick - 1 do
local c = nick:sub(i, i)
if conn.prefixmode[c] then
access[conn.prefixmode[c]] = true
else
namestart = i
break
end
end
access.op = access.o
access.voice = access.v
local name = nick:sub(namestart)
return access, name
end
--mIRC markup scheme (de-facto standard)
m.color = {
color = {
black = 1,
blue = 2,
green = 3,
@ -61,60 +117,48 @@ m.color = {
white = 16
}
local colByte = string.char(3)
setmetatable(m.color, {__call = function(_, text, colornum)
colornum = (type(colornum) == "string" and
assert(color[colornum], "Invalid color '"..colornum.."'") or
colornum)
local colByte = char(3)
setmetatable(color, {__call = function(_, text, colornum)
colornum = type(colornum) == "string" and assert(color[colornum], "Invalid color '"..colornum.."'") or colornum
return table.concat{colByte, tostring(colornum), text, colByte}
end})
local boldByte = string.char(2)
function m.bold(text)
local boldByte = char(2)
function bold(text)
return boldByte..text..boldByte
end
local underlineByte = string.char(31)
function m.underline(text)
local underlineByte = char(31)
function underline(text)
return underlineByte..text..underlineByte
end
function m.checkNick(nick)
function checkNick(nick)
return nick:find("^[a-zA-Z_%-%[|%]%^{|}`][a-zA-Z0-9_%-%[|%]%^{|}`]*$") ~= nil
end
function m.defaultNickGenerator(nick)
function defaultNickGenerator(nick)
-- LuaBot -> LuaCot -> LuaCou -> ...
-- We change a random character rather than appending to the
-- We change a random charachter rather than appending to the
-- nickname as otherwise the new nick could exceed the ircd's
-- maximum nickname length.
local randindex = math.random(1, #nick)
local randchar = string.sub(nick, randindex, randindex)
local b = string.byte(randchar)
local randindex = random(1, #nick)
local randchar = sub(nick, randindex, randindex)
local b = byte(randchar)
b = b + 1
if b < 65 or b > 125 then
b = 65
end
-- Get the halves before and after the changed character
local first = string.sub(nick, 1, randindex - 1)
local last = string.sub(nick, randindex + 1, #nick)
nick = first .. string.char(b) .. last -- Insert the new charachter
local first = sub(nick, 1, randindex - 1)
local last = sub(nick, randindex + 1, #nick)
nick = first..char(b)..last -- Insert the new charachter
return nick
end
function m.capitalize(text)
function capitalize(text)
-- Converts first character to upercase and the rest to lowercase.
-- "PING" -> "Ping" | "hello" -> "Hello" | "123" -> "123"
return text:sub(1, 1):upper()..text:sub(2):lower()
end
function m.split(str, sep)
local t = {}
for s in str:gmatch("%S+") do
table.insert(t, s)
end
return t
end
return m