forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPandaPub.coffee
More file actions
73 lines (53 loc) · 1.79 KB
/
Copy pathPandaPub.coffee
File metadata and controls
73 lines (53 loc) · 1.79 KB
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
define [ 'INST', 'jquery' ], (INST, $) ->
class Client
constructor: ->
@faye = null
@tokens = {}
# Is truthy if PandaPub is enabled.
#
enabled:
INST.pandaPubSettings
# Subscribe to a channel with a token. Returns an object
# which can receive a .cancel() call in order to unsubscribe.
# That object is also a Deferred, to find out when the subscription
# is successful or failed.
#
subscribe: (channel, token, cb) =>
fullChannel = "/#{INST.pandaPubSettings.application_id}#{channel}"
@tokens[fullChannel] = token
dfd = new $.Deferred
dfd.cancel = ->
@client (faye) =>
subscription = faye.subscribe fullChannel, (message) ->
cb(message)
subscription.then dfd.resolve, dfd.reject
dfd.cancel = ->
subscription.cancel()
dfd
# Subscribe to transport-level events, transport:down or
# transport:up. See http://faye.jcoglan.com/browser/transport.html
on: (event, cb) =>
@client (faye) =>
faye.on(event, cb)
# @api private
authExtension: =>
outgoing: (message, cb) =>
if message.channel == '/meta/subscribe'
if message.subscription of @tokens
message.ext ||= {}
message.ext.auth =
token: @tokens[message.subscription]
cb(message)
# Creates or returns the internal Faye client, loading it first
# if necessary.
#
# @api private
client: (cb) ->
if @faye then cb(@faye)
unless @faye
$.getScript INST.pandaPubSettings.push_url + '/client.js', =>
@faye = new window.Faye.Client INST.pandaPubSettings.push_url
@faye.addExtension @authExtension()
cb @faye
# We return a singleton instance of our client.
new Client