/
trans-jsonp.coffee
84 lines (72 loc) · 2.45 KB
/
trans-jsonp.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
# ***** BEGIN LICENSE BLOCK *****
# Copyright (c) 2011-2012 VMware, Inc.
#
# For the license see COPYING.
# ***** END LICENSE BLOCK *****
transport = require('./transport')
class JsonpReceiver extends transport.ResponseReceiver
protocol: "jsonp-polling"
max_response_size: 1
constructor: (res, options, @callback) ->
super(res, options)
doSendFrame: (payload) ->
# Yes, JSONed twice, there isn't a a better way, we must pass
# a string back, and the script, will be evaled() by the
# browser.
super(@callback + "(" + JSON.stringify(payload) + ");\r\n")
exports.app =
jsonp: (req, res, _, next_filter) ->
if not('c' of req.query or 'callback' of req.query)
throw {
status: 500
message: '"callback" parameter required'
}
callback = if 'c' of req.query then req.query['c'] else req.query['callback']
if /[^a-zA-Z0-9-_.]/.test(callback)
throw {
status: 500
message: 'invalid "callback" parameter'
}
res.setHeader('Content-Type', 'application/javascript; charset=UTF-8')
res.writeHead(200)
transport.register(req, @, new JsonpReceiver(res, @options, callback))
return true
jsonp_send: (req, res, query) ->
if not query
throw {
status: 500
message: 'Payload expected.'
}
if typeof query is 'string'
try
d = JSON.parse(query)
catch e
throw {
status: 500
message: 'Broken JSON encoding.'
}
else
d = query.d
if typeof d is 'string' and d
try
d = JSON.parse(d)
catch e
throw {
status: 500
message: 'Broken JSON encoding.'
}
if not d or d.__proto__.constructor isnt Array
throw {
status: 500
message: 'Payload expected.'
}
jsonp = transport.Session.bySessionId(req.session)
if jsonp is null
throw {status: 404}
for message in d
jsonp.didMessage(message)
res.setHeader('Content-Length', '2')
res.setHeader('Content-Type', 'text/plain; charset=UTF-8')
res.writeHead(200)
res.end('ok')
return true