This repository has been archived by the owner on Jun 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
233 lines (199 loc) · 6.03 KB
/
app.js
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
'use strict'
// Requirement
const Koa = require('koa')
const chalk = require('chalk')
const log = require('fancy-log')
const koaBody = require('koa-body')
const Router = require('koa-router')
const mongoose = require('mongoose')
const Streamer = require('fanfou-streamer')
const APN = require('./utils/apn')
const ClientModel = require('./models/client')
const config = require('./config')
const {
PORT,
CONSUMER_KEY,
CONSUMER_SECRET
} = config
// =========================
// Database connection
// =========================
const database = `mongodb://${config.DB.HOST}:${config.DB.PORT}/${config.DB.DATABASE}`
const connOptions = {
useMongoClient: true
}
// Attach user and pass info if present to operate on the secured collection
if (config.DB.USER && config.DB.PASS) {
connOptions.user = config.DB.USER
connOptions.pass = config.DB.PASS
}
mongoose.connect(database, connOptions)
mongoose.connection.on('connected', () => {
console.log(`Database connected to ${database}`)
})
mongoose.connection.on('error', err => {
console.log(`Database connection to ${database} error: ${err}`)
})
mongoose.connection.on('disconnected', () => {
console.log(`Database disconnected from ${database}`)
})
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log(`Database disconnected from ${database} due to server app termination`)
process.exit(0)
})
})
// Clients
process.clients = {}
function createStreamer (id, deviceToken, oauthToken, oauthTokenSecret) {
process.clients[id] = {}
process.clients[id].streamer = new Streamer({
consumerKey: CONSUMER_KEY,
consumerSecret: CONSUMER_SECRET,
oauthToken,
oauthTokenSecret
})
process.clients[id].streamer.start()
process.clients[id].user = {
deviceToken,
oauthToken,
oauthTokenSecret
}
// Mentions
process.clients[id].streamer.on('message.mention', res => {
log('mention event')
APN.send(`@${res.source.screen_name} 提到了你:\n${res.object.text}`, deviceToken)
})
// Reply
process.clients[id].streamer.on('message.reply', res => {
log('reply event')
APN.send(`@${res.source.screen_name} 回复了你:\n${res.object.text}`, deviceToken)
})
// Repost
process.clients[id].streamer.on('message.repost', res => {
log('repost event')
APN.send(`@${res.source.screen_name} 转发了:\n${res.object.text}`, deviceToken)
})
// Add fav
process.clients[id].streamer.on('fav.create', res => {
log('add-fav event')
APN.send(`@${res.source.screen_name} 收藏了:\n${res.object.text}`, deviceToken)
})
// Del fav
process.clients[id].streamer.on('fav.delete', res => {
log('del-fav event')
APN.send(`@${res.source.screen_name} 取消收藏了:\n${res.object.text}`, deviceToken)
})
// Create direct message
process.clients[id].streamer.on('dm.create', res => {
log('dm-create event')
APN.send(`@${res.source.screen_name} 私信了你:\n${res.object.text}`, deviceToken)
})
// Create friends
process.clients[id].streamer.on('friends.create', res => {
log('friends-create event')
APN.send(`@${res.source.srceen_name} 关注了你`)
})
// Request friends
process.clients[id].streamer.on('friends.request', res => {
log('friends-request event')
APN.send(`@${res.source.screen_name} 请求关注你`)
})
}
// Restore all existing states from DB
(async function () {
let result
try {
result = await ClientModel.find()
} catch (err) {
log(`Failed to find client states from DB: ${err.toString()}`)
}
if (!Array.isArray(result)) {
return false
}
for (const client of result) {
createStreamer(
client.clientId,
client.deviceToken,
client.oauthToken,
client.oauthTokenSecret
)
}
})()
// Koa
const app = new Koa()
const router = new Router()
// Router
router.post('/notifier/on', koaBody(), async ctx => {
log('POST /notifier/on')
const deviceToken = ctx.request.body.device_token
const oauthToken = ctx.request.body.oauth_token
const oauthTokenSecret = ctx.request.body.oauth_token_secret
const id = `${deviceToken}${oauthToken}`
// Validate
if (!(deviceToken && oauthToken && oauthTokenSecret)) {
log('invalid parameters')
ctx.body = 'invalid'
} else if (process.clients[id] && process.clients[id].streamer) {
log('streamer already exists')
if (!process.clients[id].streamer.isStreaming) {
process.clients[id].streamer.start()
}
ctx.body = 'on'
} else {
log('create streamer')
// Save the client to DB
const dbParams = {
clientId: id,
deviceToken,
oauthToken,
oauthTokenSecret
}
const dbHandle = new ClientModel(dbParams)
ctx.body = 'on'
try {
await dbHandle.save()
} catch (err) {
log(`Failed to save Client state to DB: ${err.toString()}`)
}
// Start a streamer
createStreamer(id, deviceToken, oauthToken, oauthTokenSecret)
}
})
router.post('/notifier/off', koaBody(), async ctx => {
const deviceToken = ctx.request.body.device_token
const oauthToken = ctx.request.body.oauth_token
const id = `${deviceToken}${oauthToken}`
if (!(deviceToken && oauthToken)) {
ctx.body = 'invalid'
} else if (process.clients[id] && process.clients[id].streamer && process.clients[id].streamer.isStreaming) {
process.clients[id].streamer.stop()
delete process.clients[id]
ctx.body = 'off'
} else {
ctx.body = 'off'
}
// Remove the client from DB
await ClientModel.deleteByClientId(id)
})
router.get('/notifier/check', ctx => {
const deviceToken = ctx.query.device_token
const oauthToken = ctx.query.oauth_token
const id = `${deviceToken}${oauthToken}`
if (!(deviceToken && oauthToken)) {
ctx.body = 'invalid'
} else if (process.clients[id] && process.clients[id].streamer) {
if (!process.clients.streamer.isStreaming) {
process.clients[id].streamer._start()
}
ctx.body = 'on'
} else {
ctx.body = 'off'
}
})
app
.use(router.routes())
.use(router.allowedMethods())
app.listen(PORT)
// Log
log(chalk.green(`Maofan notifier startup, listening on ${PORT}`))