Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change config mechanism #69

Merged
merged 4 commits into from
Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ dist
**/.env
**/node_modules
NOTES.md
.docker-test
.docker-test
options.dev.json
28 changes: 4 additions & 24 deletions ps5-mqtt/run.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
#!/usr/bin/env bashio

export CONFIG_PATH="/data/options.json"
export CREDENTIAL_STORAGE_PATH="/config/ps5-mqtt/credentials.json"

if bashio::config.is_empty 'mqtt' && bashio::var.has_value "$(bashio::services 'mqtt')"; then
export MQTT_HOST="$(bashio::services 'mqtt' 'host')"
export MQTT_PORT="$(bashio::services 'mqtt' 'port')"
Expand All @@ -12,35 +15,12 @@ else
export MQTT_PASSWORD=$(bashio::config 'mqtt.pass')
fi

export DEVICE_CHECK_INTERVAL=$(bashio::config 'device_check_interval')
export DEVICE_DISCOVERY_INTERVAL=$(bashio::config 'device_discovery_interval')
export ACCOUNT_CHECK_INTERVAL=$(bashio::config 'account_check_interval')

export INCLUDE_PS4_DEVICES=$(bashio::config 'include_ps4_devices')

export FRONTEND_PORT=8645
if [ ! -z $(bashio::addon.ingress_port) ]; then
FRONTEND_PORT=$(bashio::addon.ingress_port)
fi

if [ ! -z $(bashio::config 'psn_accounts') ]; then
export PSN_ACCOUNTS="["

for computer in $(bashio::config 'psn_accounts|keys'); do
USERNAME=$(bashio::config "psn_accounts[${computer}].username")
NPSSO=$(bashio::config "psn_accounts[${computer}].npsso")

PSN_ACCOUNTS+="{\"username\":\"$USERNAME\",\"npsso\":\"$NPSSO\"},"
done

PSN_ACCOUNTS=${PSN_ACCOUNTS::-1}
PSN_ACCOUNTS+="]"
else
export PSN_ACCOUNTS="[]"
fi

export CREDENTIAL_STORAGE_PATH="/config/ps5-mqtt/credentials.json"

# configure logger
export DEBUG="*,-mqttjs*,-mqtt-packet*,-playactor:*,-@ha:state*,-@ha:ps5:poll*,-@ha:ps5:check*"

if [ ! -z $(bashio::config 'logger') ]; then
Expand Down
112 changes: 112 additions & 0 deletions ps5-mqtt/server/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import * as fs from 'fs';
import * as process from 'process';
import lodash from 'lodash';

import { createErrorLogger } from './util/error-logger';

const logError = createErrorLogger();

export interface AppConfig {
// yml options
mqtt: {
host: string,
pass: string,
port: string,
user: string
},

device_check_interval: number,
device_discovery_interval: number,

include_ps4_devices: boolean,

psn_accounts: AppConfig.PsnAccountInfo[],

account_check_interval: number,

// non yml options
credentialsStoragePath: string,
frontendPort: string,
}

export module AppConfig {
export interface PsnAccountInfo {
npsso: string,
username?: string,
}
}

export function getAppConfig(): AppConfig {
const {
CONFIG_PATH
} = process.env;

const configFileOptions = getJsonConfig(CONFIG_PATH);
const envOptions = getEnvConfig();

return lodash.merge(configFileOptions, envOptions) as AppConfig
}

function getJsonConfig(configPath: string): Partial<AppConfig> {
if (!fs.existsSync(configPath)) {
logError(`config could not be read from '${configPath}'`);
return {};
}
const optionsRaw = fs.readFileSync(configPath, { encoding: 'utf-8' });
try {
const options: AppConfig = JSON.parse(optionsRaw);
return options;
} catch (err) {
logError(`Received invalid options: "${optionsRaw}".`)
return {};
}
}

