refactor typów danych

This commit is contained in:
2023-11-10 15:04:49 +01:00
parent e82b4b8817
commit f8b4ce103f
84 changed files with 1011 additions and 1173 deletions
+33 -42
View File
@@ -1,28 +1,21 @@
import axios from 'axios';
import { defineStore } from 'pinia';
import { io } from 'socket.io-client';
import { DataStatus } from '../scripts/enums/DataStatus';
import StationRoutes from '../scripts/interfaces/StationRoutes';
import Train from '../scripts/interfaces/Train';
import { URLs } from '../scripts/utils/apiURLs';
import { parseSpawns, getScheduledTrains, getStationTrains } from '../scripts/utils/storeUtils';
import { parseSpawns, getScheduledTrains, getStationTrains } from './utils';
import {
APIData,
OnlineScenery,
StationJSONData,
StoreState
} from '../scripts/interfaces/store/storeTypes';
import { OnlineScenery, ScheduledTrain, StationJSONData, StoreState } from './typings';
import packageInfo from '../../package.json';
import { RollingStockGithubData } from '../scripts/interfaces/github_api/StockInfoGithubData';
import { ScheduledTrain } from '../scripts/interfaces/ScheduledTrain';
import { DispatcherStatus } from '../scripts/enums/DispatcherStatus';
import { Websocket, API } from '../typings/api';
import { Status } from '../typings/common';
export const useStore = defineStore('store', {
state: () =>
({
apiData: {} as unknown,
activeData: {} as unknown,
rollingStockData: undefined,
stationList: [],
@@ -46,16 +39,16 @@ export const useStore = defineStore('store', {
driverStatsName: '',
driverStatsData: undefined,
driverStatsStatus: DataStatus.Initialized,
driverStatsStatus: Status.Data.Initialized,
chosenModalTrainId: undefined,
dataStatuses: {
connection: DataStatus.Loading,
sceneries: DataStatus.Loading,
timetables: DataStatus.Loading,
dispatchers: DataStatus.Loading,
trains: DataStatus.Loading
connection: Status.Data.Loading,
sceneries: Status.Data.Loading,
timetables: Status.Data.Loading,
dispatchers: Status.Data.Loading,
trains: Status.Data.Loading
},
currentStatsTab: null,
@@ -67,7 +60,7 @@ export const useStore = defineStore('store', {
getters: {
trainList(): Train[] {
return (this.apiData?.trains ?? [])
return (this.activeData?.trains ?? [])
.filter((train) => train.online || train.timetable || train.lastSeen > Date.now() - 180000)
.map((train) => {
const stock = train.stockString.split(';');
@@ -119,11 +112,11 @@ export const useStore = defineStore('store', {
onlineSceneryList(state): OnlineScenery[] {
if (state.isOffline) return [];
if (!state.apiData?.activeSceneries) return [];
if (!state.activeData?.activeSceneries) return [];
return state.apiData?.activeSceneries.reduce((list, scenery) => {
return state.activeData?.activeSceneries.reduce((list, scenery) => {
if (scenery.isOnline !== 1 && Date.now() - scenery.lastSeen > 1000 * 60 * 2) return list;
if (scenery.dispatcherStatus == DispatcherStatus.UNKNOWN) return list;
if (scenery.dispatcherStatus == Status.ActiveDispatcher.UNKNOWN) return list;
const station = this.stationList.find((s) => s.name === scenery.stationName);
@@ -181,7 +174,7 @@ export const useStore = defineStore('store', {
).data;
if (!sceneryData) {
this.dataStatuses.sceneries = DataStatus.Error;
this.dataStatuses.sceneries = Status.Data.Error;
return;
}
@@ -239,8 +232,8 @@ export const useStore = defineStore('store', {
async connectToWebsocket() {
if (import.meta.env.VITE_APP_WS_DEV === '1') {
const mockWebsocketData = await import('../data/mockWebsocketData.json');
this.dataStatuses.connection = DataStatus.Loaded;
this.apiData = mockWebsocketData as any;
this.dataStatuses.connection = Status.Data.Loaded;
this.activeData = mockWebsocketData as any;
this.setStatuses();
console.warn('Stacjownik działa w trybie mockowania danych z WS');
@@ -257,19 +250,19 @@ export const useStore = defineStore('store', {
socket.emit('CONNECTION', { version: packageInfo.version });
socket.on('connect_error', () => {
this.dataStatuses.connection = DataStatus.Error;
this.dataStatuses.connection = Status.Data.Error;
});
socket.on('UPDATE', (data: APIData) => {
this.apiData = data;
this.dataStatuses.connection = DataStatus.Loaded;
socket.on('UPDATE', (data: Websocket.ActiveData) => {
this.activeData = data;
this.dataStatuses.connection = Status.Data.Loaded;
this.setStatuses();
});
socket.emit('FETCH_DATA', { version: packageInfo.version }, (data: APIData) => {
this.dataStatuses.connection = DataStatus.Loaded;
this.apiData = data;
socket.emit('FETCH_DATA', { version: packageInfo.version }, (data: Websocket.ActiveData) => {
this.dataStatuses.connection = Status.Data.Loaded;
this.activeData = data;
this.setStatuses();
});
@@ -289,7 +282,7 @@ export const useStore = defineStore('store', {
async fetchStockInfoData() {
try {
this.rollingStockData = (
await axios.get<RollingStockGithubData>(
await axios.get<API.RollingStock.Response>(
'https://raw.githubusercontent.com/Spythere/api/main/td2/data/stockInfo.json'
)
).data;
@@ -299,19 +292,17 @@ export const useStore = defineStore('store', {
},
async setStatuses() {
if (!this.apiData.stations) {
this.dataStatuses.sceneries = DataStatus.Error;
this.dataStatuses.trains = DataStatus.Error;
this.dataStatuses.dispatchers = DataStatus.Error;
if (!this.activeData.activeSceneries) {
this.dataStatuses.sceneries = Status.Data.Error;
this.dataStatuses.trains = Status.Data.Error;
this.dataStatuses.dispatchers = Status.Data.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.dataStatuses.sceneries = Status.Data.Loaded;
this.dataStatuses.trains = !this.activeData.trains ? Status.Data.Warning : Status.Data.Loaded;
this.dataStatuses.dispatchers = Status.Data.Loaded;
// if (this.apiData.dispatchers != null) this.lastDispatcherStatuses = prevDispatcherStatuses;
}
+51 -3
View File
@@ -1,10 +1,58 @@
import { defineStore } from 'pinia';
import inputData from '../data/options.json';
import StorageManager from '../scripts/managers/storageManager';
import { useStore } from './store';
import { filterInitStates } from '../scripts/constants/stores/initFilterStates';
import { useStore } from './mainStore';
import { filterStations, sortStations } from '../scripts/utils/filterUtils';
import { HeadIdsTypes } from '../scripts/data/stationHeaderNames';
import StorageManager from '../managers/storageManager';
import { Filter } from '../components/StationsView/typings';
const filterInitStates: Filter = {
default: false,
notDefault: false,
real: false,
fictional: false,
SPK: false,
SCS: false,
SPE: false,
SUP: false,
noSUP: false,
ręczne: false,
'ręczne+SPK': false,
'ręczne+SCS': false,
mechaniczne: false,
'mechaniczne+SPK': false,
'mechaniczne+SCS': false,
współczesna: false,
kształtowa: false,
historyczna: false,
mieszana: false,
SBL: false,
PBL: false,
minLevel: 0,
maxLevel: 20,
minOneWayCatenary: 0,
minOneWay: 0,
minTwoWayCatenary: 0,
minTwoWay: 0,
'include-selected': false,
'no-1track': false,
'no-2track': false,
free: true,
occupied: false,
ending: false,
nonPublic: false,
unavailable: true,
abandoned: true,
afkStatus: false,
endingStatus: false,
noSpaceStatus: false,
unavailableStatus: false,
unsignedStatus: false,
authors: '',
onlineFromHours: 0
};
export const useStationFiltersStore = defineStore('stationFiltersStore', {
state() {
+196
View File
@@ -0,0 +1,196 @@
import { Socket } from 'socket.io-client';
import Station from '../scripts/interfaces/Station';
import { API, Websocket } from '../typings/api';
import { Status } from '../typings/common';
export type Availability = 'default' | 'unavailable' | 'nonPublic' | 'abandoned' | 'nonDefault';
export interface RegionCounters {
stationCount: number;
trainsCount: number;
timetablesCount: number;
}
export interface StoreState {
stationList: Station[];
activeData: Websocket.ActiveData;
rollingStockData?: API.RollingStock.Response;
regionOnlineCounters: RegionCounters[];
lastDispatcherStatuses: {
hash: string;
statusTimestamp: number;
statusID: Status.ActiveDispatcher;
}[];
sceneryData: any[][];
region: { id: string; value: string };
trainCount: number;
stationCount: number;
webSocket?: Socket;
isOffline: boolean;
dispatcherStatsName: string;
dispatcherStatsData?: API.DispatcherStats.Response;
driverStatsName: string;
driverStatsData?: API.DriverStats.Response;
driverStatsStatus: Status.Data;
chosenModalTrainId?: string;
currentStatsTab: 'daily' | 'driver' | null;
dataStatuses: {
connection: Status.Data;
sceneries: Status.Data;
timetables: Status.Data;
dispatchers: Status.Data;
trains: Status.Data;
};
listenerLaunched: boolean;
blockScroll: boolean;
modalLastClickedTarget: EventTarget | null;
}
export interface StationRoutesInfo {
routeName: string;
isElectric: boolean;
isInternal: boolean;
isRouteSBL: boolean;
routeLength: number;
routeSpeed: number;
routeTracks: number;
}
export interface StationJSONData {
name: string;
abbr: string;
url: string;
lines: string;
project: string;
projectUrl: string;
reqLevel: number;
signalType: string;
controlType: string;
SUP: boolean;
// routes: string;
routesInfo: StationRoutesInfo[];
checkpoints: string | null;
authors?: string;
availability: Availability;
}
export interface OnlineScenery {
name: string;
hash: string;
region: string;
maxUsers: number;
currentUsers: number;
spawns: { spawnName: string; spawnLength: number; isElectrified: boolean }[];
dispatcherName: string;
dispatcherRate: number;
dispatcherId: number;
dispatcherExp: number;
dispatcherIsSupporter: boolean;
dispatcherStatus: Status.ActiveDispatcher | number;
isOnline: boolean;
stationTrains?: StationTrain[];
scheduledTrains?: ScheduledTrain[];
scheduledTrainCount: {
all: number;
confirmed: number;
unconfirmed: number;
};
}
export interface StationTrain {
driverName: string;
driverId: number;
trainNo: number;
trainId: string;
stopStatus: string;
}
export interface ScheduledTrain {
checkpointName: string;
trainId: string;
trainNo: number;
driverName: string;
driverId: number;
currentStationName: string;
currentStationHash: string;
category: string;
stopInfo: TrainStop;
terminatesAt: string;
beginsAt: string;
prevStationName: string;
nextStationName: string;
arrivingLine: string | null;
departureLine: string | null;
prevDepartureLine: string | null;
nextArrivalLine: string | null;
signal: string;
connectedTrack: string;
stopLabel: string;
stopStatus: StopStatus;
stopStatusID: number;
}
export enum StopStatus {
ARRIVING = 'arriving',
DEPARTED = 'departed',
DEPARTED_AWAY = 'departed-away',
ONLINE = 'online',
STOPPED = 'stopped',
TERMINATED = 'terminated'
}
export interface TrainStop {
stopName: string;
stopNameRAW: string;
stopType: string;
stopDistance: number;
mainStop: boolean;
arrivalLine: string | null;
arrivalTimestamp: number;
arrivalRealTimestamp: number;
arrivalDelay: number;
departureLine: string | null;
departureTimestamp: number;
departureRealTimestamp: number;
departureDelay: number;
pointId: number;
comments?: any;
beginsHere: boolean;
terminatesHere: boolean;
confirmed: boolean;
stopped: boolean;
stopTime: number | null;
}
+267
View File
@@ -0,0 +1,267 @@
import Station from '../scripts/interfaces/Station';
import Train from '../scripts/interfaces/Train';
import { API } from '../typings/api';
import { ScheduledTrain, StationTrain, StopStatus, TrainStop } from './typings';
export function getLocoURL(locoType: string): string {
return `https://rj.td2.info.pl/dist/img/thumbnails/${
locoType.includes('EN') ? locoType + 'rb' : locoType
}.png`;
}
export function getStatusTimestamp(stationStatus: any): number {
if (!stationStatus) return -2;
const statusCode = stationStatus[2];
const statusTimestamp = stationStatus[3];
switch (statusCode) {
case 0:
case 1:
case 3:
return statusTimestamp;
case 2:
if (statusTimestamp == 0) return 0;
break;
default:
break;
}
return -1;
}
export function parseSpawns(spawnString: string | null) {
if (!spawnString) return [];
if (spawnString === 'NO_SPAWN') return [];
return spawnString.split(';').map((spawn) => {
const spawnArray = spawn.split(',');
const spawnName = spawnArray[6] ? spawnArray[6] : spawnArray[0];
const spawnLength = parseInt(spawnArray[2]);
const isElectrified = spawnArray[3] == 'True';
return { spawnName, spawnLength, isElectrified };
});
}
export function getTimestamp(date: string | null): number {
return date ? new Date(date).getTime() : 0;
}
export function getTrainStopStatus(
stopInfo: TrainStop,
currentStationName: string,
sceneryName: string
) {
let stopStatus = StopStatus.ARRIVING,
stopLabel = '',
stopStatusID = -1;
if (stopInfo.terminatesHere && stopInfo.confirmed) {
stopStatus = StopStatus.TERMINATED;
stopLabel = 'Skończył bieg';
stopStatusID = 5;
} else if (!stopInfo.terminatesHere && stopInfo.confirmed && currentStationName == sceneryName) {
stopStatus = StopStatus.DEPARTED;
stopLabel = 'Odprawiony';
stopStatusID = 2;
} else if (!stopInfo.terminatesHere && stopInfo.confirmed && currentStationName != sceneryName) {
stopStatus = StopStatus.DEPARTED_AWAY;
stopLabel = 'Odjechał';
stopStatusID = 4;
} else if (currentStationName == sceneryName && !stopInfo.stopped) {
stopStatus = StopStatus.ONLINE;
stopLabel = 'Na stacji';
stopStatusID = 0;
} else if (currentStationName == sceneryName && stopInfo.stopped) {
stopStatus = StopStatus.STOPPED;
stopLabel = 'Postój';
stopStatusID = 1;
} else if (currentStationName != sceneryName) {
stopStatus = StopStatus.ARRIVING;
stopLabel = 'W drodze';
stopStatusID = 3;
}
return { stopStatus, stopLabel, stopStatusID };
}
export function getCheckpointTrain(
train: Train,
trainStopIndex: number,
sceneryName: string
): ScheduledTrain {
const timetable = train.timetableData!;
const followingStops = timetable.followingStops;
const trainStop = followingStops[trainStopIndex];
const trainStopStatus = getTrainStopStatus(trainStop, train.currentStationName, sceneryName);
let prevStationName = '',
nextStationName = '';
let prevDepartureLine: string | null = null,
nextArrivalLine: string | null = null;
for (let i = trainStopIndex - 1; i >= 0; i--) {
if (/strong|podg/g.test(followingStops[i].stopName)) {
prevStationName = followingStops[i].stopNameRAW.replace(/,.*/g, '');
break;
}
}
for (let i = trainStopIndex + 1; i < followingStops.length; i++) {
if (/strong|podg/g.test(followingStops[i].stopName)) {
nextStationName = followingStops[i].stopNameRAW.replace(/,.*/g, '');
break;
}
}
let departureLine: string | null = null;
let arrivingLine: string | null = null;
for (let i = trainStopIndex; i < followingStops.length; i++) {
const currentStop = followingStops[i];
if (currentStop.departureLine == null) continue;
if (!/-|_|it|sbl/gi.test(currentStop.departureLine)) {
departureLine = currentStop.departureLine;
nextArrivalLine = followingStops[i + 1]?.arrivalLine || null;
break;
}
}
for (let i = trainStopIndex; i >= 0; i--) {
const currentStop = followingStops[i];
if (currentStop.arrivalLine == null) continue;
if (!/-|_|it|sbl/gi.test(currentStop.arrivalLine)) {
arrivingLine = currentStop.arrivalLine;
prevDepartureLine = followingStops[i - 1]?.departureLine || null;
break;
}
}
return {
checkpointName: trainStop.stopNameRAW,
trainNo: train.trainNo,
trainId: train.trainId,
signal: train.signal,
connectedTrack: train.connectedTrack,
driverName: train.driverName,
driverId: train.driverId,
currentStationName: train.currentStationName,
currentStationHash: train.currentStationHash,
category: timetable.category,
beginsAt: timetable.followingStops[0].stopNameRAW,
terminatesAt: timetable.followingStops[timetable.followingStops.length - 1].stopNameRAW,
nextStationName,
prevStationName,
stopInfo: trainStop,
stopLabel: trainStopStatus.stopLabel,
stopStatus: trainStopStatus.stopStatus,
stopStatusID: trainStopStatus.stopStatusID,
arrivingLine,
departureLine,
nextArrivalLine,
prevDepartureLine
};
}
export function getScheduledTrains(
trainList: Train[],
sceneryData: API.ActiveSceneries.Data,
stationGeneralInfo: Station['generalInfo']
): ScheduledTrain[] {
const stationName = sceneryData.stationName.toLocaleLowerCase();
stationGeneralInfo?.checkpoints.forEach((cp) => (cp.scheduledTrains.length = 0));
return trainList.reduce((acc: ScheduledTrain[], train) => {
if (!train.timetableData) return acc;
const timetable = train.timetableData;
if (!timetable.sceneries.includes(sceneryData.stationHash)) return acc;
const stopInfoIndex = timetable.followingStops.findIndex((stop) => {
const stopName = stop.stopNameRAW.toLowerCase();
return (
stationName == stopName ||
(!/(po\.|podg\.)/.test(stopName) && stopName.includes(stationName)) ||
(!/(po\.|podg\.)/.test(stationName) && stationName.includes(stopName)) ||
(stopName.split(', podg.')[0] !== undefined &&
stationName.startsWith(stopName.split(', podg.')[0]))
);
});
const checkpointScheduledTrains: ScheduledTrain[] = [];
if (stopInfoIndex != -1) {
checkpointScheduledTrains.push(
getCheckpointTrain(train, stopInfoIndex, sceneryData.stationName)
);
}
stationGeneralInfo?.checkpoints?.forEach((checkpoint) => {
if (checkpoint.checkpointName.toLocaleLowerCase() == stationName) return;
if (
checkpointScheduledTrains.findIndex(
(cpTrain) =>
cpTrain.checkpointName.toLocaleLowerCase() ==
checkpoint.checkpointName.toLocaleLowerCase()
) != -1
)
return;
const index = timetable.followingStops.findIndex(
(stop) => stop.stopNameRAW.toLowerCase() == checkpoint.checkpointName.toLowerCase()
);
if (index > -1)
checkpointScheduledTrains.push(getCheckpointTrain(train, index, sceneryData.stationName));
});
acc.push(...checkpointScheduledTrains);
return acc;
}, []) as ScheduledTrain[];
}
export function getStationTrains(
trainList: Train[],
scheduledTrainList: ScheduledTrain[],
region: string,
sceneryData: API.ActiveSceneries.Data
): StationTrain[] {
return trainList
.filter(
(train) =>
train?.region === region &&
train.online &&
train.currentStationName === sceneryData.stationName
)
.map((train) => ({
driverName: train.driverName,
driverId: train.driverId,
trainNo: train.trainNo,
trainId: train.trainId,
stopStatus:
scheduledTrainList.find((st) => st.trainNo === train.trainNo)?.stopStatus || 'no-timetable'
}));
}