-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotification.js
229 lines (198 loc) · 6.09 KB
/
Notification.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
'use strict';
const cheerio = require('cheerio');
const md5 = require('md5');
const log = require('npmlog');
var jsonSize = require('json-size')
//inti admin
const admin = require('firebase-admin');
let serviceAccount = process.env.service_account_key ? JSON.parse(process.env.service_account_key) : require(__dirname + '/admin.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://server-dut.firebaseio.com'
});
let db = admin.database();
let infoHP = db.ref('thong_tin_lop_hoc_phan/');
const dataRef = '/data';
const keyRef = '/key';
const MAIN_QR = '.MsoNormal';
const TITLE_QR = 'span span';
const DAY_QR = 'b span';
const REGEX_URL = /((https|http):\/\/)([\da-z\.-]+)\.([a-z\.]{0,0})([\/\w \.-\?]*)*\/?/;
const REGEX_HTTP = /[hH][tT][tT][pP]/;
const NOTI_TYPE = {
hp: "tb_lhp",
chung: "tbc"
};//["tb_lhp", "tbc"];
const TOPIC_CHUNG = "TBChung";
log.info('name', admin.app().name);
let listHP;
getListHP();
function getListHP() {
return new Promise((resolve, reject) => {
infoHP.once('value', snapshot => {
log.info('getThongTinLopHocPhan', 'ok');
listHP = snapshot.val();
resolve();
}, err => {
log.error('The read failed', err.code);
reject();
});
})
}
function textToHtml(elem) {
let $ = cheerio.load(elem);
let tagName = $(this)[0].tagName;
let text = getText($(this));
if (tagName === 'br') {
return '<br>';
}
if (!text) {
return;
}
if (tagName === 'a') {
return toTagA($(this).attr('href'), text);
}
if (!$(this).html()) {
return text;
}
text = $(this).contents()
.map(function () {
if (this.type === 'text') {
return getText($(this));
}
return textToHtml.bind(this)($.html(this));
}).get().join('');
return text;
}
function getText(elem) {
return elem.text().trim().replace(REGEX_URL, (link) => toTagA(link, link));
}
/***
* Create html code from text
* @param link {string}
* @param text {string}
* @returns {string}
*/
function toTagA(link, text) {
if (!link) {
return text;
}
link = link.replace(REGEX_HTTP, a => a.toLowerCase());
return ` <a href='${link}'>${text}</a>`;
}
function getClassCode(className, name) {
for (let topic in listHP) {
if (listHP.hasOwnProperty(topic) && topic.indexOf(className) >= 0
&& listHP[topic].tenHP.replace(/\+/g, ' ').indexOf(name.trim()) >= 0) {
//log.info('topic', topic);
return topic;
}
}
//log.error('failed', {className, name});
return '';
}
/***
* @param title {string}
*/
function getAllClass(title) {
let parts = title.split(',');
let allClass = [];
for (let part of parts) {
let regex = part.match(/\[.*?]/);
if (!regex) {
continue;
}
let className = regex[0]; // Ex: '[15.Nh71]'
let name = part.split(className)[1]; //Ex: ' Kết cấu CT (BT Thép)'
className = className.replace('[', '').replace(']', '').replace('.Nh', '_'); //Ex: '15_71'
if (name && className) {
let classCode = getClassCode(className, name);
classCode && allClass.push(classCode);
}
}
return allClass;
}
function sendNotification(noti) {
var date = new Date()
let type = NOTI_TYPE.hp;
if (noti.maHP.length === 0) {
type = NOTI_TYPE.chung;
noti.maHP.push(TOPIC_CHUNG)
}
let payload = {
data: {
timestamp: date.getTime().toString(),
thoi_gian: noti.day.replace(":", ""),
// tieu_de: noti.event,
// noi_dung: noti.content,
id: noti.key,
type: type,
screen: "main",
title: noti.event,
body: noti.content.replace(/<.*?>/g, "").replace(/<.*?>/g, "").trim()
}
};
console.log(payload);
console.log('payload size = ', jsonSize(payload))
for (let maHP of noti.maHP) {
console.log(maHP);
maHP && admin.messaging().sendToTopic(maHP, payload)
.then(res => {
log.info("Successfully sent message:", res);
})
.catch(err => {
log.error("Error sending message:", err);
});
}
}
module.exports = class Notification {
constructor(ref) {
this.dataRef = db.ref(ref).child(dataRef);
this.keyRef = db.ref(ref).child(keyRef);
}
update(raw) {
let $ = cheerio.load(raw);
let mDay = '';
let mContent = '';
let mTitle = '';
let arr = [];
let push = (day, content, event) => {
let hash = day + ':' + event + ':' + content, key = md5(hash);
content = content.trim();
if (!listHP) {
log.info('listHP', 'loading...');
throw new Error('listHP is not init')
}
let maHP = getAllClass(event);
let noti = {day, content, event, key, maHP};
this.keyRef.once('value', snapshot => {
if (snapshot.hasChild(key)) {
// log.info('exists', key);
} else {
log.info('not exists', key);
//set key
this.keyRef.child(key).set(1);
sendNotification(noti);
}
});
arr.push(noti);
};
$('body').contents()
.filter(function () {
if ($(this).not(MAIN_QR).length === 1) {
// this is content
let text = textToHtml.bind(this)($.html(this));
if (text) {
mContent += text;
}
} else {
push(mDay, mContent, mTitle);
mDay = $(this).find(DAY_QR).text();
mTitle = $(this).find(TITLE_QR).text();
mContent = '';
}
});
arr.shift();
this.dataRef.set(arr);
}
};