This repository has been archived by the owner on Sep 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpusher.js
58 lines (56 loc) · 2.05 KB
/
pusher.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
// Run node build/js/pusher to run this (while hz serve --dev is also running)
var r = require('rethinkdb');
var http = require('http');
var request = require('request');
console.log('connecting to port ', process.argv[2])
r.connect({host: 'localhost', port: process.argv[2], db: 'collaboration'}, function(err, connection){
if (err) {
throw err;
}
console.log('connected');
r.table('directMessages').changes().run(connection, function(err, cursor) {
if (err) {
console.error(err)
} else {
cursor.each(function(err, row) {
if (err) throw err;
var text = row.new_val.text;
// var bothUserIds = row.new_val.chatRoomId.split('-');
// var userId = bothUserIds[0] === row.new_val.fromUserId ? bothUserIds[1] : bothUserIds[0];
var userId = row.new_val.toUserId;
var fromUserId = row.new_val.fromUserId;
console.log('recieved message of '+text.length+' characters to user '+userId);
r.table('users').get(userId).run(connection, function(err, result) {
if (err) {
console.error(err);
} else {
if (result.pushEndpoint) {
var senderId = result.pushEndpoint.substr('https://android.googleapis.com/gcm/send/'.length);
console.log('sending push message to ', senderId);
request.post({
url: 'https://android.googleapis.com/gcm/send',
headers: {
'Authorization': 'key=AIzaSyAs5kl1lntUFNYeP_83yxydOBzaBf_bu-c',
'Content-Type': 'application/json'
},
body: JSON.stringify({
registration_ids: [senderId],
data: {
text: text,
fromUserId: fromUserId
}
})
}, function(error, response, body) {
if (err) {
console.error(err);
} else {
console.log(body);
}
});
}
}
});
});
}
});
});