Bump wersji

This commit is contained in:
2022-08-27 20:19:03 +02:00
parent 6dd8cb2dad
commit 03950eef66
3 changed files with 686 additions and 686 deletions
+287 -287
View File
@@ -1,287 +1,287 @@
<template>
<div class="train-info" tabindex="0">
<section class="train-route">
<div class="train_general">
<span>
<span class="timetable-id" v-if="train.timetableData">#{{ train.timetableData.timetableId }}</span>
<span class="timetable_warnings">
<span class="train-badge twr" v-if="train.timetableData?.TWR">TWR</span>
<span class="train-badge skr" v-if="train.timetableData?.SKR">SKR</span>
</span>
<strong v-if="train.timetableData">{{ train.timetableData.category }}&nbsp;</strong>
<strong>{{ train.trainNo }}</strong>
<span>&nbsp;| {{ train.driverName }}&nbsp;</span>
</span>
</div>
<div class="timetable_route" v-if="train.timetableData">
<strong>{{ train.timetableData.route.replace('|', ' - ') }}</strong>
<img
v-if="getSceneriesWithComments(train.timetableData).length > 0"
class="image-warning"
:src="getIcon('warning')"
:title="`${$t('trains.timetable-comments')} (${getSceneriesWithComments(train.timetableData)})`"
/>
</div>
<hr style="margin: 0.25em 0" />
<div class="timetable_stops" v-if="train.timetableData">
<span v-if="train.timetableData.followingStops.length > 2">
{{ $t('trains.via-title') }}
<span v-html="displayStopList(train.timetableData.followingStops)"></span>
</span>
</div>
<div class="timetable_progress" style="margin-top: 0.5em" v-if="train.timetableData">
<!-- <span> </span> -->
<span class="timetable_progress-bar">
<!-- {{ confirmedPercentage(train.timetableData.followingStops) }}%&nbsp; -->
<span class="bar-bg"></span>
<span
class="bar-fg"
:style="{ width: `${Math.floor(confirmedPercentage(train.timetableData.followingStops))}%` }"
></span>
</span>
<span class="timetable_progress-distance">
&nbsp; {{ currentDistance(train.timetableData.followingStops) }} km /
<span class="text--primary"> {{ train.timetableData.routeDistance }} km </span>
|
<span v-html="currentDelay(train.timetableData.followingStops)"></span>
</span>
<div class="train-status-badges">
<div v-if="!train.currentStationHash" class="train-badge offline">{{ $t('trains.scenery-offline') }}</div>
<div v-if="!train.online" class="train-badge offline">Offline {{ lastSeenMessage(train.lastSeen) }}</div>
</div>
</div>
<div class="driver_position text--grayed" style="margin-top: 0.25em">
{{ displayTrainPosition(train) }}
</div>
</section>
<section class="train-stats">
<div>
<img :src="train.locoURL" loading="lazy" alt="Loco image not found" @error="onImageError" />
</div>
<div class="text--grayed">
{{ train.locoType }}
<span v-if="train.cars.length > 0">
&nbsp;&bull; {{ $t('trains.cars') }}:
<span class="count">{{ train.cars.length }}</span>
</span>
</div>
<div>
<span v-for="(stat, i) in STATS.main" :key="stat.name">
<span v-if="i > 0"> &bull; </span>
<span>{{ `${~~((train as any)[stat.name] * (stat.multiplier || 1))}${stat.unit}` }} </span>
</span>
</div>
</section>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import imageMixin from '../../mixins/imageMixin';
import trainInfoMixin from '../../mixins/trainInfoMixin';
import Train from '../../scripts/interfaces/Train';
export default defineComponent({
props: {
train: {
type: Object as () => Train,
required: true,
},
extended: {
type: Boolean,
default: true,
},
},
mixins: [trainInfoMixin, imageMixin],
});
</script>
<style lang="scss" scoped>
@import '../../styles/responsive.scss';
.image-warning {
height: 1em;
margin-left: 0.5em;
}
.train-stats {
display: flex;
justify-content: center;
align-content: center;
flex-direction: column;
text-align: center;
img {
margin: 0.5em 0;
width: 12em;
}
}
.train-info {
display: grid;
grid-template-columns: 2fr 1fr;
grid-template-rows: 1fr;
padding: 1em;
background-color: #1a1a1a;
gap: 0.5em;
}
.timetable-id {
margin-right: 0.3em;
color: #d2d2d2;
}
.timetable_stops {
font-size: 0.75em;
}
.train_general {
display: flex;
align-items: center;
flex-wrap: wrap;
}
.train-status-badges {
display: flex;
flex-wrap: wrap;
}
.train-badge {
padding: 0.15em 0.35em;
margin-right: 0.3em;
font-weight: bold;
font-size: 0.9em;
&.twr {
background-color: var(--clr-twr);
}
&.skr {
background-color: var(--clr-skr);
}
&.offline {
background-color: #b83b2d;
}
}
.timetable_route {
display: flex;
align-items: center;
margin-top: 0.5em;
}
.timetable_warnings {
color: black;
}
.timetable_progress {
display: flex;
align-items: center;
flex-wrap: wrap;
}
.timetable_progress-bar {
position: relative;
width: 6em;
height: 1em;
margin: 0.5em 0;
.bar-fg,
.bar-bg {
position: absolute;
height: 1em;
width: 100%;
left: 0;
}
.bar-fg {
background-color: springgreen;
}
.bar-bg {
background-color: #5b5b5b;
}
}
.timetable_progress-distance {
margin-right: 0.25em;
}
.comments {
display: flex;
align-items: center;
font-size: 0.9em;
margin-top: 1em;
img {
margin-right: 0.5em;
}
}
@include smallScreen() {
.train-info {
grid-template-columns: 1fr;
gap: 1em 0;
text-align: center;
font-size: 1.15em;
}
.train-stats {
font-size: 1.1em;
img {
display: none;
}
}
.train_general {
justify-content: center;
}
.train-status-badges {
justify-content: center;
}
.timetable_route {
justify-content: center;
}
.timetable_progress {
justify-content: center;
}
.comments {
flex-direction: column;
justify-content: center;
img {
margin: 0 0 0.5em 0;
}
}
}
</style>
<template>
<div class="train-info" tabindex="0">
<section class="train-route">
<div class="train_general">
<span>
<span class="timetable-id" v-if="train.timetableData">#{{ train.timetableData.timetableId }}</span>
<span class="timetable_warnings">
<span class="train-badge twr" v-if="train.timetableData?.TWR">TWR</span>
<span class="train-badge skr" v-if="train.timetableData?.SKR">SKR</span>
</span>
<strong v-if="train.timetableData">{{ train.timetableData.category }}&nbsp;</strong>
<strong>{{ train.trainNo }}</strong>
<span>&nbsp;| {{ train.driverName }}&nbsp;</span>
</span>
</div>
<div class="timetable_route" v-if="train.timetableData">
<strong>{{ train.timetableData.route.replace('|', ' - ') }}</strong>
<img
v-if="getSceneriesWithComments(train.timetableData).length > 0"
class="image-warning"
:src="getIcon('warning')"
:title="`${$t('trains.timetable-comments')} (${getSceneriesWithComments(train.timetableData)})`"
/>
</div>
<hr style="margin: 0.25em 0" />
<div class="timetable_stops" v-if="train.timetableData">
<span v-if="train.timetableData.followingStops.length > 2">
{{ $t('trains.via-title') }}
<span v-html="displayStopList(train.timetableData.followingStops)"></span>
</span>
</div>
<div class="timetable_progress" style="margin-top: 0.5em" v-if="train.timetableData">
<!-- <span> </span> -->
<span class="timetable_progress-bar">
<!-- {{ confirmedPercentage(train.timetableData.followingStops) }}%&nbsp; -->
<span class="bar-bg"></span>
<span
class="bar-fg"
:style="{ width: `${Math.floor(confirmedPercentage(train.timetableData.followingStops))}%` }"
></span>
</span>
<span class="timetable_progress-distance">
&nbsp; {{ currentDistance(train.timetableData.followingStops) }} km /
<span class="text--primary"> {{ train.timetableData.routeDistance }} km </span>
|
<span v-html="currentDelay(train.timetableData.followingStops)"></span>
</span>
<div class="train-status-badges">
<div v-if="!train.currentStationHash" class="train-badge offline">{{ $t('trains.scenery-offline') }}</div>
<div v-if="!train.online" class="train-badge offline">Offline {{ lastSeenMessage(train.lastSeen) }}</div>
</div>
</div>
<div class="driver_position text--grayed" style="margin-top: 0.25em">
{{ displayTrainPosition(train) }}
</div>
</section>
<section class="train-stats">
<div>
<img :src="train.locoURL" loading="lazy" alt="Loco image not found" @error="onImageError" />
</div>
<div class="text--grayed">
{{ train.locoType }}
<span v-if="train.cars.length > 0">
&nbsp;&bull; {{ $t('trains.cars') }}:
<span class="count">{{ train.cars.length }}</span>
</span>
</div>
<div>
<span v-for="(stat, i) in STATS.main" :key="stat.name">
<span v-if="i > 0"> &bull; </span>
<span>{{ `${~~((train as any)[stat.name] * (stat.multiplier || 1))}${stat.unit}` }} </span>
</span>
</div>
</section>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import imageMixin from '../../mixins/imageMixin';
import trainInfoMixin from '../../mixins/trainInfoMixin';
import Train from '../../scripts/interfaces/Train';
export default defineComponent({
props: {
train: {
type: Object as () => Train,
required: true,
},
extended: {
type: Boolean,
default: true,
},
},
mixins: [trainInfoMixin, imageMixin],
});
</script>
<style lang="scss" scoped>
@import '../../styles/responsive.scss';
.image-warning {
height: 1em;
margin-left: 0.5em;
}
.train-stats {
display: flex;
justify-content: center;
align-content: center;
flex-direction: column;
text-align: center;
img {
margin: 0.5em 0;
width: 12em;
}
}
.train-info {
display: grid;
grid-template-columns: 2fr 1fr;
grid-template-rows: 1fr;
padding: 1em;
background-color: #1a1a1a;
gap: 0.5em;
}
.timetable-id {
margin-right: 0.3em;
color: #d2d2d2;
}
.timetable_stops {
font-size: 0.75em;
}
.train_general {
display: flex;
align-items: center;
flex-wrap: wrap;
}
.train-status-badges {
display: flex;
flex-wrap: wrap;
}
.train-badge {
padding: 0.15em 0.35em;
margin-right: 0.3em;
font-weight: bold;
font-size: 0.9em;
&.twr {
background-color: var(--clr-twr);
}
&.skr {
background-color: var(--clr-skr);
}
&.offline {
background-color: #b83b2d;
}
}
.timetable_route {
display: flex;
align-items: center;
margin-top: 0.5em;
}
.timetable_warnings {
color: black;
}
.timetable_progress {
display: flex;
align-items: center;
flex-wrap: wrap;
}
.timetable_progress-bar {
position: relative;
width: 6em;
height: 1em;
margin: 0.5em 0;
.bar-fg,
.bar-bg {
position: absolute;
height: 1em;
width: 100%;
left: 0;
}
.bar-fg {
background-color: springgreen;
}
.bar-bg {
background-color: #5b5b5b;
}
}
.timetable_progress-distance {
margin-right: 0.25em;
}
.comments {
display: flex;
align-items: center;
font-size: 0.9em;
margin-top: 1em;
img {
margin-right: 0.5em;
}
}
@include smallScreen() {
.train-info {
grid-template-columns: 1fr;
gap: 1em 0;
text-align: center;
font-size: 1.15em;
}
.train-stats {
font-size: 1.1em;
img {
display: none;
}
}
.train_general {
justify-content: center;
}
.train-status-badges {
justify-content: center;
}
.timetable_route {
justify-content: center;
}
.timetable_progress {
justify-content: center;
}
.comments {
flex-direction: column;
justify-content: center;
img {
margin: 0 0 0.5em 0;
}
}
}
</style>
+398 -398
View File
@@ -1,398 +1,398 @@
import axios from 'axios';
import { defineStore } from 'pinia';
import { io } from 'socket.io-client';
import { DataStatus } from '../scripts/enums/DataStatus';
import StationAPIData from '../scripts/interfaces/api/StationAPIData';
import ScheduledTrain from '../scripts/interfaces/ScheduledTrain';
import Station from '../scripts/interfaces/Station';
import StationRoutes from '../scripts/interfaces/StationRoutes';
import Train from '../scripts/interfaces/Train';
import { URLs } from '../scripts/utils/apiURLs';
import {
getLocoURL,
getStatusTimestamp,
getStatusID,
getScheduledTrain,
parseSpawns,
} from '../scripts/utils/storeUtils';
import { APIData, StationJSONData, StoreState } from './storeTypes';
export const useStore = defineStore('store', {
state: () =>
({
apiData: {} as unknown,
stationList: [],
trainList: [],
sceneryData: [],
lastDispatcherStatuses: [],
region: { id: 'eu', value: 'PL1' },
trainCount: 0,
stationCount: 0,
webSocket: undefined,
dispatcherStatsName: '',
dispatcherStatsData: undefined,
driverStatsName: '',
driverStatsData: undefined,
chosenModalTrainId: undefined,
dataStatuses: {
connection: DataStatus.Loading,
sceneries: DataStatus.Loading,
timetables: DataStatus.Loading,
dispatchers: DataStatus.Loading,
trains: DataStatus.Loading,
},
listenerLaunched: false,
} as StoreState),
actions: {
setTrainsOnlineData() {
const { trains } = this.apiData;
if (!trains) return [];
this.trainList = trains
.filter(
(train) =>
train.region === this.region.id && (train.online || train.timetable || train.lastSeen > Date.now() - 180000)
)
.map((train) => {
const stock = train.stockString.split(';');
const locoType = stock ? stock[0] : train.stockString;
const timetable = train.timetable;
return {
trainId: train.driverName + train.trainNo.toString(),
trainNo: train.trainNo,
mass: train.mass,
length: train.length,
speed: train.speed,
region: train.region,
distance: train.distance,
signal: train.signal,
online: train.online,
driverId: train.driverId,
driverName: train.driverName,
currentStationName: train.currentStationName,
currentStationHash: train.currentStationHash,
connectedTrack: train.connectedTrack,
locoType,
locoURL: getLocoURL(locoType),
cars: stock.slice(1),
lastSeen: train.lastSeen,
timetableData: timetable
? {
timetableId: timetable.timetableId,
SKR: timetable.SKR,
TWR: timetable.TWR,
route: timetable.route,
category: timetable.category,
followingStops: timetable.stopList,
routeDistance: timetable.stopList[timetable.stopList.length - 1].stopDistance,
sceneries: timetable.sceneries,
}
: undefined,
};
}) as Train[];
},
getDispatcherStatus(onlineStationData: StationAPIData) {
const { dispatchers } = this.apiData;
const prevDispatcherStatus = this.lastDispatcherStatuses.find(
(dispatcher) => dispatcher.hash === onlineStationData.stationHash
);
const stationStatus = !dispatchers
? undefined
: dispatchers.find(
(status: string[]) => status[0] == onlineStationData.stationHash && status[1] == this.region.id
) || -1;
const statusTimestamp =
prevDispatcherStatus && !dispatchers ? prevDispatcherStatus.statusTimestamp : getStatusTimestamp(stationStatus);
const statusID =
prevDispatcherStatus && !dispatchers ? prevDispatcherStatus.statusID : getStatusID(stationStatus);
return {
hash: onlineStationData.stationHash,
statusID,
statusTimestamp,
};
},
getScheduledTrains(stationGeneralInfo: Station['generalInfo'], stationAPIData: StationAPIData) {
const stationName = stationAPIData.stationName.toLowerCase();
stationGeneralInfo?.checkpoints.forEach((cp) => (cp.scheduledTrains.length = 0));
return this.trainList.reduce((acc: ScheduledTrain[], train) => {
if (!train.timetableData) return acc;
const timetable = train.timetableData;
if (!timetable.sceneries.includes(stationAPIData.stationHash)) return acc;
const stopInfoIndex = timetable.followingStops.findIndex((stop) => {
const stopName = stop.stopNameRAW.toLowerCase();
if (stationName === stopName) return true;
if (stopName.includes(stationName) && !stop.stopName.includes('po.') && !stop.stopName.includes('podg.'))
return true;
if (stationName.includes(stopName) && !stop.stopName.includes('po.') && !stop.stopName.includes('podg.'))
return true;
if (
stopName.includes('podg.') &&
stopName.split(', podg.')[0] &&
stationName.includes(stopName.split(', podg.')[0])
)
return true;
if (
stationGeneralInfo &&
stationGeneralInfo.checkpoints &&
stationGeneralInfo.checkpoints.length > 0 &&
stationGeneralInfo.checkpoints.some((cp) =>
cp.checkpointName.toLowerCase().includes(stop.stopNameRAW.toLowerCase())
)
)
return true;
return false;
});
if (stopInfoIndex == -1) return acc;
const scheduledStopTrain = getScheduledTrain(train, stopInfoIndex, stationAPIData.stationName);
if (stationGeneralInfo?.checkpoints) {
for (const checkpoint of stationGeneralInfo.checkpoints) {
const index = timetable.followingStops.findIndex(
(stop) => stop.stopNameRAW.toLowerCase() == checkpoint.checkpointName.toLowerCase()
);
if (index == -1) continue;
const scheduledCheckpointTrain = getScheduledTrain(train, index, stationAPIData.stationName);
checkpoint.scheduledTrains.push(scheduledCheckpointTrain);
}
}
acc.push(scheduledStopTrain);
return acc;
}, []) as ScheduledTrain[];
},
getStationTrains(stationAPIData: StationAPIData) {
return this.trainList
.filter(
(train) =>
train?.region === this.region.id && train.online && train.currentStationName === stationAPIData.stationName
)
.map((train) => ({
driverName: train.driverName,
driverId: train.driverId,
trainNo: train.trainNo,
trainId: train.trainId,
}));
},
setStationsOnlineInfo() {
const onlineStationNames: string[] = [];
const prevDispatcherStatuses: StoreState['lastDispatcherStatuses'] = [];
this.apiData.stations?.forEach((stationAPIData) => {
if (stationAPIData.region !== this.region.id || !stationAPIData.isOnline) return;
const station = this.stationList.find((s) => s.name === stationAPIData.stationName);
onlineStationNames.push(stationAPIData.stationName);
const dispatcherStatus = this.getDispatcherStatus(stationAPIData);
prevDispatcherStatuses.push(dispatcherStatus);
const stationTrains = this.getStationTrains(stationAPIData);
const scheduledTrains = this.getScheduledTrains(station?.generalInfo, stationAPIData);
const onlineInfo = {
name: stationAPIData.stationName,
hash: stationAPIData.stationHash,
region: stationAPIData.region,
maxUsers: stationAPIData.maxUsers,
currentUsers: stationAPIData.currentUsers,
spawns: parseSpawns(stationAPIData.spawnString),
dispatcherName: stationAPIData.dispatcherName,
dispatcherRate: stationAPIData.dispatcherRate,
dispatcherId: stationAPIData.dispatcherId,
dispatcherExp: stationAPIData.dispatcherExp,
dispatcherIsSupporter: stationAPIData.dispatcherIsSupporter,
stationTrains,
statusTimestamp: dispatcherStatus.statusTimestamp,
statusID: dispatcherStatus.statusID,
scheduledTrains,
};
if (!station) {
this.stationList.push({
name: stationAPIData.stationName,
onlineInfo,
});
return;
}
station.onlineInfo = { ...onlineInfo };
this.stationList
.filter((station) => !onlineStationNames.includes(station.name) && station.onlineInfo)
.forEach((offlineStation) => {
offlineStation.onlineInfo = undefined;
});
});
if (this.apiData.dispatchers != null) this.lastDispatcherStatuses = prevDispatcherStatuses;
},
async fetchStationsGeneralInfo() {
const sceneryData: StationJSONData[] = await (
await axios.get(`${URLs.stacjownikAPI}/api/getSceneries?timestamp=${Math.floor(Date.now() / 1800000)}`)
).data;
if (!sceneryData) {
this.dataStatuses.sceneries = DataStatus.Error;
return;
}
this.stationList = sceneryData.map((scenery) => ({
name: scenery.name,
generalInfo: {
...scenery,
authors: scenery.authors?.split(',').map((a) => a.trim()),
routes:
scenery.routes
?.split(';')
.filter((routeString) => routeString)
.reduce(
(acc, routeString) => {
const specs1 = routeString.split('_')[0];
const isInternal = specs1.startsWith('!');
const name = isInternal ? specs1.replace('!', '') : specs1;
const specs2 = routeString.split('_')[1].split('');
const twoWay = specs2[0] == '2';
const catenary = specs2[1] == 'E';
const SBL = specs2[2] == 'S';
const TWB = specs2[3] ? true : false;
const propName = twoWay
? catenary
? 'twoWayCatenaryRouteNames'
: 'twoWayNoCatenaryRouteNames'
: catenary
? 'oneWayCatenaryRouteNames'
: 'oneWayNoCatenaryRouteNames';
acc[twoWay ? 'twoWay' : 'oneWay'].push({
name,
SBL,
TWB,
catenary,
isInternal,
tracks: twoWay ? 2 : 1,
});
if (!isInternal) acc[propName].push(name);
if (SBL) acc['sblRouteNames'].push(name);
return acc;
},
{
oneWay: [],
twoWay: [],
sblRouteNames: [],
oneWayCatenaryRouteNames: [],
oneWayNoCatenaryRouteNames: [],
twoWayCatenaryRouteNames: [],
twoWayNoCatenaryRouteNames: [],
} as StationRoutes
) || {},
checkpoints: scenery.checkpoints
? scenery.checkpoints.split(';').map((sub) => ({ checkpointName: sub, scheduledTrains: [] }))
: [],
},
}));
},
connectToWebsocket() {
const socket = io(URLs.stacjownikAPI, {
transports: ['websocket', 'polling'],
rememberUpgrade: true,
reconnection: true,
timeout: 10000,
});
socket.on('connect_error', (err) => {
this.dataStatuses.connection = DataStatus.Error;
this.webSocket = undefined;
});
socket.on('UPDATE', (data: APIData) => {
this.apiData = data;
this.dataStatuses.connection = DataStatus.Loaded;
this.setOnlineData();
});
socket.emit('FETCH_DATA', {}, (data: APIData) => {
this.apiData = data;
this.setOnlineData();
});
this.webSocket = socket;
},
async connectToAPI() {
await this.fetchStationsGeneralInfo();
this.connectToWebsocket();
},
async changeRegion(region: StoreState['region']) {
this.region = region;
await this.setOnlineData();
},
async setOnlineData() {
if (!this.apiData.stations) {
this.dataStatuses.sceneries = DataStatus.Error;
this.dataStatuses.trains = DataStatus.Error;
this.dataStatuses.dispatchers = DataStatus.Error;
return;
}
this.dataStatuses.sceneries = DataStatus.Loaded;
this.dataStatuses.trains = !this.apiData.trains ? DataStatus.Warning : DataStatus.Loaded;
this.dataStatuses.dispatchers = !this.apiData.dispatchers ? DataStatus.Warning : DataStatus.Loaded;
this.setTrainsOnlineData();
this.setStationsOnlineInfo();
},
},
});
import axios from 'axios';
import { defineStore } from 'pinia';
import { io } from 'socket.io-client';
import { DataStatus } from '../scripts/enums/DataStatus';
import StationAPIData from '../scripts/interfaces/api/StationAPIData';
import ScheduledTrain from '../scripts/interfaces/ScheduledTrain';
import Station from '../scripts/interfaces/Station';
import StationRoutes from '../scripts/interfaces/StationRoutes';
import Train from '../scripts/interfaces/Train';
import { URLs } from '../scripts/utils/apiURLs';
import {
getLocoURL,
getStatusTimestamp,
getStatusID,
getScheduledTrain,
parseSpawns,
} from '../scripts/utils/storeUtils';
import { APIData, StationJSONData, StoreState } from './storeTypes';
export const useStore = defineStore('store', {
state: () =>
({
apiData: {} as unknown,
stationList: [],
trainList: [],
sceneryData: [],
lastDispatcherStatuses: [],
region: { id: 'eu', value: 'PL1' },
trainCount: 0,
stationCount: 0,
webSocket: undefined,
dispatcherStatsName: '',
dispatcherStatsData: undefined,
driverStatsName: '',
driverStatsData: undefined,
chosenModalTrainId: undefined,
dataStatuses: {
connection: DataStatus.Loading,
sceneries: DataStatus.Loading,
timetables: DataStatus.Loading,
dispatchers: DataStatus.Loading,
trains: DataStatus.Loading,
},
listenerLaunched: false,
} as StoreState),
actions: {
setTrainsOnlineData() {
const { trains } = this.apiData;
if (!trains) return [];
this.trainList = trains
.filter(
(train) =>
train.region === this.region.id && (train.online || train.timetable || train.lastSeen > Date.now() - 180000)
)
.map((train) => {
const stock = train.stockString.split(';');
const locoType = stock ? stock[0] : train.stockString;
const timetable = train.timetable;
return {
trainId: train.driverName + train.trainNo.toString(),
trainNo: train.trainNo,
mass: train.mass,
length: train.length,
speed: train.speed,
region: train.region,
distance: train.distance,
signal: train.signal,
online: train.online,
driverId: train.driverId,
driverName: train.driverName,
currentStationName: train.currentStationName,
currentStationHash: train.currentStationHash,
connectedTrack: train.connectedTrack,
locoType,
locoURL: getLocoURL(locoType),
cars: stock.slice(1),
lastSeen: train.lastSeen,
timetableData: timetable
? {
timetableId: timetable.timetableId,
SKR: timetable.SKR,
TWR: timetable.TWR,
route: timetable.route,
category: timetable.category,
followingStops: timetable.stopList,
routeDistance: timetable.stopList[timetable.stopList.length - 1].stopDistance,
sceneries: timetable.sceneries,
}
: undefined,
};
}) as Train[];
},
getDispatcherStatus(onlineStationData: StationAPIData) {
const { dispatchers } = this.apiData;
const prevDispatcherStatus = this.lastDispatcherStatuses.find(
(dispatcher) => dispatcher.hash === onlineStationData.stationHash
);
const stationStatus = !dispatchers
? undefined
: dispatchers.find(
(status: string[]) => status[0] == onlineStationData.stationHash && status[1] == this.region.id
) || -1;
const statusTimestamp =
prevDispatcherStatus && !dispatchers ? prevDispatcherStatus.statusTimestamp : getStatusTimestamp(stationStatus);
const statusID =
prevDispatcherStatus && !dispatchers ? prevDispatcherStatus.statusID : getStatusID(stationStatus);
return {
hash: onlineStationData.stationHash,
statusID,
statusTimestamp,
};
},
getScheduledTrains(stationGeneralInfo: Station['generalInfo'], stationAPIData: StationAPIData) {
const stationName = stationAPIData.stationName.toLowerCase();
stationGeneralInfo?.checkpoints.forEach((cp) => (cp.scheduledTrains.length = 0));
return this.trainList.reduce((acc: ScheduledTrain[], train) => {
if (!train.timetableData) return acc;
const timetable = train.timetableData;
if (!timetable.sceneries.includes(stationAPIData.stationHash)) return acc;
const stopInfoIndex = timetable.followingStops.findIndex((stop) => {
const stopName = stop.stopNameRAW.toLowerCase();
if (stationName === stopName) return true;
if (stopName.includes(stationName) && !stop.stopName.includes('po.') && !stop.stopName.includes('podg.'))
return true;
if (stationName.includes(stopName) && !stop.stopName.includes('po.') && !stop.stopName.includes('podg.'))
return true;
if (
stopName.includes('podg.') &&
stopName.split(', podg.')[0] &&
stationName.includes(stopName.split(', podg.')[0])
)
return true;
if (
stationGeneralInfo &&
stationGeneralInfo.checkpoints &&
stationGeneralInfo.checkpoints.length > 0 &&
stationGeneralInfo.checkpoints.some((cp) =>
cp.checkpointName.toLowerCase().includes(stop.stopNameRAW.toLowerCase())
)
)
return true;
return false;
});
if (stopInfoIndex == -1) return acc;
const scheduledStopTrain = getScheduledTrain(train, stopInfoIndex, stationAPIData.stationName);
if (stationGeneralInfo?.checkpoints) {
for (const checkpoint of stationGeneralInfo.checkpoints) {
const index = timetable.followingStops.findIndex(
(stop) => stop.stopNameRAW.toLowerCase() == checkpoint.checkpointName.toLowerCase()
);
if (index == -1) continue;
const scheduledCheckpointTrain = getScheduledTrain(train, index, stationAPIData.stationName);
checkpoint.scheduledTrains.push(scheduledCheckpointTrain);
}
}
acc.push(scheduledStopTrain);
return acc;
}, []) as ScheduledTrain[];
},
getStationTrains(stationAPIData: StationAPIData) {
return this.trainList
.filter(
(train) =>
train?.region === this.region.id && train.online && train.currentStationName === stationAPIData.stationName
)
.map((train) => ({
driverName: train.driverName,
driverId: train.driverId,
trainNo: train.trainNo,
trainId: train.trainId,
}));
},
setStationsOnlineInfo() {
const onlineStationNames: string[] = [];
const prevDispatcherStatuses: StoreState['lastDispatcherStatuses'] = [];
this.apiData.stations?.forEach((stationAPIData) => {
if (stationAPIData.region !== this.region.id || !stationAPIData.isOnline) return;
const station = this.stationList.find((s) => s.name === stationAPIData.stationName);
onlineStationNames.push(stationAPIData.stationName);
const dispatcherStatus = this.getDispatcherStatus(stationAPIData);
prevDispatcherStatuses.push(dispatcherStatus);
const stationTrains = this.getStationTrains(stationAPIData);
const scheduledTrains = this.getScheduledTrains(station?.generalInfo, stationAPIData);
const onlineInfo = {
name: stationAPIData.stationName,
hash: stationAPIData.stationHash,
region: stationAPIData.region,
maxUsers: stationAPIData.maxUsers,
currentUsers: stationAPIData.currentUsers,
spawns: parseSpawns(stationAPIData.spawnString),
dispatcherName: stationAPIData.dispatcherName,
dispatcherRate: stationAPIData.dispatcherRate,
dispatcherId: stationAPIData.dispatcherId,
dispatcherExp: stationAPIData.dispatcherExp,
dispatcherIsSupporter: stationAPIData.dispatcherIsSupporter,
stationTrains,
statusTimestamp: dispatcherStatus.statusTimestamp,
statusID: dispatcherStatus.statusID,
scheduledTrains,
};
if (!station) {
this.stationList.push({
name: stationAPIData.stationName,
onlineInfo,
});
return;
}
station.onlineInfo = { ...onlineInfo };
this.stationList
.filter((station) => !onlineStationNames.includes(station.name) && station.onlineInfo)
.forEach((offlineStation) => {
offlineStation.onlineInfo = undefined;
});
});
if (this.apiData.dispatchers != null) this.lastDispatcherStatuses = prevDispatcherStatuses;
},
async fetchStationsGeneralInfo() {
const sceneryData: StationJSONData[] = await (
await axios.get(`${URLs.stacjownikAPI}/api/getSceneries?timestamp=${Math.floor(Date.now() / 1800000)}`)
).data;
if (!sceneryData) {
this.dataStatuses.sceneries = DataStatus.Error;
return;
}
this.stationList = sceneryData.map((scenery) => ({
name: scenery.name,
generalInfo: {
...scenery,
authors: scenery.authors?.split(',').map((a) => a.trim()),
routes:
scenery.routes
?.split(';')
.filter((routeString) => routeString)
.reduce(
(acc, routeString) => {
const specs1 = routeString.split('_')[0];
const isInternal = specs1.startsWith('!');
const name = isInternal ? specs1.replace('!', '') : specs1;
const specs2 = routeString.split('_')[1].split('');
const twoWay = specs2[0] == '2';
const catenary = specs2[1] == 'E';
const SBL = specs2[2] == 'S';
const TWB = specs2[3] ? true : false;
const propName = twoWay
? catenary
? 'twoWayCatenaryRouteNames'
: 'twoWayNoCatenaryRouteNames'
: catenary
? 'oneWayCatenaryRouteNames'
: 'oneWayNoCatenaryRouteNames';
acc[twoWay ? 'twoWay' : 'oneWay'].push({
name,
SBL,
TWB,
catenary,
isInternal,
tracks: twoWay ? 2 : 1,
});
if (!isInternal) acc[propName].push(name);
if (SBL) acc['sblRouteNames'].push(name);
return acc;
},
{
oneWay: [],
twoWay: [],
sblRouteNames: [],
oneWayCatenaryRouteNames: [],
oneWayNoCatenaryRouteNames: [],
twoWayCatenaryRouteNames: [],
twoWayNoCatenaryRouteNames: [],
} as StationRoutes
) || {},
checkpoints: scenery.checkpoints
? scenery.checkpoints.split(';').map((sub) => ({ checkpointName: sub, scheduledTrains: [] }))
: [],
},
}));
},
connectToWebsocket() {
const socket = io(URLs.stacjownikAPI, {
transports: ['websocket', 'polling'],
rememberUpgrade: true,
reconnection: true,
timeout: 10000,
});
socket.on('connect_error', (err) => {
this.dataStatuses.connection = DataStatus.Error;
this.webSocket = undefined;
});
socket.on('UPDATE', (data: APIData) => {
this.apiData = data;
this.dataStatuses.connection = DataStatus.Loaded;
this.setOnlineData();
});
socket.emit('FETCH_DATA', {}, (data: APIData) => {
this.apiData = data;
this.setOnlineData();
});
this.webSocket = socket;
},
async connectToAPI() {
await this.fetchStationsGeneralInfo();
this.connectToWebsocket();
},
async changeRegion(region: StoreState['region']) {
this.region = region;
await this.setOnlineData();
},
async setOnlineData() {
if (!this.apiData.stations) {
this.dataStatuses.sceneries = DataStatus.Error;
this.dataStatuses.trains = DataStatus.Error;
this.dataStatuses.dispatchers = DataStatus.Error;
return;
}
this.dataStatuses.sceneries = DataStatus.Loaded;
this.dataStatuses.trains = !this.apiData.trains ? DataStatus.Warning : DataStatus.Loaded;
this.dataStatuses.dispatchers = !this.apiData.dispatchers ? DataStatus.Warning : DataStatus.Loaded;
this.setTrainsOnlineData();
this.setStationsOnlineInfo();
},
},
});