This repository has been archived by the owner on Nov 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.coffee
158 lines (140 loc) · 5.42 KB
/
api.coffee
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
###
# Chatbot for Tim's Chat 3
# Copyright (C) 2011 - 2014 Tim Düsterhus
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
###
common = require './common'
config = require './config'
winston = require 'winston'
debug = (require 'debug')('Chatbot:api')
remainingFails = 3
# attempts to retrieve the current security token
# calls the callback without parameters afterwards
fetchSecurityToken = (callback) ->
debug "Fetching security token..."
common.request.get config.host + '/index.php', (err, res, body) ->
common.fatal 'Cannot fetch security token:', err if err?
common.fatal 'Unable to find security token in source' unless [_, config.securityToken] = body.match /var SECURITY_TOKEN = '([a-f0-9]{40})';/
debug "Done, Security token is: #{config.securityToken}"
callback?()
# attempts to login the user, will save the userID in config.userID
# calls the callback without parameters afterwards
sendLoginRequest = (callback) ->
debug "Logging in as #{config.username}..."
common.request.post config.host + '/index.php/Login/',
form:
username: config.username
password: config.password
t: config.securityToken
, (err, res, body) ->
common.fatal 'Cannot send login request', err if err?
common.fatal 'Login unsuccessful' unless /WCF\.User\.init\((\d+), '/.test body
[ _, userID ] = body.match /WCF\.User\.init\((\d+), '/
common.fatal 'Login unsuccessful' if not userID or (config.userID = parseInt userID) is 0
winston.info 'Logged in as userID', config.userID
callback?()
# attempts to join the room with the given roomID
# calls the callback without parameters if everything was successful
# and with a string as the first parameter when something failed
joinRoom = (roomID, callback) ->
debug "Joining room #{roomID}"
common.request.post config.host + '/index.php/AJAXProxy/',
form:
actionName: 'join'
className: 'chat\\data\\room\\RoomAction'
'parameters[roomID]': roomID
t: config.securityToken
, (err, res, body) ->
data = (JSON.parse body).returnValues
if data.errorMessage?
if data.fieldName is 'roomID'
winston.error "Room is invalid"
callback 'invalid' if callback?
else
common.fatal "Unexpected error while joining: #{JSON.stringify(data)}"
else
debug "Done, room title is #{data.title}"
callback?()
# retrieves the roomlist and calls the callback with the roomList as
# first parameter afterwards
getRoomList = (callback) ->
debug "Fetching roomlist..."
common.request.post config.host + '/index.php/AJAXProxy/',
form:
actionName: 'getRoomList'
className: 'chat\\data\\room\\RoomAction'
t: config.securityToken
, (err, res, body) ->
roomList = (JSON.parse body).returnValues
debug "Found #{roomList.length} rooms"
callback roomList if callback?
# Leaves the chat
# calls the callback without parameters afterwards
leaveChat = (callback) ->
winston.info "Leaving chat..."
common.request.post config.host + '/index.php/AJAXProxy/',
form:
actionName: 'leave'
className: 'chat\\data\\room\\RoomAction'
t: config.securityToken
, callback
# Fetches new messages and calls the callback with the retrieved data object
fetchMessages = (callback) ->
common.request.get config.host + '/index.php/NewMessages/', (err, res, body) ->
try
data = JSON.parse body
remainingFails = 3
catch e
unless --remainingFails
common.fatal "Invalid JSON returned by NewMessages #{body}"
else
winston.warn "Fetching messages failed. Remaining fails until shutdown: #{remainingFails}"
callback? data
# Permanently fetches messages with a delay of half a second between requests
recursiveFetchMessages = (callback) ->
fetchMessages (data) ->
callback data if callback
setTimeout ->
recursiveFetchMessages callback
, 5e2
# sends a message with `message` as the content and the given
# smiley status and calls the callback without any parameters afterwards
sendMessage = (message, options..., callback) ->
enableSmilies = options[0] ? yes
roomID = options[1] ? 0
common.request.post config.host + '/index.php/AJAXProxy/',
form:
actionName: 'send'
className: 'chat\\data\\message\\MessageAction'
'parameters[text]': message
'parameters[enableSmilies]': if enableSmilies then 1 else 0
'parameters[roomID]': roomID
t: config.securityToken
, callback
# replies (i.e. whispers to the sender) to the given message. See `sendMessage`
replyTo = (message, reply, enableSmilies = yes, callback) -> sendMessage "/whisper #{message.username}, #{reply}", enableSmilies, callback
# escapes the / at the beginning of a message
escapeMessage = (message) -> message.replace /^\//, '//'
module.exports =
fetchSecurityToken: fetchSecurityToken
sendLoginRequest: sendLoginRequest
joinRoom: joinRoom
getRoomList: getRoomList
leaveChat: leaveChat
fetchMessages: fetchMessages
recursiveFetchMessages: recursiveFetchMessages
sendMessage: sendMessage
replyTo: replyTo
escapeMessage: escapeMessage