-
Notifications
You must be signed in to change notification settings - Fork 2
/
startServices.js
182 lines (150 loc) · 5.6 KB
/
startServices.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
var firebase = require('firebase-admin');
var request = require('request');
var moment = require('moment');
var config = require('./config.json')
var nodemailer = require("nodemailer");
var fs = require('fs')
, Log = require('log')
, FCMlog = new Log('info', fs.createWriteStream(__dirname + '/FCMlog.txt', { flags: 'a' }))
, Reglog = new Log('info', fs.createWriteStream(__dirname + '/Registrationlog.txt', { flags: 'a' }));
FCMlog.info("=================================")
FCMlog.info("Server restarted")
FCMlog.info("=================================")
Reglog.info("=================================")
Reglog.info("Server restarted")
Reglog.info("=================================")
var API_KEY = config.API_KEY; // Your Firebase Cloud Messaging Server API key
// Fetch the service account key JSON file contents
var serviceAccount = require("./serviceAccount.json");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: config.databaseURL
});
ref = firebase.database().ref();
// FCM Notification
function listenForNotificationRequests() {
FCMlog.info("Ready for listening")
var requests = ref.child('feeds');
requests.on('child_added', function (requestSnapshot) {
var feeds = requestSnapshot.val();
if (feeds.time > (moment().unix() - 600)) {
// Push only feeds which are new or at most 10 minutes old
sendNotification(feeds.to, feeds.title, feeds.description)
} else {
FCMlog.info("Outdated: %s", feeds.title)
console.log("[" + moment().format() + "] Outdated: ", feeds.title)
}
}, function (error) {
FCMlog.error(error)
});
};
function sendNotification(to, title, body) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type': ' application/json',
'Authorization': 'key=' + API_KEY
},
body: JSON.stringify({
notification: {
title,
body,
"sound": "default",
"click_action": "fcm.ACTION.HELLO"
},
to
})
}, function (error, response, body1) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
FCMlog.error("HTTP error: %s - %s", response.statusCode, response.statusMessage)
console.log('HTTP Error: ' + response.statusCode + ' - ' + response.statusMessage);
} else {
FCMlog.info("Pushed: %s: %s", to, title)
console.log("[" + moment().format() + "] Pushed: ", to, ":", title)
}
});
}
// Registration
let selfSignedConfig = {
host: config.host,
port: config.port,
secure: true, // use TLS
auth: {
user: config.username,
pass: config.password
},
tls: {
rejectUnauthorized: false
}
};
var transporter = nodemailer.createTransport(selfSignedConfig)
function sendRegistrationMail(to, eventTitle, name) {
var message = {
from: 'Anaadyanta Team [email protected]',
replyTo: '[email protected]',
bcc: '[email protected]',
to: to || "[email protected]",
subject: `Registration for ${eventTitle} `,
html: `
<div style="background-color:'white; padding-left: 20px; padding-top: 20px; padding-bottom: 20px; padding-right: 20px">
<h1>Hello <i>${name || "User XXX"},</i></h1>
<img alt="${eventTitle}" src="http://www.onspon.com/event/pics/1565306216whatsappimage2017-01-06at12.00.24am(1).jpeg" style="width: 100%"/>
<p>Thank you for showing interest and registering for <b>${eventTitle}</b> at Anaadyanta '17.
<p>What next</p>
<ul>
<li>Come to college atleast 1 hr prior to sheduled time.</li>
<li>Pay the registration fee at registration desk and collect your entry ticket.</li>
<li>Participate and win all prizes.</li>
</ul>
<p>Hope to see you soon</p>
<p>All the best</p>
<p>Yours <b>Team Anaadyanta</b></p>
</div>
<p style="text-align:'center'">https:github.com/priyesh9875/anaadyanta</p>
<p>Contact</p>
<p>[email protected]</p>
<p>[email protected]</p>
`,
};
transporter.sendMail(message, function (err, info) {
if (err) {
// check if htmlstream is still open and close it to clean up
Reglog.error(`Mail send error: ${eventTitle}: ${to}`)
} else {
Reglog.error(`Mail sent: ${eventTitle} -> ${to}`)
console.log(`[${moment().format()}] Mail sent: ${eventTitle} -> ${to}`)
}
});
}
function listenForRegisterationRequests() {
var requests = ref.child('registration');
Reglog.info("Listening for registrations")
console.log("Listening for registrations")
requests.on('child_added', function (requestSnapshot) {
var child = requestSnapshot.val();
// If registertion is older than 10 minutes, dont send
if (child.date > (moment().unix() - 600)) {
sendRegistrationMail(child.email, child.event, child.name)
} else {
Reglog.error(`Outdated: ${child.event} -> ${child.email}`)
console.log(`[${moment().format()}] Outdated: ${child.event} -> ${child.email}`)
}
}, function (error) {
console.log(error)
});
};
// Verify and start registertion service
transporter.verify(function (error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
listenForRegisterationRequests()
}
});
// Start FCM service
listenForNotificationRequests();
console.log("Server started")