-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpushcpp_subscriptions.cpp
101 lines (78 loc) · 2.01 KB
/
pushcpp_subscriptions.cpp
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
#include "pushcpp_internal.h"
bool pushcpp::subscribe(
const string &channel,
ChannelEventHandler event,
ChannelAuthHandler auth
)
{
ChannelData d = m_channelData[channel];
if (event != NULL)
d.eventHandlers.insert(event);
if (auth != NULL)
d.authHandler = auth;
else
d.authHandler = NULL;
m_channelData[channel] = d;
DEBUG("Subscribing to %s", channel.c_str());
if (connected())
return sendSubscription(true, channel);
else
return false;
}
void pushcpp::unsubscribe(
const std::string &channel
)
{
m_channelData.erase(channel);
DEBUG("Unsubscribing from %s", channel.c_str());
if (connected())
sendSubscription(false, channel);
}
std::unordered_map<std::string, pushcpp::ChannelData> pushcpp::subscriptions(
bool confirmedOnly
) const
{
unordered_map<string, ChannelData> ret;
for (
auto it = m_channelData.begin();
it != m_channelData.end();
it++
)
if (!confirmedOnly || (confirmedOnly && it->second.subscribed))
ret[it->first] = it->second;
return ret;
}
bool pushcpp::sendSubscription(
bool subscribe,
const std::string &channel
)
{
json_t *json = json_object();
json_object_set_new(
json, "event",
json_string(subscribe ? "pusher:subscribe" : "pusher:unsubscribe"));
json_t *data = json_object();
json_object_set_new(data, "channel", json_string(channel.c_str()));
if (subscribe) {
auto chanData = m_channelData.find(channel);
if (chanData != m_channelData.end() && chanData->second.authHandler != NULL) {
assert(!this->m_socketId.empty());
ChannelAuthentication authdata =
chanData->second.authHandler(this->m_socketId, channel);
string chdata = authdata.channelData;
if (chdata == "")
chdata = "{}";
json_object_set_new(data, "auth",
json_string(authdata.auth.c_str()));
json_object_set_new(data, "channel_data",
json_string(chdata.c_str()));
}
}
json_object_set_new(json, "data", data);
char *dumped = json_dumps(json, 0);
assert(dumped);
bool ret = sendRaw(dumped);
free(dumped);
json_decref(json);
return ret;
}