-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHessen Way.js
297 lines (259 loc) · 9.14 KB
/
Hessen Way.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
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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: blue; icon-glyph: subway; share-sheet-inputs: plain-text;
/* eslint-disable require-await */
/* eslint-disable no-undef */
// Version 1.1.0
// Instructions
//
// When running the widget for the first time you need to setup an access key from RMV.
// In case you don't have one request one here: https://opendata.rmv.de/site/anmeldeseite.html
// It might take a few hours for you to receive your key in the email.
//
// When adding a widget to the screen add the station you are looking for as a parameter.
// You can get the station id by using https://www.rmv.de/hapi/location.name?format=json&accessId=<API_KEY>&input=<LOCATION>
// and replacing <API_KEY> by your key and <LOCATION> by the name of the station you are looking for.
// In the response look for the extId field.
//
// More detailed instructions can be found here: https://github.com/Nahoot/HessenWay
//
// ANY CHANGE BELOW THIS POINT IS AT YOUR OWN RISK
// ---------------------------------------------------------
// Init constants
// Layout configuration
const widgetBackgroundColor = "#222222";
const widgetPadding = 10;
const titleTextSize = 14;
const bodyTextSize = 10;
const numberOfLines = { "small": 5, "medium": 10, "large": 24 };
// ---------------------------------------------------------
const small = "small"; medium = "medium"; large = "large";
const baseURL = 'https://www.rmv.de';
const departuresURL = '/hapi/departureBoard?lang=en&format=json&accessId=';
const rmvAccessKey = 'hessenway.rmv.api.key';
// Default station to look for.
// The station's id to be used when the script is run in the app.
// if it's executed from the widget it should be passed as parameter.
// If it doesn't it will default to the value below
let extId = args.widgetParameter
if(extId == null)
extId = "3000010" // Hauptbahnhof
// ---------------------------------------------------------
// Base functions
async function getRMVDepartures(departureStationCode){
const result = {};
const resp = await get({
url: baseURL + departuresURL + Keychain.get(rmvAccessKey) + '&extId=' + departureStationCode
})
result.origin = resp.Departure[0].stop;
result.departures = resp.Departure;
return result;
}
function getTransportationsSortedByTime(departures){
let transports = [];
departures.forEach(function(obj){
//console.log(obj.name)
const transport = {};
// Get tranport type (bus, train, subway, etc..)
transport.category = obj.Product[0].catOut.trim();
// 2DO: Replace the text with the image directly
// Get transport time. Always gets scheduled time. If the transport is delayed and there is "real time" use it instead
// In the end turn the time string into a date object
let time = obj.time;
if ("rtTime" in obj){
time = obj.rtTime
}
transport.time = formatTime(time);
// Gets the line code (ex: S5, U3, RE70). Adds empty spaces for visualization in the table.
// 2DO: Remove the spaces from here and move them to "printing" code
transport.name = obj.name.trim().padEnd(6, String.fromCodePoint(0x2007)).padEnd(7, ' ')
// Gets the transport's final destination
transport.destination = obj.direction.trim();
transports.push(transport);
})
return transports.sort(function (a, b){
return a.time.getTime() - b.time.getTime();
})
}
function printWidgetHeader(widget, origin, widgetSize = medium){
if(widgetSize == small){
if(origin.startsWith("Frankfurt (Main) ")){
origin = origin.replace("Frankfurt (Main) ", '');
}
}
let titleStack = widget.addStack()
titleStack.centerAlignContent()
titleStack.addSpacer()
let titleText = titleStack.addText(origin)
titleText.centerAlignText()
titleText.font = Font.boldSystemFont(titleTextSize)
titleText = Color.white()
titleStack.addSpacer()
}
function printWidgetBody(widget, departures, widgetSize = medium){
// console.log(departures)
var BreakException = {}
let resultNumber = numberOfLines[widgetSize];
try {
departures.forEach(function(obj){
let entryStack = widget.addStack()
entryStack.layoutHorizontally()
let cat = obj.category;
let img = SFSymbol.named("bus.fill")
if (cat == "Tram")
img = SFSymbol.named("tram.circle")
if (cat == "S")
img = SFSymbol.named("tram")
if (cat == "RE")
img = SFSymbol.named("tram.fill")
img.applyThinWeight()
// Make this work
// const bus = entryStack.addImage(images[obj.category].applyThinWeight());
const bus = entryStack.addImage(img.image)
bus.tintColor = Color.white()
bus.imageSize = new Size(bodyTextSize, bodyTextSize)
bus.leftAlignImage()
entryStack.addSpacer(10)
let date = entryStack.addDate(obj.time)
date.applyTimeStyle()
date.font = Font.thinMonospacedSystemFont(bodyTextSize)
entryStack.addSpacer(10)
let train = entryStack.addText(obj.name);
train.font = Font.thinMonospacedSystemFont(bodyTextSize)
entryStack.addSpacer(10)
// If the widget is small we change lines
if(widgetSize == small){
entryStack = widget.addStack();
entryStack.addSpacer(20);
}
let direction = entryStack.addText(obj.destination)
direction.font = Font.thinMonospacedSystemFont(bodyTextSize)
entryStack.addSpacer()
if (!--resultNumber)
throw BreakException;
}
)
} catch (e){
if (e !== BreakException) throw e
}
}
async function buildWidget(widget, departureStationCode, widgetSize){
widget.setPadding(widgetPadding, widgetPadding, widgetPadding, widgetPadding)
widget.backgroundColor = new Color(widgetBackgroundColor)
if(!Keychain.contains(rmvAccessKey)){
// Generate Widget visualization
let titleText = widget.addText("The key was not found. Please follow the instructions to obtain a key from RMV and add it in the configuration.")
titleText.centerAlignText()
titleText.font = Font.boldSystemFont(titleTextSize)
titleText.textColor = Color.red()
}else if(!departureStationCode){
// Generate Widget visualization
let titleText = widget.addText("No parameter was given. Follow the instructions to configure a departure station.");
titleText.centerAlignText()
titleText.font = Font.boldSystemFont(titleTextSize)
titleText.textColor = Color.red()
}
else {
let result = await getRMVDepartures(departureStationCode);
let transports = getTransportationsSortedByTime(result.departures);
printWidgetHeader(widget, result.origin, widgetSize);
printWidgetBody(widget, transports, widgetSize);
}
}
// ---------------------------------------------------------
// Helper functions
function formatTime(sTime){
const arrTime = sTime.split(':')
let time = new Date()
time.setHours(arrTime[0], arrTime[1], 0, 0)
return time
}
async function get(opts) {
const request = new Request(opts.url)
request.headers = {
...opts.headers,
...this.defaultHeaders
}
var result=await request.loadJSON()
// console.log(result)
return result
}
async function promptForKey(){
let alert = new Alert();
alert.title = "API key";
alert.message = "Paste below the API key you have received from RMV.";
alert.addTextField("d9z9zz50-dd9d-459d-b0f8-d514e455d386");
alert.addAction("OK");
alert.addCancelAction("Cancel");
alert.addDestructiveAction("Delete key!")
let idx = await alert.present();
if(idx == 0){
Keychain.set(rmvAccessKey, alert.textFieldValue(0));
}
if(idx == 1){
Keychain.remove(rmvAccessKey);
}
}
async function showWidgetPreview(){
let idx = 0;
do{
let alert = new Alert();
alert.title = "Widget size";
alert.addAction("Small");
alert.addAction("Medium");
alert.addAction("Large");
alert.addCancelAction("Back");
idx = await alert.present();
switch(idx){
case 0:
widget = new ListWidget();
await buildWidget(widget, extId, small);
await widget.presentSmall();
break;
case 1:
widget = new ListWidget();
await buildWidget(widget, extId, medium);
await widget.presentMedium();
break;
case 2:
widget = new ListWidget();
await buildWidget(widget, extId, large);
await widget.presentLarge();
break;
default:
break;
}
}while(idx != -1);
}
// ---------------------------------------------------------
if(config.runsInApp){
let idx = 0;
do{
let alert = new Alert();
alert.title = "Widget options";
alert.addAction("Enter API key");
alert.addAction("Show widget");
//alert.addAction("Update widget");
alert.addCancelAction("Exit menu");
idx = await alert.present();
switch(idx){
case 0:
await promptForKey();
break;
case 1:
await showWidgetPreview();
break;
case 2:
// 2DO: Update widget automatically
break;
default:
break;
}
}while(idx != -1);
}
else{
const widget = new ListWidget();
await buildWidget(widget, args.widgetParameter, config.widgetFamily);
Script.setWidget(widget);
}
Script.complete();