-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
162 lines (148 loc) · 5.01 KB
/
app.js
File metadata and controls
162 lines (148 loc) · 5.01 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
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
'use strict';
const projectId = process.env.GOOGLE_CLOUD_PROJECT;
// Preparing GCP libraries
const FEED_KIND = 'Feed';
const Datastore = require('@google-cloud/datastore');
const CloudTasks = require('@google-cloud/tasks');
const { Translate } = require('@google-cloud/translate');
// Start server
const bodyParser = require('body-parser')
const express = require('express');
const PORT = process.env.PORT || 8080;
const app = express();
app.enable('trust proxy');
app.use(bodyParser.raw());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.listen(PORT, () => {
console.info(`App listening on port ${PORT}`);
console.info('Started');
});
// Handlers
app.get('/', (_, res) => {
res.status(200).send('Hello, world!').end();
});
// README: Create task as many as the number of feeds registered in Datastore
app.post('/v1/tasks/make', async (_, res) => {
const addResult = await addFeedTask().catch((err) => res.status(500).send({ msg: 'Cloud Tasks registration failed' }).end())
res.status(200).send('success').end();
});
// README: Notify LINE when RSS is updated
app.post('/v1/tasks/notify', async (req, res) => {
const buff = new Buffer.from(req.body, 'base64');
const url = buff.toString('ascii');
const rssResult = await readRss(url).catch((err) => res.status(500).send({ msg: `RSS failed: ${err}` }).end())
let msg = 'success';
if (rssResult.isUpdated) {
const notifyResult = await notify(rssResult).catch((err) => res.status(500).send({ msg: 'Notification failed' }).end());
const updateResult = await updateLastModified(rssResult, url).catch((err) => res.status(500).send({ msg: 'Update failed' }).end());
} else {
msg = 'There is no update';
}
res.status(200).send({ msg: msg }).end();
});
// Cloud Datastore
// README: Read multiple feed urls
async function addFeedTask() {
const datastore = new Datastore({
projectId: projectId,
});
const query = datastore.createQuery('Feed')
const results = await datastore.runQuery(query)
const feeds = results[0]
feeds.forEach(feed => {
addTask(feed.url)
})
}
// Cloud Tasks
// README: Make a task
async function addTask(url) {
const client = new CloudTasks.CloudTasksClient();
const options = { payload: url };
const task = {
appEngineHttpRequest: {
httpMethod: 'POST',
relativeUri: '/v1/tasks/notify',
},
};
task.appEngineHttpRequest.body = Buffer.from(options.payload).toString(
'base64'
);
const queue = 'notify-queue';
const location = 'us-central1';
const parent = client.queuePath(projectId, location, queue);
const request = {
parent: parent,
task: task,
};
return client.createTask(request)
}
// README: Read RSS and flag it when there is an update
async function readRss(url) {
const Parser = require('rss-parser');
const parser = new Parser();
const feed = await parser.parseURL(url);
const originalText = feed.items[0].contentSnippet.replace(/(\r\n\t|\n|\r\t)/gm, "");
const date = feed.items[0].isoDate;
let response = {
text: originalText,
translation: '',
link: feed.items[0].link,
key: '', //Feed Key
isUpdated: false,
date: date,
}
// Get RSS Last Acquisition Date
const datastore = new Datastore({
projectId: projectId,
});
const query = datastore.createQuery('Feed').filter('url', '=', url);
const datastoreResults = await datastore.runQuery(query);
//If RSS is updated, create responses for updated content and translated text
const isUpdated = Date.parse(date.toString()) > Date.parse(datastoreResults[0][0].date.toString());
if (isUpdated) {
const translate = new Translate({
projectId: projectId,
});
let translateResult = await translate.translate(originalText, 'ja')
if (!translateResult.err) {
response.key = datastoreResults[0][0][datastore.KEY];
response.translation = translateResult[0];
response.isUpdated = true;
}
}
return response
}
// README: Notify LINE
async function notify(rssResult) {
const auth = process.env.LINE_AUTHORIZATION;
let request = require('request');
let options = {
url: 'https://notify-api.line.me/api/notify',
method: 'POST',
headers: {
'Authorization': 'Bearer ' + auth
},
json: true,
form: { 'message': '' }
}
options.form.message = rssResult.text + "\n\n\n" + rssResult.translation + "\n\n" + rssResult.link;
request(options, function (error, response, body) {
return body
})
}
// README: Save the last read date
async function updateLastModified(rssResult, url) {
const datastore = new Datastore({
projectId: projectId,
});
const feed = {
key: rssResult.key,
data: {
date: new Date(),
url: url,
},
};
return await datastore.save(feed)
}