-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode_helper.js
29 lines (23 loc) · 6.66 KB
/
node_helper.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
/*! *****************************************************************************
mmm-rnv
Version 1.2.0
This is a departure monitor for the Rhein-Neckar-Verkehr (RNV) public transport network for the MagicMirror² platform.
Please submit bugs at https://github.com/jalibu/MMM-RNV/issues
(c) Julian Dinter,Jan Litzenburger
Licence: MIT
This file is auto-generated. Do not edit.
***************************************************************************** */
"use strict";var e=require("node_helper"),t=require("apollo-client"),n=require("apollo-cache-inmemory"),i=require("apollo-link-http"),o=require("apollo-link-context"),r=require("graphql-tag"),s=require("node-fetch"),a=require("logger");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function c(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var u=c(e),d=l(r),h=l(s),p=c(a);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function f(e,t,n,i){return new(n||(n=Promise))((function(o,r){function s(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((i=i.apply(e,t||[])).next())}))}module.exports=u.create({start(){this.client=null,this.schedule=[],this.colorCodes=[],this.failedRequests=0,this.getColorCodes()},getColorCodes(){return f(this,void 0,void 0,(function*(){try{const e=yield h.default("https://rnvopendataportalpublic.blob.core.windows.net/public/openDataPortal/liniengruppen-farben.json"),t=yield e.json();this.colorCodes=t.lineGroups}catch(e){p.warn("Could not request color codes",e)}}))},socketNotificationReceived(e,t){return f(this,void 0,void 0,(function*(){if("RNV_DEPARTURE_REQUEST"===e){const e=t;this.getData(e)}}))},getData(e){return f(this,void 0,void 0,(function*(){try{if(!this.client)try{this.client=yield this.createClient(e)}catch(e){return p.error(`Error generating the client: ${e.message}`),void this.sendSocketNotification("RNV_ERROR_RESPONSE",{type:"WARNING",message:"Error with API authentication."})}const t=new Date(Date.now()+e.walkingTimeMs);p.info(`Request departures for station '${e.stationId}'`);const n=`query {\n station(id:"${e.stationId}") {\n hafasID\n longName\n journeys(startTime: "${t.toISOString()}" first: 50) {\n totalCount\n elements {\n ... on Journey {\n line {\n id\n }\n type\n stops(onlyHafasID: "${e.stationId}") {\n pole {\n platform {\n type\n label\n barrierFreeType\n }\n }\n destinationLabel\n plannedArrival {\n isoString\n }\n realtimeArrival {\n isoString\n }\n plannedDeparture {\n isoString\n }\n realtimeDeparture {\n isoString\n }\n }\n }\n }\n }\n }\n }`,i=[],o=(yield this.client.query({query:d.default(n)})).data.station.journeys.elements.filter((e=>null!==e.stops[0].plannedDeparture.isoString));o.sort(((e,t)=>{const n=e.stops[0].plannedDeparture.isoString,i=t.stops[0].plannedDeparture.isoString;return n<i?-1:n>i?1:0}));for(const t of o){const n=new Date(t.stops[0].plannedDeparture.isoString);let o=0;try{const e=new Date(t.stops[0].realtimeDeparture.isoString),i=Math.abs(n.getMilliseconds()-e.getMilliseconds());o=Math.floor(i/60*1e3)}catch(e){p.warn(`Error calculating the delay: ${e.message}`)}const r=t.line.id.split("-")[1];if(e.excludeLines.includes(r)||e.excludePlatforms.includes(t.stops[0].pole.platform.label))continue;const s={line:r,destination:t.stops[0].destinationLabel,departure:n.getTime(),delayInMin:o,platform:t.stops[0].pole.platform.label,type:t.type,highlighted:e.highlightLines.includes(r),color:this.colorCodes.find((e=>e.id===r))};if(i.push(s),i.length===e.maxResults)break}this.failedRequests=0,this.sendSocketNotification(`RNV_DATA_RESPONSE_${e.stationId}`,i)}catch(e){p.warn(`Error fetching the data from the API: ${e.message}`),this.failedRequests+=1,this.failedRequests>5&&(this.client=null,p.log("Reset the RNV API client"),this.sendSocketNotification("RNV_ERROR_RESPONSE",{type:"WARNING",message:"Error fetching data."}))}}))},createClient(e){return f(this,void 0,void 0,(function*(){const{clientId:r,clientSecret:s,resourceId:a,tenantId:l}=e.credentials,c=yield h.default(`https://login.microsoftonline.com/${l}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=client_credentials&client_id=${r}&client_secret=${s}&resource=${a}`});if(!c.ok)throw Error(`Could not fetch the access token (${c.status} ${c.statusText})`);const{access_token:u}=yield c.json();p.log("Created new RNV API access token");const d=i.createHttpLink({uri:e.clientApiUrl,fetch:h.default}),g=o.setContext(((e,{headers:t})=>f(this,void 0,void 0,(function*(){return{headers:Object.assign(Object.assign({},t),{authorization:u?`Bearer ${u}`:null})}}))));return new t.ApolloClient({link:g.concat(d),cache:new n.InMemoryCache})}))}});