-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_traffic.ts
314 lines (267 loc) · 8.34 KB
/
get_traffic.ts
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// eslint-disable-next-line @typescript-eslint/no-var-requires
require("dotenv").config();
import Axios from "axios";
import * as B from "bluebird";
import * as Cron from "cron";
import * as fs from "fs";
import * as Twilio from "twilio";
import { getTime, isFuture } from "date-fns";
const readFileAsync: (
name: string,
encoding: string
// eslint-disable-next-line @typescript-eslint/no-var-requires
) => Promise<any> = B.promisify(require("fs").readFile);
const writeFileAsync: (
name: string,
contents: string,
encoding: string
// eslint-disable-next-line @typescript-eslint/no-var-requires
) => Promise<any> = B.promisify(require("fs").writeFile);
interface Location {
Latitude: string;
Longitude: string;
}
interface AlertObject {
AlertId: string;
AlertIcon: string;
Description: string;
Direction: string;
EndMileMarker?: string;
Headline: string;
Impact: string;
IsBothDirectionFlg: string;
LastUpdatedDate: string;
Location?: Location;
LocationDescription: string;
RoadId: string;
RoadName: string;
RoadwayClosure: string;
RoadwayClosureId: string;
ReportedTime: string;
StartMileMarker: string;
Title: string;
Type: string;
TypeId: string;
}
interface AlertsResponse {
Alerts: {
Alert: AlertObject[];
};
}
async function getTrafficData(): Promise<AlertObject[]> {
const closuresData = await Axios.get<AlertsResponse>(
"https://www.cotrip.org/roadConditions/getLaneClosureAlerts.do"
);
return closuresData.data.Alerts.Alert;
}
const analyticsDirectory = "./analytics";
const roadDataFileName = "./roaddata.json";
const subscriptionsFileName = "./numbers.json";
const archiveDirectory = "./archive";
interface Subscription {
number: string;
expiration: string;
}
function readSubscriptionsFile(): Promise<Subscription[] | null> {
return readFileAsync(subscriptionsFileName, "utf8")
.then(JSON.parse)
.catch(() => {
return null;
});
}
function readJSONFile(): Promise<AlertObject[] | null> {
return readFileAsync(roadDataFileName, "utf8")
.then(JSON.parse)
.catch(() => {
return null;
});
}
function saveAnalytics(action: string, payload): Promise<any> {
const time = getTime(new Date());
const fileName = `${analyticsDirectory}/${time}.json`;
const contents = JSON.stringify({
action,
time,
payload: payload || null,
});
return writeFileAsync(fileName, contents, "utf8");
}
async function sendMessages(
messages: string[],
users?: Subscription[]
): Promise<any> {
if (!users || users.length === 0) return;
const client = Twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
const textPromises = messages.reduce((acc, m) => {
return [
...acc,
...users.map((u) =>
client.messages.create({
body: m,
from: "+14342267669",
to: u.number,
})
),
];
}, []);
await saveAnalytics("SEND_MESSAGES", {
count: textPromises.length,
messages,
});
return B.all(textPromises).catch((err) => {
console.error("Caught an error trying to send a message", err);
});
}
function writeToNumbersFile(
updatedSubscriptions: Subscription[]
): Promise<any> {
return writeFileAsync(
subscriptionsFileName,
JSON.stringify(updatedSubscriptions),
"utf8"
);
}
function writeToJSONFile(
updatedClosures: AlertObject[],
savedClosures?: AlertObject[]
): Promise<any> {
return writeFileAsync(
roadDataFileName,
JSON.stringify(updatedClosures),
"utf8"
).then(() => {
if (savedClosures) {
const timeStamp = new Date().toISOString();
return writeFileAsync(
`${archiveDirectory}/${timeStamp}-road-closures.json`,
JSON.stringify(updatedClosures),
"utf8"
);
}
});
}
function filterOpenings(closure: AlertObject) {
const northLatBoundary = 40.517692;
const southLatBoundary = 39.084296;
const westLongBoundary = -107.399081;
const eastLongBoundary = -105.128684;
const roadIdBlacklist = [
"40", // US 36
"1", // C-470 (somehow got #1 id)
];
const roadInBlacklist = roadIdBlacklist.includes(closure.RoadId);
if (!closure || !closure.Location || roadInBlacklist) {
return false;
}
const { Latitude, Longitude } = closure.Location;
const lat = parseFloat(Latitude);
const long = parseFloat(Longitude);
const inLatBounds = lat >= southLatBoundary && lat <= northLatBoundary;
const inLongBounds = long >= westLongBoundary && long <= eastLongBoundary;
return inLatBounds && inLongBounds;
}
async function checkTrafficClosures() {
return B.all([readJSONFile(), getTrafficData()])
.then(async ([savedClosures, updatedStateClosures]) => {
const updatedClosures = updatedStateClosures.filter(filterOpenings);
if (!savedClosures) {
console.log(`Generating new ${roadDataFileName} file.`);
return writeToJSONFile(updatedClosures);
}
const savedClosureAlertIds = savedClosures.map(
(c: AlertObject) => c.AlertId
);
const updatedClosureAlertIds = updatedClosures.map(
(c: AlertObject) => c.AlertId
);
const newClosures = updatedClosures.filter((closure: AlertObject) => {
return !savedClosureAlertIds.includes(closure.AlertId);
});
const newOpenings = savedClosures.filter((closure: AlertObject) => {
return !updatedClosureAlertIds.includes(closure.AlertId);
});
const timeStamp = new Date().toISOString();
let updates = [];
if (newClosures) {
updates = newClosures.map((c) => {
const directionText =
c.IsBothDirectionFlg === "true"
? "in both directions"
: `going ${c.Direction}`;
const mileMarkerText = c.EndMileMarker
? `from mile marker ${c.StartMileMarker} to ${c.EndMileMarker}`
: `at mile marker ${c.StartMileMarker}`;
const severity = c.RoadwayClosureId === "4" ? "(full)" : "(partial)";
const locationDescription = ` (${c.LocationDescription})` || "";
const textMessage = `New ${severity} closure on ${c.RoadName} ${directionText} ${mileMarkerText}${locationDescription}. From CODOT: ${c.Description}`;
console.log(`${timeStamp}: ${textMessage}`);
return textMessage;
});
}
if (newOpenings) {
updates = [
...updates,
...newOpenings.map((c) => {
const directionText =
c.IsBothDirectionFlg === "true"
? "in both directions"
: `going ${c.Direction}`;
const mileMarkerText = c.EndMileMarker
? `from mile marker ${c.StartMileMarker} to ${c.EndMileMarker}`
: `at mile marker ${c.StartMileMarker}`;
const locationDescription = ` (${c.LocationDescription})` || "";
const textMessage = `Road reopened on ${c.RoadName} ${directionText} ${mileMarkerText}${locationDescription}.`;
console.log(`${timeStamp}: ${textMessage}`);
return textMessage;
}),
];
}
const changePresent =
(newOpenings && newOpenings.length !== 0) ||
(newClosures && newClosures.length !== 0);
if (!changePresent) {
console.log(`${timeStamp}: No new closures or openings`);
return writeToJSONFile(updatedClosures);
}
const subscriptions = await readSubscriptionsFile();
const validSubs = subscriptions.filter((sub) =>
isFuture(new Date(sub.expiration))
);
await writeToNumbersFile(validSubs);
await sendMessages(updates, validSubs);
return writeToJSONFile(updatedClosures, savedClosures);
})
.catch((err) => {
console.error("Encountered error fetching new data");
console.error(err);
});
}
async function startJob() {
console.log("starting job");
try {
await fs.promises.mkdir(archiveDirectory);
console.log("created archive directory");
} catch (err) {
console.log("archive directory already exists");
}
try {
await fs.promises.mkdir(analyticsDirectory);
console.log("created analytics directory");
} catch (err) {
console.log("analytics directory already exists");
}
const cronPattern = "*/1 * * * *";
const job = new Cron.CronJob(
cronPattern,
function () {
return checkTrafficClosures();
},
null,
true
);
console.log("job started with cron pattern", cronPattern);
}
startJob();