Skip to content

Commit

Permalink
Configurable API endpoint (#99)
Browse files Browse the repository at this point in the history
* more

* more

* more
  • Loading branch information
prosif authored Nov 13, 2024
1 parent a252020 commit 141a147
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 38 deletions.
33 changes: 24 additions & 9 deletions src/dashboard/HomegamesDashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const https = require('https');
const path = require('path');
const fs = require('fs');

const { getConfigValue, getAppDataPath, log } = require('homegames-common');

const { Asset, Game, ViewableGame, GameNode, Colors, ShapeUtils, Shapes, squish, unsquish, ViewUtils } = require('squish-1009');

const squishMap = require('../common/squish-map');
Expand All @@ -13,6 +15,13 @@ const gameModal = require('./game-modal');

const COLORS = Colors.COLORS;

const API_URL = getConfigValue('API_URL', 'https://api.homegames.io:443');

console.log("API URL " + API_URL);

const parsedUrl = new URL(API_URL);
const isSecure = parsedUrl.protocol == 'https:';

const { ExpiringSet, animations } = require('../common/util');

const gameOption = require('./game-option');
Expand All @@ -23,8 +32,6 @@ if (baseDir.endsWith('src')) {
baseDir = baseDir.substring(0, baseDir.length - 3);
}

const { getConfigValue, getAppDataPath, log } = require('homegames-common');

const serverPortMin = getConfigValue('GAME_SERVER_PORT_RANGE_MIN', 7002);
const serverPortMax = getConfigValue('GAME_SERVER_PORT_RANGE_MAX', 7099);

Expand Down Expand Up @@ -124,7 +131,7 @@ if (!fs.existsSync(DOWNLOADED_GAME_DIRECTORY)) {

const networkHelper = {
searchGames: (q) => new Promise((resolve, reject) => {
getUrl('https://api.homegames.io/games?query=' + q).then(response => {
getUrl(`${API_URL}/games?query=${q}`).then(response => {
let results;
try {
results = JSON.parse(response);
Expand All @@ -135,11 +142,13 @@ const networkHelper = {
resolve(results);
}).catch(err => {
log.error('Error searching games', err);
console.log('huh lol');
console.log(err);
reject(err);
});
}),
getGameDetails: (gameId) => new Promise((resolve, reject) => {
getUrl('https://api.homegames.io/games/' + gameId).then(response => {
getUrl(`${API_URL}/games/${gameId}`).then(response => {
let results;
try {
results = JSON.parse(response);
Expand All @@ -154,7 +163,7 @@ const networkHelper = {
});
}),
getGameVersionDetails: (gameId, versionId) => new Promise((resolve, reject) => {
getUrl('https://api.homegames.io/games/' + gameId + '/version/' + versionId).then(response => {
getUrl(`${API_URL}/games/${gameId}/version/${versionId}`).then(response => {
resolve(JSON.parse(response));
}).catch(err => {
log.error(err);
Expand Down Expand Up @@ -237,6 +246,7 @@ const getGameMap = () => {
metadata: {
name: gameMetadata.name || gameClass.name,
thumbnail: gameMetadata.thumbnail,
thumbnailSource: gameMetadata.thumbnailSource,
author: gameMetadata.createdBy || 'Unknown author',
isTest: gameMetadata.isTest || false
},
Expand Down Expand Up @@ -301,6 +311,7 @@ const getGameMap = () => {
metadata: {
name: gameMetadata.name || gameClass.name,
thumbnail: gameMetadata.thumbnail,
thumbnailSource: gameMetadata.thumbnailSource,
author: gameMetadata.createdBy || 'Unknown author'
},
versions: {
Expand Down Expand Up @@ -366,6 +377,7 @@ class HomegamesDashboard extends ViewableGame {
Object.keys(this.localGames).filter(k => this.localGames[k].metadata && this.localGames[k].metadata.thumbnail).forEach(key => {
this.assets[key] = new Asset({
'id': this.localGames[key].metadata && this.localGames[key].metadata.thumbnail,
'source': this.localGames[key].metadata && this.localGames[key].metadata.thumbnailSource,
'type': 'image'
});
});
Expand Down Expand Up @@ -764,7 +776,8 @@ class HomegamesDashboard extends ViewableGame {
metadata: {
name: localGameMetadata.name || key,
author: localGameMetadata.author,
thumbnail: localGameMetadata.thumbnail
thumbnail: localGameMetadata.thumbnail,
thumbnailSource: localGameMetadata.thumbnailSource
}
}
}
Expand Down Expand Up @@ -1027,8 +1040,9 @@ class HomegamesDashboard extends ViewableGame {
}

downloadGame({ gameDetails, version }) {
const { id: gameId, description, name, createdBy, createdAt } = gameDetails;
const { versionId, location, isReviewed } = version;
const { id: gameId, description, name, developerId: createdBy, created: createdAt } = gameDetails.game;
const { id: versionId, assetId, isReviewed } = version;
const location = `${API_URL}/assets/${assetId}`;

const metadataToStore = {
version: {
Expand Down Expand Up @@ -1069,14 +1083,15 @@ class HomegamesDashboard extends ViewableGame {
Object.keys(this.localGames).filter(k => this.localGames[k].metadata && this.localGames[k].metadata.thumbnail).forEach(key => {
this.assets[key] = new Asset({
'id': this.localGames[key].metadata && this.localGames[key].metadata.thumbnail,
'source': this.localGames[key].metadata && this.localGames[key].metadata.thumbnailSource,
'type': 'image'
});
});
resolve(indexPath);
});
});

https.get(location, (res) => {
(API_URL.startsWith('https') ? https : http).get(location, (res) => {
res.pipe(zipWriteStream);
zipWriteStream.on('finish', () => {
zipWriteStream.close();
Expand Down
2 changes: 1 addition & 1 deletion src/dashboard/game-modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { fork } = require('child_process');
const http = require('http');
const https = require('https');
const path = require('path');
const { Game, ViewableGame, GameNode, Colors, ShapeUtils, Shapes, squish, unsquish, ViewUtils } = require('squish-1006');
const { Game, ViewableGame, GameNode, Colors, ShapeUtils, Shapes, squish, unsquish, ViewUtils } = require('squish-1009');

const fs = require('fs');

Expand Down
2 changes: 1 addition & 1 deletion src/dashboard/game-option.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { fork } = require('child_process');
const http = require('http');
const https = require('https');
const path = require('path');
const { Asset, Game, ViewableGame, GameNode, Colors, ShapeUtils, Shapes, squish, unsquish, ViewUtils } = require('squish-1006');
const { Asset, Game, ViewableGame, GameNode, Colors, ShapeUtils, Shapes, squish, unsquish, ViewUtils } = require('squish-1009');

const fs = require('fs');
const gameModal = require('./game-modal');
Expand Down
10 changes: 5 additions & 5 deletions src/games/infinite-questions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,13 +242,13 @@ class InfiniteQuestions extends Game {
const keywordString = keywords.join(',');

this.contentGenerator.requestContent({
model: 'mistral-7b-instruct-v0.2',
model: 'mistral-7b-v0.2',
prompt: `Generate 5 conversation starter questions in JSON format. The response should contain only JSON with a single key "questions" containing a list of strings. The questions should be about the following topics: ${keywordString}.`
}).then((_contentJson) => {
}).then((_content) => {
// it doesnt _just_ give json of course
const leftParenIndex = _contentJson.response.lastIndexOf('{');
const rightParenIndex = _contentJson.response.lastIndexOf('}');
const contentJson = JSON.parse(_contentJson.response.substring(leftParenIndex, rightParenIndex + 1));
const leftParenIndex = _content.lastIndexOf('{');
const rightParenIndex = _content.lastIndexOf('}');
const contentJson = JSON.parse(_content.substring(leftParenIndex, rightParenIndex + 1));
this.content = contentJson;
this.error = null;
this.loading = false;
Expand Down
26 changes: 15 additions & 11 deletions src/services/index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
const http = require('http');
const https = require('https');

const { getConfigValue } = require('homegames-common');

const services = {};

const API_URL = getConfigValue('API_URL', 'https://api.homegames.io:443');

const parsedUrl = new URL(API_URL);
const isSecure = parsedUrl.protocol == 'https:';

const supportedServices = {
'contentGenerator': {
requestContent: (request) => new Promise((resolve, reject) => {
const makePost = (path, _payload) => new Promise((resolve, reject) => {
const payload = JSON.stringify(_payload);

let module, hostname, port;

module = https;
port = 443;
hostname = 'api.homegames.io';
const module = isSecure ? https : http;
const port = parsedUrl.port || isSecure ? 443 : 80;
const hostname = parsedUrl.hostname;

const headers = {};

Expand Down Expand Up @@ -46,24 +51,23 @@ const supportedServices = {
req.end();
});

makePost('https://api.homegames.io/services', { type: 'content-generation', ...request }).then((response) => {
makePost(`${API_URL}/services`, { type: 'content-generation', ...request }).then((response) => {
if (!response.startsWith('{')) {
reject(response);
} else {
const requestId = JSON.parse(response).requestId;
const interval = setInterval(() => {
https.get(`https://api.homegames.io/service_requests/${requestId}`, {}, (res) => {
https.get(`${API_URL}/service_requests/${requestId}`, {}, (res) => {
let bufs = [];
res.on('data', (chunk) => {
bufs.push(chunk);
});

res.on('end', () => {
const fin = JSON.parse(Buffer.concat(bufs));
const parsed = fin;//JSON.parse(fin);
if (parsed.response) {
const r = JSON.parse(Buffer.concat(bufs));
if (r.response) {
clearInterval(interval);
resolve(parsed.response);
resolve(r.response);
}
});
});
Expand Down
12 changes: 9 additions & 3 deletions src/util/homenames-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@ if (baseDir.endsWith('/src')) {

const { getConfigValue, getUserHash, log } = require('homegames-common');

const API_URL = getConfigValue('API_URL', 'https://api.homegames.io:443');
const parsedUrl = new URL(API_URL);

const isSecure = parsedUrl.protocol == 'https:';

const HTTPS_ENABLED = getConfigValue('HTTPS_ENABLED', false);

const DOMAIN_NAME = getConfigValue('DOMAIN_NAME', null);
const CERT_DOMAIN = getConfigValue('CERT_DOMAIN', null);

const getLocalIP = () => {
const ifaces = os.networkInterfaces();
Expand All @@ -32,7 +38,7 @@ const getLocalIP = () => {
};

const getPublicIP = () => new Promise((resolve, reject) => {
https.get(`https://api.homegames.io/ip`, (res) => {
(isSecure ? https : http).get(`${API_URL}/ip`, (res) => {
let buf = '';
res.on('data', (chunk) => {
buf += chunk.toString();
Expand All @@ -48,7 +54,7 @@ const makeGet = (path = '', headers = {}, username) => new Promise((resolve, rej
const protocol = HTTPS_ENABLED ? 'https' : 'http';
// todo: fix
getPublicIP().then(publicIp => {
const host = HTTPS_ENABLED ? (DOMAIN_NAME || (getUserHash(publicIp) + '.homegames.link')) : 'localhost';
const host = HTTPS_ENABLED ? (DOMAIN_NAME || (`${getUserHash(publicIp)}.${CERT_DOMAIN}`)) : 'localhost';
const base = `${protocol}://${host}:${getConfigValue('HOMENAMES_PORT')}`;

(HTTPS_ENABLED ? https : http).get(`${base}${path}`, (res) => {
Expand All @@ -73,7 +79,7 @@ const makePost = (path, _payload, username) => new Promise((resolve, reject) =>
port = getConfigValue('HOMENAMES_PORT');

getPublicIP().then(publicIp => {
hostname = HTTPS_ENABLED ? (DOMAIN_NAME || (getUserHash(publicIp) + '.homegames.link')) : 'localhost';
hostname = HTTPS_ENABLED ? (DOMAIN_NAME || (`${getUserHash(publicIp)}.${CERT_DOMAIN}`)) : 'localhost';

const headers = {};

Expand Down
12 changes: 10 additions & 2 deletions src/util/link-helper.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { log } = require('homegames-common');

const WebSocket = require('ws');
const http = require('http');
const https = require('https');
const os = require('os');
const fs = require('fs');
Expand All @@ -14,8 +15,12 @@ if (baseDir.endsWith('src')) {

const { getConfigValue } = require('homegames-common');

const API_URL = getConfigValue('API_URL', 'https://api.homegames.io:443');
const parsedUrl = new URL(API_URL);
const isSecure = parsedUrl.protocol == 'https:';

const getPublicIP = () => new Promise((resolve, reject) => {
https.get(`https://api.homegames.io/ip`, (res) => {
(isSecure ? https : http).get(`${API_URL}/ip`, (res) => {
let buf = '';
res.on('data', (chunk) => {
buf += chunk.toString();
Expand Down Expand Up @@ -55,8 +60,10 @@ const getClientInfo = () => new Promise((resolve, reject) => {
});
});

const LINK_URL = getConfigValue('LINK_URL', `wss://homegames.link`);

const linkConnect = (msgHandler) => new Promise((resolve, reject) => {
const client = new WebSocket('wss://homegames.link');
const client = new WebSocket(LINK_URL);

let interval;

Expand Down Expand Up @@ -88,6 +95,7 @@ const linkConnect = (msgHandler) => new Promise((resolve, reject) => {
client.on('message', msgHandler ? msgHandler : () => {});

client.on('error', (err) => {
console.log(err);
log.error('Link client error');
log.error(err);
reject(err);
Expand Down
18 changes: 12 additions & 6 deletions src/util/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ if (baseDir.endsWith('src')) {

const { getConfigValue, log, getUserHash } = require('homegames-common');

const API_URL = getConfigValue('API_URL', 'https://api.homegames.io:443');

const LINK_PROXY_URL = getConfigValue('LINK_PROXY_URL', 'wss://public.homegames.link:81');

const parsedUrl = new URL(API_URL);
const isSecure = parsedUrl.protocol == 'https:';

const HOMENAMES_PORT = getConfigValue('HOMENAMES_PORT', 7100);
const BEZEL_SIZE_X = getConfigValue('BEZEL_SIZE_X', 15);
const _BEZEL_SIZE_Y = getConfigValue('BEZEL_SIZE_Y', 15);
Expand All @@ -23,9 +30,10 @@ const HOTLOAD_ENABLED = getConfigValue('HOTLOAD_ENABLED', false);
const BEZEL_SIZE_Y = getConfigValue('BEZEL_SIZE_Y', 15);

const DOMAIN_NAME = getConfigValue('DOMAIN_NAME', null);
const CERT_DOMAIN = getConfigValue('CERT_DOMAIN', null);

const getPublicIP = () => new Promise((resolve, reject) => {
https.get(`https://api.homegames.io/ip`, (res) => {
(isSecure ? https : http).get(`${API_URL}/ip`, (res) => {
let buf = '';
res.on('data', (chunk) => {
buf += chunk.toString();
Expand Down Expand Up @@ -67,9 +75,6 @@ const listenable = function(obj, onChange) {
const change = Reflect.deleteProperty(target, property);
onChange && onChange();
return change;
},
ayy() {
console.log('i am ayy');
}
};

Expand Down Expand Up @@ -114,13 +119,14 @@ const generateProxyPlayerId = () => {
};

const broadcast = (gameSession) => {
const proxyServer = new WebSocket('wss://public.homegames.link:81');
const proxyServer = new WebSocket(LINK_PROXY_URL);

proxyServer.on('open', () => {
log.info('Opened connection to proxy server');
});

proxyServer.on('error', (err) => {
console.log(err);
log.error(err);
log.info('Unable to connect to proxy server. Public games will be unavailable.');
});
Expand Down Expand Up @@ -256,7 +262,7 @@ const socketServer = (gameSession, port, cb = null, certPath = null, username =

const requestedGame = jsonMessage.clientInfo && jsonMessage.clientInfo.requestedGame;
const req = (certPath ? https : http).request({
hostname: certPath ? (DOMAIN_NAME || (getUserHash(publicIp)+ '.homegames.link')) : 'localhost',
hostname: certPath ? (DOMAIN_NAME || (`${getUserHash(publicIp)}.${CERT_DOMAIN}`)) : 'localhost',
port: HOMENAMES_PORT,
path: `/info/${ws.id}`,
method: 'GET'
Expand Down

0 comments on commit 141a147

Please sign in to comment.