function getEnvConfig(): Partial<AppConfig> {
const {
MQTT_HOST,
MQTT_PASSWORD,
MQTT_PORT,
MQTT_USERNAME,

FRONTEND_PORT,

CREDENTIAL_STORAGE_PATH,

INCLUDE_PS4_DEVICES,

DEVICE_CHECK_INTERVAL,
DEVICE_DISCOVERY_INTERVAL,
ACCOUNT_CHECK_INTERVAL,

PSN_ACCOUNTS,
} = process.env;

return {
mqtt: {
host: MQTT_HOST,
port: MQTT_PORT,
pass: MQTT_PASSWORD,
user: MQTT_USERNAME,
},

device_check_interval:
DEVICE_CHECK_INTERVAL
? parseInt(DEVICE_CHECK_INTERVAL, 10)
: undefined,
device_discovery_interval:
DEVICE_DISCOVERY_INTERVAL
? parseInt(DEVICE_DISCOVERY_INTERVAL, 10)
: undefined,
account_check_interval:
ACCOUNT_CHECK_INTERVAL
? parseInt(ACCOUNT_CHECK_INTERVAL, 10)
: undefined,

psn_accounts: PSN_ACCOUNTS ? JSON.parse(PSN_ACCOUNTS) : undefined,
include_ps4_devices: Boolean(INCLUDE_PS4_DEVICES),

credentialsStoragePath: CREDENTIAL_STORAGE_PATH,
frontendPort: FRONTEND_PORT
}
}
64 changes: 20 additions & 44 deletions ps5-mqtt/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import createDebugger from "debug";
import os from 'os';
import path from 'path';
import createSagaMiddleware from "redux-saga";
import { AppConfig, getAppConfig } from "./config";
import { PsnAccount } from "./psn-account";
import reducer, {
getDeviceRegistry,
Expand All @@ -22,47 +23,24 @@ const debugMqtt = createDebugger("@ha:ps5:mqtt");
const debugState = createDebugger("@ha:state");
const logError = createErrorLogger();

const {
MQTT_HOST,
MQTT_PASSWORD,
MQTT_PORT,
MQTT_USERNAME,

FRONTEND_PORT,

CREDENTIAL_STORAGE_PATH,

INCLUDE_PS4_DEVICES,

DEVICE_CHECK_INTERVAL,
DEVICE_DISCOVERY_INTERVAL,
ACCOUNT_CHECK_INTERVAL,

PSN_ACCOUNTS,
} = process.env;

const accountsInfo = JSON.parse(PSN_ACCOUNTS);

const credentialStoragePath = CREDENTIAL_STORAGE_PATH
? CREDENTIAL_STORAGE_PATH
: path.join(os.homedir(), '.config', 'playactor', 'credentials.json');
const appConfig = getAppConfig();

const createMqtt = async (): Promise<MQTT.AsyncMqttClient> => {
return await MQTT.connectAsync(`mqtt://${MQTT_HOST}`, {
password: MQTT_PASSWORD,
port: parseInt(MQTT_PORT || "1883", 10),
username: MQTT_USERNAME,
return await MQTT.connectAsync(`mqtt://${appConfig.mqtt.host}`, {
password: appConfig.mqtt.pass,
port: parseInt(appConfig.mqtt.port || "1883", 10),
username: appConfig.mqtt.user,
reconnectPeriod: 2000,
connectTimeout: 3 * 60 * 1000 // 3 minutes
});
};

async function getPsnAccountRegistry(
accounts: { npsso: string }[]
accounts: AppConfig.PsnAccountInfo[]
): Promise<Record<string, PsnAccount>> {
const accountRegistry: Record<string, PsnAccount> = {};
for (const { npsso } of accounts) {
const account = await PsnAccount.exchangeNpssoForPsnAccount(npsso);
for (const { npsso, username } of accounts) {
const account = await PsnAccount.exchangeNpssoForPsnAccount(npsso, username);
accountRegistry[account.accountId] = account;
}
return accountRegistry;
Expand All @@ -77,15 +55,13 @@ async function run() {

const settings: Settings = {
// polling intervals
checkDevicesInterval:
parseInt(DEVICE_CHECK_INTERVAL || "5000", 10),
checkAccountInterval:
parseInt(ACCOUNT_CHECK_INTERVAL || "5000", 10),
discoverDevicesInterval:
parseInt(DEVICE_DISCOVERY_INTERVAL || "60000", 10),

credentialStoragePath,
allowPs4Devices: INCLUDE_PS4_DEVICES === 'true',
checkDevicesInterval: appConfig.device_check_interval || 5000,
checkAccountInterval: appConfig.account_check_interval || 5000,
discoverDevicesInterval: appConfig.device_discovery_interval || 60000,

credentialStoragePath: appConfig.credentialsStoragePath
?? path.join(os.homedir(), '.config', 'playactor', 'credentials.json'),
allowPs4Devices: appConfig.include_ps4_devices ?? true,
};

try {
Expand All @@ -95,13 +71,13 @@ async function run() {
[SETTINGS]: settings,
}
});
const accounts = await getPsnAccountRegistry(accountsInfo)
const accounts = await getPsnAccountRegistry(appConfig.psn_accounts ?? [])
const store = configureStore({
reducer,
middleware: [sagaMiddleware],
preloadedState: {
devices: {},
accounts: accounts,
accounts: accounts,
}
});
store.subscribe(() => {
Expand Down Expand Up @@ -135,14 +111,14 @@ async function run() {
if (Object.keys(accounts).length > 0) {
store.dispatch(pollPsnPresence());
}

store.dispatch(pollDiscovery());
store.dispatch(pollDevices());
} catch (e) {
logError(e);
}

setupWebserver(FRONTEND_PORT ?? 3000, settings)
setupWebserver(appConfig.frontendPort ?? 3000, settings)
}

if (require.main === module) {
Expand Down
10 changes: 5 additions & 5 deletions ps5-mqtt/server/src/psn-account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ export module PsnAccount {
launchPlatform: NormalizedDeviceType;
}

export async function exchangeNpssoForPsnAccount(npsso: string): Promise<PsnAccount> {
return getAccount(npsso);
export async function exchangeNpssoForPsnAccount(npsso: string, username?: string): Promise<PsnAccount> {
return getAccount(npsso, username);
}

export async function updateAccount(account: PsnAccount): Promise<PsnAccount> {
Expand Down Expand Up @@ -86,15 +86,15 @@ interface BasicPresenceResponse {
}
}

async function getAccount(npsso: string): Promise<PsnAccount> {
async function getAccount(npsso: string, username?: string): Promise<PsnAccount> {
const accessCode = await psnApi.exchangeNpssoForCode(npsso);

const authorization = await psnApi.exchangeCodeForAccessToken(accessCode);

const { profile } = await psnApi.getProfileFromUserName(authorization, 'me');

const account: PsnAccount = {
accountName: profile.onlineId,
accountName: username ?? profile.onlineId,
accountId: profile.accountId,
npsso,
authInfo: convertAuthResponseToAuthInfo(authorization)
Expand Down Expand Up @@ -130,7 +130,7 @@ async function getAccountActivity({ accountId, authInfo }: PsnAccount): Promise<
launchPlatform: activeTitle.launchPlatform.toUpperCase() as NormalizedDeviceType,
}
} else {
if(response.status >= 400 && response.status < 600) {
if (response.status >= 400 && response.status < 600) {
debug(`Unable to retrieve PSN information. API response: "${response.status}:${response.statusText}"`)
}
return undefined;
Expand Down
10 changes: 5 additions & 5 deletions ps5-mqtt/server/src/redux/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { merge } from "lodash";
import _ from "lodash";
import type { AnyAction, State } from "./types";

const defaultState: State = {
Expand All @@ -9,21 +9,21 @@ const defaultState: State = {
const reducer = (state = defaultState, action: AnyAction) => {
switch (action.type) {
case "ADD_DEVICE": {
return merge({}, state, {
return _.merge({}, state, {
devices: {
[action.payload.id]: action.payload,
},
});
}

case "UPDATE_HOME_ASSISTANT": {
const newState = merge({}, state);
const newState = _.merge({}, state);
newState.devices[action.payload.id] = action.payload;
return newState;
}

case "TRANSITIONING": {
return merge({}, state, {
return _.merge({}, state, {
devices: {
[action.payload.id]: {
transitioning: action.payload.transitioning,
Expand All @@ -33,7 +33,7 @@ const reducer = (state = defaultState, action: AnyAction) => {
}

case "UPDATE_PSN_ACCOUNT": {
return merge({}, state, {
return _.merge({}, state, {
accounts: {
[action.payload.accountId]: action.payload,
},
Expand Down
1 change: 0 additions & 1 deletion ps5-mqtt/server/src/redux/sagas/check-psn-presence.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { merge } from "lodash";
import { call, put, select } from "redux-saga/effects";
import { PsnAccount } from "../../psn-account";
import { createErrorLogger } from "../../util/error-logger";
Expand Down
4 changes: 2 additions & 2 deletions ps5-mqtt/server/src/redux/sagas/delay-for-transition.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import createDebugger from "debug"
import { merge } from "lodash"
import lodash from "lodash"
import { delay, put } from "redux-saga/effects"
import { pollDevices, pollPsnPresence, setTransitioning } from "../action-creators"
import type { SetTransitioningAction } from "../types"
Expand All @@ -11,7 +11,7 @@ function* delayForTransition(action: SetTransitioningAction) {
yield delay(15000)
debug("Resume polling")
yield put(
setTransitioning(merge({}, action.payload, { transitioning: false }))
setTransitioning(lodash.merge({}, action.payload, { transitioning: false }))
);
} else {
yield put(pollDevices());
Expand Down
Loading