Compare commits
No commits in common. "master" and "pixi.js" have entirely different histories.
36 changed files with 429 additions and 988 deletions
1
build/public/assets/index.19dfb063.js
Normal file
1
build/public/assets/index.19dfb063.js
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -4,7 +4,7 @@
|
|||
<meta charset="UTF-8">
|
||||
|
||||
<title>🧩 jigsaw.hyottoko.club</title>
|
||||
<script type="module" crossorigin src="/assets/index.63ff8630.js"></script>
|
||||
<script type="module" crossorigin src="/assets/index.19dfb063.js"></script>
|
||||
<link rel="modulepreload" href="/assets/vendor.684f7bc8.js">
|
||||
<link rel="stylesheet" href="/assets/index.22dc307c.css">
|
||||
</head>
|
||||
|
|
|
|||
|
|
@ -155,7 +155,6 @@ function encodeGame(data) {
|
|||
data.scoreMode,
|
||||
data.shapeMode,
|
||||
data.snapMode,
|
||||
data.creatorUserId,
|
||||
];
|
||||
}
|
||||
function decodeGame(data) {
|
||||
|
|
@ -171,7 +170,6 @@ function decodeGame(data) {
|
|||
scoreMode: data[6],
|
||||
shapeMode: data[7],
|
||||
snapMode: data[8],
|
||||
creatorUserId: data[9],
|
||||
};
|
||||
}
|
||||
function coordByPieceIdx(info, pieceIdx) {
|
||||
|
|
@ -342,8 +340,6 @@ const INPUT_EV_REPLAY_SPEED_UP = 13;
|
|||
const INPUT_EV_REPLAY_SPEED_DOWN = 14;
|
||||
const INPUT_EV_TOGGLE_PLAYER_NAMES = 15;
|
||||
const INPUT_EV_CENTER_FIT_PUZZLE = 16;
|
||||
const INPUT_EV_TOGGLE_FIXED_PIECES = 17;
|
||||
const INPUT_EV_TOGGLE_LOOSE_PIECES = 18;
|
||||
const CHANGE_DATA = 1;
|
||||
const CHANGE_TILE = 2;
|
||||
const CHANGE_PLAYER = 3;
|
||||
|
|
@ -372,8 +368,6 @@ var Protocol = {
|
|||
INPUT_EV_REPLAY_SPEED_DOWN,
|
||||
INPUT_EV_TOGGLE_PLAYER_NAMES,
|
||||
INPUT_EV_CENTER_FIT_PUZZLE,
|
||||
INPUT_EV_TOGGLE_FIXED_PIECES,
|
||||
INPUT_EV_TOGGLE_LOOSE_PIECES,
|
||||
CHANGE_DATA,
|
||||
CHANGE_TILE,
|
||||
CHANGE_PLAYER,
|
||||
|
|
@ -612,16 +606,12 @@ function setEvtInfo(gameId, playerId, evtInfo) {
|
|||
}
|
||||
function getAllGames() {
|
||||
return Object.values(GAMES).sort((a, b) => {
|
||||
const finished = isFinished(a.id);
|
||||
// when both have same finished state, sort by started
|
||||
if (finished === isFinished(b.id)) {
|
||||
if (finished) {
|
||||
return b.puzzle.data.finished - a.puzzle.data.finished;
|
||||
}
|
||||
if (isFinished(a.id) === isFinished(b.id)) {
|
||||
return b.puzzle.data.started - a.puzzle.data.started;
|
||||
}
|
||||
// otherwise, sort: unfinished, finished
|
||||
return finished ? 1 : -1;
|
||||
return isFinished(a.id) ? 1 : -1;
|
||||
});
|
||||
}
|
||||
function getAllPlayers(gameId) {
|
||||
|
|
@ -636,12 +626,10 @@ function getPieceCount(gameId) {
|
|||
return GAMES[gameId].puzzle.tiles.length;
|
||||
}
|
||||
function getImageUrl(gameId) {
|
||||
const imageUrl = GAMES[gameId].puzzle.info.image?.url
|
||||
|| GAMES[gameId].puzzle.info.imageUrl;
|
||||
if (!imageUrl) {
|
||||
throw new Error('[2021-07-11] no image url set');
|
||||
return GAMES[gameId].puzzle.info.imageUrl;
|
||||
}
|
||||
return imageUrl;
|
||||
function setImageUrl(gameId, imageUrl) {
|
||||
GAMES[gameId].puzzle.info.imageUrl = imageUrl;
|
||||
}
|
||||
function getScoreMode(gameId) {
|
||||
return GAMES[gameId].scoreMode;
|
||||
|
|
@ -1255,6 +1243,7 @@ var GameCommon = {
|
|||
getFinishedPiecesCount,
|
||||
getPieceCount,
|
||||
getImageUrl,
|
||||
setImageUrl,
|
||||
get: get$1,
|
||||
getAllGames,
|
||||
getPlayerBgColor,
|
||||
|
|
@ -1360,7 +1349,6 @@ const get = (gameId, offset = 0) => {
|
|||
log[0][5] = DefaultScoreMode(log[0][5]);
|
||||
log[0][6] = DefaultShapeMode(log[0][6]);
|
||||
log[0][7] = DefaultSnapMode(log[0][7]);
|
||||
log[0][8] = log[0][8] || null;
|
||||
}
|
||||
return log;
|
||||
};
|
||||
|
|
@ -1370,8 +1358,6 @@ var GameLog = {
|
|||
exists,
|
||||
log: _log,
|
||||
get,
|
||||
filename,
|
||||
idxname,
|
||||
};
|
||||
|
||||
const log$4 = logger('Images.ts');
|
||||
|
|
@ -1446,8 +1432,8 @@ const imageFromDb = (db, imageId) => {
|
|||
const i = db.get('images', { id: imageId });
|
||||
return {
|
||||
id: i.id,
|
||||
uploaderUserId: i.uploader_user_id,
|
||||
filename: i.filename,
|
||||
file: `${UPLOAD_DIR}/${i.filename}`,
|
||||
url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`,
|
||||
title: i.title,
|
||||
tags: getTags(db, i.id),
|
||||
|
|
@ -1485,8 +1471,8 @@ inner join images i on i.id = ixc.image_id ${where.sql};
|
|||
const images = db.getMany('images', wheresRaw, orderByMap[orderBy]);
|
||||
return images.map(i => ({
|
||||
id: i.id,
|
||||
uploaderUserId: i.uploader_user_id,
|
||||
filename: i.filename,
|
||||
file: `${UPLOAD_DIR}/${i.filename}`,
|
||||
url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`,
|
||||
title: i.title,
|
||||
tags: getTags(db, i.id),
|
||||
|
|
@ -1503,8 +1489,8 @@ const allImagesFromDisk = (tags, sort) => {
|
|||
.filter(f => f.toLowerCase().match(/\.(jpe?g|webp|png)$/))
|
||||
.map(f => ({
|
||||
id: 0,
|
||||
uploaderUserId: null,
|
||||
filename: f,
|
||||
file: `${UPLOAD_DIR}/${f}`,
|
||||
url: `${UPLOAD_URL}/${encodeURIComponent(f)}`,
|
||||
title: f.replace(/\.[a-z]+$/, ''),
|
||||
tags: [],
|
||||
|
|
@ -1515,12 +1501,12 @@ const allImagesFromDisk = (tags, sort) => {
|
|||
switch (sort) {
|
||||
case 'alpha_asc':
|
||||
images = images.sort((a, b) => {
|
||||
return a.filename > b.filename ? 1 : -1;
|
||||
return a.file > b.file ? 1 : -1;
|
||||
});
|
||||
break;
|
||||
case 'alpha_desc':
|
||||
images = images.sort((a, b) => {
|
||||
return a.filename < b.filename ? 1 : -1;
|
||||
return a.file < b.file ? 1 : -1;
|
||||
});
|
||||
break;
|
||||
case 'date_asc':
|
||||
|
|
@ -1566,7 +1552,7 @@ var Images = {
|
|||
// final resized version of the puzzle image
|
||||
const TILE_SIZE = 64;
|
||||
async function createPuzzle(rng, targetTiles, image, ts, shapeMode) {
|
||||
const imagePath = `${UPLOAD_DIR}/${image.filename}`;
|
||||
const imagePath = image.file;
|
||||
const imageUrl = image.url;
|
||||
// determine puzzle information from the image dimensions
|
||||
const dim = await Images.getDimensions(imagePath);
|
||||
|
|
@ -1665,7 +1651,6 @@ async function createPuzzle(rng, targetTiles, image, ts, shapeMode) {
|
|||
// information that was used to create the puzzle
|
||||
targetTiles: targetTiles,
|
||||
imageUrl,
|
||||
image: image,
|
||||
width: info.width,
|
||||
height: info.height,
|
||||
tileSize: info.tileSize,
|
||||
|
|
@ -1756,63 +1741,7 @@ function setDirty(gameId) {
|
|||
function setClean(gameId) {
|
||||
delete dirtyGames[gameId];
|
||||
}
|
||||
function loadGamesFromDb(db) {
|
||||
const gameRows = db.getMany('games');
|
||||
for (const gameRow of gameRows) {
|
||||
loadGameFromDb(db, gameRow.id);
|
||||
}
|
||||
}
|
||||
function loadGameFromDb(db, gameId) {
|
||||
const gameRow = db.get('games', { id: gameId });
|
||||
let game;
|
||||
try {
|
||||
game = JSON.parse(gameRow.data);
|
||||
}
|
||||
catch {
|
||||
log$3.log(`[ERR] unable to load game from db ${gameId}`);
|
||||
}
|
||||
if (typeof game.puzzle.data.started === 'undefined') {
|
||||
game.puzzle.data.started = gameRow.created;
|
||||
}
|
||||
if (typeof game.puzzle.data.finished === 'undefined') {
|
||||
game.puzzle.data.finished = gameRow.finished;
|
||||
}
|
||||
if (!Array.isArray(game.players)) {
|
||||
game.players = Object.values(game.players);
|
||||
}
|
||||
const gameObject = storeDataToGame(game, game.creator_user_id);
|
||||
GameCommon.setGame(gameObject.id, gameObject);
|
||||
}
|
||||
function persistGamesToDb(db) {
|
||||
for (const gameId of Object.keys(dirtyGames)) {
|
||||
persistGameToDb(db, gameId);
|
||||
}
|
||||
}
|
||||
function persistGameToDb(db, gameId) {
|
||||
const game = GameCommon.get(gameId);
|
||||
if (!game) {
|
||||
log$3.error(`[ERROR] unable to persist non existing game ${gameId}`);
|
||||
return;
|
||||
}
|
||||
if (game.id in dirtyGames) {
|
||||
setClean(game.id);
|
||||
}
|
||||
db.upsert('games', {
|
||||
id: game.id,
|
||||
creator_user_id: game.creatorUserId,
|
||||
image_id: game.puzzle.info.image?.id,
|
||||
created: game.puzzle.data.started,
|
||||
finished: game.puzzle.data.finished,
|
||||
data: gameToStoreData(game)
|
||||
}, {
|
||||
id: game.id,
|
||||
});
|
||||
log$3.info(`[INFO] persisted game ${game.id}`);
|
||||
}
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
function loadGamesFromDisk() {
|
||||
function loadGames() {
|
||||
const files = fs.readdirSync(DATA_DIR);
|
||||
for (const f of files) {
|
||||
const m = f.match(/^([a-z0-9]+)\.json$/);
|
||||
|
|
@ -1820,13 +1749,10 @@ function loadGamesFromDisk() {
|
|||
continue;
|
||||
}
|
||||
const gameId = m[1];
|
||||
loadGameFromDisk(gameId);
|
||||
loadGame(gameId);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
function loadGameFromDisk(gameId) {
|
||||
function loadGame(gameId) {
|
||||
const file = `${DATA_DIR}/${gameId}.json`;
|
||||
const contents = fs.readFileSync(file, 'utf-8');
|
||||
let game;
|
||||
|
|
@ -1848,21 +1774,27 @@ function loadGameFromDisk(gameId) {
|
|||
if (!Array.isArray(game.players)) {
|
||||
game.players = Object.values(game.players);
|
||||
}
|
||||
const gameObject = storeDataToGame(game, null);
|
||||
const gameObject = {
|
||||
id: game.id,
|
||||
rng: {
|
||||
type: game.rng ? game.rng.type : '_fake_',
|
||||
obj: game.rng ? Rng.unserialize(game.rng.obj) : new Rng(0),
|
||||
},
|
||||
puzzle: game.puzzle,
|
||||
players: game.players,
|
||||
evtInfos: {},
|
||||
scoreMode: DefaultScoreMode(game.scoreMode),
|
||||
shapeMode: DefaultShapeMode(game.shapeMode),
|
||||
snapMode: DefaultSnapMode(game.snapMode),
|
||||
};
|
||||
GameCommon.setGame(gameObject.id, gameObject);
|
||||
}
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
function persistGamesToDisk() {
|
||||
function persistGames() {
|
||||
for (const gameId of Object.keys(dirtyGames)) {
|
||||
persistGameToDisk(gameId);
|
||||
persistGame(gameId);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
function persistGameToDisk(gameId) {
|
||||
function persistGame(gameId) {
|
||||
const game = GameCommon.get(gameId);
|
||||
if (!game) {
|
||||
log$3.error(`[ERROR] unable to persist non existing game ${gameId}`);
|
||||
|
|
@ -1871,27 +1803,7 @@ function persistGameToDisk(gameId) {
|
|||
if (game.id in dirtyGames) {
|
||||
setClean(game.id);
|
||||
}
|
||||
fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, gameToStoreData(game));
|
||||
log$3.info(`[INFO] persisted game ${game.id}`);
|
||||
}
|
||||
function storeDataToGame(storeData, creatorUserId) {
|
||||
return {
|
||||
id: storeData.id,
|
||||
creatorUserId,
|
||||
rng: {
|
||||
type: storeData.rng ? storeData.rng.type : '_fake_',
|
||||
obj: storeData.rng ? Rng.unserialize(storeData.rng.obj) : new Rng(0),
|
||||
},
|
||||
puzzle: storeData.puzzle,
|
||||
players: storeData.players,
|
||||
evtInfos: {},
|
||||
scoreMode: DefaultScoreMode(storeData.scoreMode),
|
||||
shapeMode: DefaultShapeMode(storeData.shapeMode),
|
||||
snapMode: DefaultSnapMode(storeData.snapMode),
|
||||
};
|
||||
}
|
||||
function gameToStoreData(game) {
|
||||
return JSON.stringify({
|
||||
fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, JSON.stringify({
|
||||
id: game.id,
|
||||
rng: {
|
||||
type: game.rng.type,
|
||||
|
|
@ -1902,27 +1814,22 @@ function gameToStoreData(game) {
|
|||
scoreMode: game.scoreMode,
|
||||
shapeMode: game.shapeMode,
|
||||
snapMode: game.snapMode,
|
||||
});
|
||||
}));
|
||||
log$3.info(`[INFO] persisted game ${game.id}`);
|
||||
}
|
||||
var GameStorage = {
|
||||
// disk functions are deprecated
|
||||
loadGamesFromDisk,
|
||||
loadGameFromDisk,
|
||||
persistGamesToDisk,
|
||||
persistGameToDisk,
|
||||
loadGamesFromDb,
|
||||
loadGameFromDb,
|
||||
persistGamesToDb,
|
||||
persistGameToDb,
|
||||
loadGames,
|
||||
loadGame,
|
||||
persistGames,
|
||||
persistGame,
|
||||
setDirty,
|
||||
};
|
||||
|
||||
async function createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode, creatorUserId) {
|
||||
async function createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode) {
|
||||
const seed = Util.hash(gameId + ' ' + ts);
|
||||
const rng = new Rng(seed);
|
||||
return {
|
||||
id: gameId,
|
||||
creatorUserId,
|
||||
rng: { type: 'Rng', obj: rng },
|
||||
puzzle: await createPuzzle(rng, targetTiles, image, ts, shapeMode),
|
||||
players: [],
|
||||
|
|
@ -1932,10 +1839,10 @@ async function createGameObject(gameId, targetTiles, image, ts, scoreMode, shape
|
|||
snapMode,
|
||||
};
|
||||
}
|
||||
async function createGame(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode, creatorUserId) {
|
||||
const gameObject = await createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode, creatorUserId);
|
||||
async function createGame(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode) {
|
||||
const gameObject = await createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode);
|
||||
GameLog.create(gameId, ts);
|
||||
GameLog.log(gameId, Protocol.LOG_HEADER, 1, targetTiles, image, ts, scoreMode, shapeMode, snapMode, gameObject.creatorUserId);
|
||||
GameLog.log(gameId, Protocol.LOG_HEADER, 1, targetTiles, image, ts, scoreMode, shapeMode, snapMode);
|
||||
GameCommon.setGame(gameObject.id, gameObject);
|
||||
GameStorage.setDirty(gameId);
|
||||
}
|
||||
|
|
@ -2181,13 +2088,6 @@ const storage = multer.diskStorage({
|
|||
}
|
||||
});
|
||||
const upload = multer({ storage }).single('file');
|
||||
app.get('/api/me', (req, res) => {
|
||||
let user = getUser(db, req);
|
||||
res.send({
|
||||
id: user ? user.id : null,
|
||||
created: user ? user.created : null,
|
||||
});
|
||||
});
|
||||
app.get('/api/conf', (req, res) => {
|
||||
res.send({
|
||||
WS_ADDRESS: config.ws.connectstring,
|
||||
|
|
@ -2214,8 +2114,7 @@ app.get('/api/replay-data', async (req, res) => {
|
|||
let game = null;
|
||||
if (offset === 0) {
|
||||
// also need the game
|
||||
game = await Game.createGameObject(gameId, log[0][2], log[0][3], // must be ImageInfo
|
||||
log[0][4], log[0][5], log[0][6], log[0][7], log[0][8]);
|
||||
game = await Game.createGameObject(gameId, log[0][2], log[0][3], log[0][4], log[0][5], log[0][6], log[0][7]);
|
||||
}
|
||||
res.send({ log, game: game ? Util.encodeGame(game) : null });
|
||||
});
|
||||
|
|
@ -2246,28 +2145,6 @@ app.get('/api/index-data', (req, res) => {
|
|||
gamesFinished: games.filter(g => !!g.finished),
|
||||
});
|
||||
});
|
||||
const getOrCreateUser = (db, req) => {
|
||||
let user = getUser(db, req);
|
||||
if (!user) {
|
||||
db.insert('users', {
|
||||
'client_id': req.headers['client-id'],
|
||||
'client_secret': req.headers['client-secret'],
|
||||
'created': Time.timestamp(),
|
||||
});
|
||||
user = getUser(db, req);
|
||||
}
|
||||
return user;
|
||||
};
|
||||
const getUser = (db, req) => {
|
||||
let user = db.get('users', {
|
||||
'client_id': req.headers['client-id'],
|
||||
'client_secret': req.headers['client-secret'],
|
||||
});
|
||||
if (user) {
|
||||
user.id = parseInt(user.id, 10);
|
||||
}
|
||||
return user;
|
||||
};
|
||||
const setImageTags = (db, imageId, tags) => {
|
||||
tags.forEach((tag) => {
|
||||
const slug = Util.slug(tag);
|
||||
|
|
@ -2281,17 +2158,7 @@ const setImageTags = (db, imageId, tags) => {
|
|||
});
|
||||
};
|
||||
app.post('/api/save-image', express.json(), (req, res) => {
|
||||
let user = getUser(db, req);
|
||||
if (!user || !user.id) {
|
||||
res.status(403).send({ ok: false, error: 'forbidden' });
|
||||
return;
|
||||
}
|
||||
const data = req.body;
|
||||
let image = db.get('images', { id: data.id });
|
||||
if (parseInt(image.uploader_user_id, 10) !== user.id) {
|
||||
res.status(403).send({ ok: false, error: 'forbidden' });
|
||||
return;
|
||||
}
|
||||
db.update('images', {
|
||||
title: data.title,
|
||||
}, {
|
||||
|
|
@ -2316,10 +2183,8 @@ app.post('/api/upload', (req, res) => {
|
|||
log.log(err);
|
||||
res.status(400).send("Something went wrong!");
|
||||
}
|
||||
const user = getOrCreateUser(db, req);
|
||||
const dim = await Images.getDimensions(`${UPLOAD_DIR}/${req.file.filename}`);
|
||||
const imageId = db.insert('images', {
|
||||
uploader_user_id: user.id,
|
||||
filename: req.file.filename,
|
||||
filename_original: req.file.originalname,
|
||||
title: req.body.title || '',
|
||||
|
|
@ -2335,17 +2200,12 @@ app.post('/api/upload', (req, res) => {
|
|||
});
|
||||
});
|
||||
app.post('/api/newgame', express.json(), async (req, res) => {
|
||||
let user = getOrCreateUser(db, req);
|
||||
if (!user || !user.id) {
|
||||
res.status(403).send({ ok: false, error: 'forbidden' });
|
||||
return;
|
||||
}
|
||||
const gameSettings = req.body;
|
||||
log.log(gameSettings);
|
||||
const gameId = Util.uniqId();
|
||||
if (!GameCommon.exists(gameId)) {
|
||||
const ts = Time.timestamp();
|
||||
await Game.createGame(gameId, gameSettings.tiles, gameSettings.image, ts, gameSettings.scoreMode, gameSettings.shapeMode, gameSettings.snapMode, user.id);
|
||||
await Game.createGame(gameId, gameSettings.tiles, gameSettings.image, ts, gameSettings.scoreMode, gameSettings.shapeMode, gameSettings.snapMode);
|
||||
}
|
||||
res.send({ id: gameId });
|
||||
});
|
||||
|
|
@ -2427,7 +2287,7 @@ wss.on('message', async ({ socket, data }) => {
|
|||
log.error(e);
|
||||
}
|
||||
});
|
||||
GameStorage.loadGamesFromDb(db);
|
||||
GameStorage.loadGames();
|
||||
const server = app.listen(port, hostname, () => log.log(`server running on http://${hostname}:${port}`));
|
||||
wss.listen();
|
||||
const memoryUsageHuman = () => {
|
||||
|
|
@ -2441,7 +2301,7 @@ memoryUsageHuman();
|
|||
// persist games in fixed interval
|
||||
const persistInterval = setInterval(() => {
|
||||
log.log('Persisting games...');
|
||||
GameStorage.persistGamesToDb(db);
|
||||
GameStorage.persistGames();
|
||||
memoryUsageHuman();
|
||||
}, config.persistence.interval);
|
||||
const gracefulShutdown = (signal) => {
|
||||
|
|
@ -2449,7 +2309,7 @@ const gracefulShutdown = (signal) => {
|
|||
log.log('clearing persist interval...');
|
||||
clearInterval(persistInterval);
|
||||
log.log('persisting games...');
|
||||
GameStorage.persistGamesToDb(db);
|
||||
GameStorage.persistGames();
|
||||
log.log('shutting down webserver...');
|
||||
server.close();
|
||||
log.log('shutting down websocketserver...');
|
||||
|
|
|
|||
|
|
@ -1,90 +0,0 @@
|
|||
import GameCommon from '../src/common/GameCommon'
|
||||
import GameLog from '../src/server/GameLog'
|
||||
import { Game } from '../src/common/Types'
|
||||
import { logger } from '../src/common/Util'
|
||||
import { DB_FILE, DB_PATCHES_DIR, UPLOAD_DIR } from '../src/server/Dirs'
|
||||
import Db from '../src/server/Db'
|
||||
import GameStorage from '../src/server/GameStorage'
|
||||
import fs from 'fs'
|
||||
|
||||
const log = logger('fix_games_image_info.ts')
|
||||
|
||||
import Images from '../src/server/Images'
|
||||
|
||||
console.log(DB_FILE)
|
||||
|
||||
const db = new Db(DB_FILE, DB_PATCHES_DIR)
|
||||
db.patch(true)
|
||||
|
||||
// ;(async () => {
|
||||
// let images = db.getMany('images')
|
||||
// for (let image of images) {
|
||||
// console.log(image.filename)
|
||||
// let dim = await Images.getDimensions(`${UPLOAD_DIR}/${image.filename}`)
|
||||
// console.log(await Images.getDimensions(`${UPLOAD_DIR}/${image.filename}`))
|
||||
// image.width = dim.w
|
||||
// image.height = dim.h
|
||||
// db.upsert('images', image, { id: image.id })
|
||||
// }
|
||||
// })()
|
||||
|
||||
function fixOne(gameId: string) {
|
||||
let g = GameCommon.get(gameId)
|
||||
if (!g) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!g.puzzle.info.image && g.puzzle.info.imageUrl) {
|
||||
log.log('game id: ', gameId)
|
||||
const parts = g.puzzle.info.imageUrl.split('/')
|
||||
const fileName = parts[parts.length - 1]
|
||||
const imageRow = db.get('images', {filename: fileName})
|
||||
if (!imageRow) {
|
||||
return
|
||||
}
|
||||
|
||||
g.puzzle.info.image = Images.imageFromDb(db, imageRow.id)
|
||||
|
||||
log.log(g.puzzle.info.image.title, imageRow.id)
|
||||
|
||||
GameStorage.persistGameToDb(db, gameId)
|
||||
} else if (g.puzzle.info.image?.id) {
|
||||
const imageId = g.puzzle.info.image.id
|
||||
|
||||
g.puzzle.info.image = Images.imageFromDb(db, imageId)
|
||||
|
||||
log.log(g.puzzle.info.image.title, imageId)
|
||||
|
||||
GameStorage.persistGameToDb(db, gameId)
|
||||
}
|
||||
|
||||
// fix log
|
||||
const file = GameLog.filename(gameId, 0)
|
||||
if (!fs.existsSync(file)) {
|
||||
return
|
||||
}
|
||||
|
||||
const lines = fs.readFileSync(file, 'utf-8').split("\n")
|
||||
const l = lines.filter(line => !!line).map(line => {
|
||||
return JSON.parse(`[${line}]`)
|
||||
})
|
||||
if (l && l[0] && !l[0][3].id) {
|
||||
log.log(l[0][3])
|
||||
l[0][3] = g.puzzle.info.image
|
||||
const newlines = l.map(ll => {
|
||||
return JSON.stringify(ll).slice(1, -1)
|
||||
}).join("\n") + "\n"
|
||||
console.log(g.puzzle.info.image)
|
||||
// process.exit(0)
|
||||
fs.writeFileSync(file, newlines)
|
||||
}
|
||||
}
|
||||
|
||||
function fix() {
|
||||
GameStorage.loadGamesFromDisk()
|
||||
GameCommon.getAllGames().forEach((game: Game) => {
|
||||
fixOne(game.id)
|
||||
})
|
||||
}
|
||||
|
||||
fix()
|
||||
23
scripts/fix_image.ts
Normal file
23
scripts/fix_image.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import GameCommon from '../src/common/GameCommon'
|
||||
import { logger } from '../src/common/Util'
|
||||
import GameStorage from '../src/server/GameStorage'
|
||||
|
||||
const log = logger('fix_image.js')
|
||||
|
||||
function fix(gameId) {
|
||||
GameStorage.loadGame(gameId)
|
||||
let changed = false
|
||||
|
||||
let imgUrl = GameCommon.getImageUrl(gameId)
|
||||
if (imgUrl.match(/^\/example-images\//)) {
|
||||
log.log(`found bad imgUrl: ${imgUrl}`)
|
||||
imgUrl = imgUrl.replace(/^\/example-images\//, '/uploads/')
|
||||
GameCommon.setImageUrl(gameId, imgUrl)
|
||||
changed = true
|
||||
}
|
||||
if (changed) {
|
||||
GameStorage.persistGame(gameId)
|
||||
}
|
||||
}
|
||||
|
||||
fix(process.argv[2])
|
||||
|
|
@ -1,16 +1,11 @@
|
|||
import GameCommon from '../src/common/GameCommon'
|
||||
import { logger } from '../src/common/Util'
|
||||
import Db from '../src/server/Db'
|
||||
import { DB_FILE, DB_PATCHES_DIR } from '../src/server/Dirs'
|
||||
import GameStorage from '../src/server/GameStorage'
|
||||
|
||||
const log = logger('fix_tiles.js')
|
||||
|
||||
const db = new Db(DB_FILE, DB_PATCHES_DIR)
|
||||
db.patch(true)
|
||||
|
||||
function fix_tiles(gameId) {
|
||||
GameStorage.loadGameFromDb(db, gameId)
|
||||
GameStorage.loadGame(gameId)
|
||||
let changed = false
|
||||
const tiles = GameCommon.getPiecesSortedByZIndex(gameId)
|
||||
for (let tile of tiles) {
|
||||
|
|
@ -32,7 +27,7 @@ function fix_tiles(gameId) {
|
|||
}
|
||||
}
|
||||
if (changed) {
|
||||
GameStorage.persistGameToDb(db, gameId)
|
||||
GameStorage.persistGame(gameId)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,27 +0,0 @@
|
|||
import GameCommon from '../src/common/GameCommon'
|
||||
import { Game } from '../src/common/Types'
|
||||
import { logger } from '../src/common/Util'
|
||||
import { DB_FILE, DB_PATCHES_DIR } from '../src/server/Dirs'
|
||||
import Db from '../src/server/Db'
|
||||
import GameStorage from '../src/server/GameStorage'
|
||||
|
||||
const log = logger('import_games.ts')
|
||||
|
||||
console.log(DB_FILE)
|
||||
|
||||
const db = new Db(DB_FILE, DB_PATCHES_DIR)
|
||||
db.patch(true)
|
||||
|
||||
function run() {
|
||||
GameStorage.loadGamesFromDisk()
|
||||
GameCommon.getAllGames().forEach((game: Game) => {
|
||||
if (!game.puzzle.info.image?.id) {
|
||||
log.error(game.id + " has no image")
|
||||
log.error(game.puzzle.info.image)
|
||||
return
|
||||
}
|
||||
GameStorage.persistGameToDb(db, game.id)
|
||||
})
|
||||
}
|
||||
|
||||
run()
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
#!/bin/sh
|
||||
|
||||
# server for built files
|
||||
nodemon --watch build --max-old-space-size=64 -e js build/server/main.js -c config.json
|
||||
nodemon --max-old-space-size=64 -e js build/server/main.js -c config.json
|
||||
|
|
|
|||
|
|
@ -138,16 +138,12 @@ function setEvtInfo(
|
|||
|
||||
function getAllGames(): Array<Game> {
|
||||
return Object.values(GAMES).sort((a: Game, b: Game) => {
|
||||
const finished = isFinished(a.id)
|
||||
// when both have same finished state, sort by started
|
||||
if (finished === isFinished(b.id)) {
|
||||
if (finished) {
|
||||
return b.puzzle.data.finished - a.puzzle.data.finished
|
||||
}
|
||||
if (isFinished(a.id) === isFinished(b.id)) {
|
||||
return b.puzzle.data.started - a.puzzle.data.started
|
||||
}
|
||||
// otherwise, sort: unfinished, finished
|
||||
return finished ? 1 : -1
|
||||
return isFinished(a.id) ? 1 : -1
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -166,12 +162,11 @@ function getPieceCount(gameId: string): number {
|
|||
}
|
||||
|
||||
function getImageUrl(gameId: string): string {
|
||||
const imageUrl = GAMES[gameId].puzzle.info.image?.url
|
||||
|| GAMES[gameId].puzzle.info.imageUrl
|
||||
if (!imageUrl) {
|
||||
throw new Error('[2021-07-11] no image url set')
|
||||
return GAMES[gameId].puzzle.info.imageUrl
|
||||
}
|
||||
return imageUrl
|
||||
|
||||
function setImageUrl(gameId: string, imageUrl: string): void {
|
||||
GAMES[gameId].puzzle.info.imageUrl = imageUrl
|
||||
}
|
||||
|
||||
function getScoreMode(gameId: string): ScoreMode {
|
||||
|
|
@ -900,6 +895,7 @@ export default {
|
|||
getFinishedPiecesCount,
|
||||
getPieceCount,
|
||||
getImageUrl,
|
||||
setImageUrl,
|
||||
get,
|
||||
getAllGames,
|
||||
getPlayerBgColor,
|
||||
|
|
|
|||
|
|
@ -67,9 +67,6 @@ const INPUT_EV_REPLAY_SPEED_DOWN = 14
|
|||
const INPUT_EV_TOGGLE_PLAYER_NAMES = 15
|
||||
const INPUT_EV_CENTER_FIT_PUZZLE = 16
|
||||
|
||||
const INPUT_EV_TOGGLE_FIXED_PIECES = 17
|
||||
const INPUT_EV_TOGGLE_LOOSE_PIECES = 18
|
||||
|
||||
const CHANGE_DATA = 1
|
||||
const CHANGE_TILE = 2
|
||||
const CHANGE_PLAYER = 3
|
||||
|
|
@ -107,9 +104,6 @@ export default {
|
|||
INPUT_EV_TOGGLE_PLAYER_NAMES,
|
||||
INPUT_EV_CENTER_FIT_PUZZLE,
|
||||
|
||||
INPUT_EV_TOGGLE_FIXED_PIECES,
|
||||
INPUT_EV_TOGGLE_LOOSE_PIECES,
|
||||
|
||||
CHANGE_DATA,
|
||||
CHANGE_TILE,
|
||||
CHANGE_PLAYER,
|
||||
|
|
|
|||
|
|
@ -51,7 +51,6 @@ export type EncodedGame = FixedLengthArray<[
|
|||
ScoreMode,
|
||||
ShapeMode,
|
||||
SnapMode,
|
||||
number|null,
|
||||
]>
|
||||
|
||||
export interface ReplayData {
|
||||
|
|
@ -73,7 +72,6 @@ interface GameRng {
|
|||
|
||||
export interface Game {
|
||||
id: string
|
||||
creatorUserId: number|null
|
||||
players: Array<EncodedPlayer>
|
||||
puzzle: Puzzle
|
||||
evtInfos: Record<string, EvtInfo>
|
||||
|
|
@ -95,7 +93,7 @@ export interface Image {
|
|||
|
||||
export interface GameSettings {
|
||||
tiles: number
|
||||
image: ImageInfo
|
||||
image: Image
|
||||
scoreMode: ScoreMode
|
||||
shapeMode: ShapeMode
|
||||
snapMode: SnapMode
|
||||
|
|
@ -154,24 +152,10 @@ export interface PieceChange {
|
|||
group?: number
|
||||
}
|
||||
|
||||
export interface ImageInfo
|
||||
{
|
||||
id: number
|
||||
uploaderUserId: number|null
|
||||
filename: string
|
||||
url: string
|
||||
title: string
|
||||
tags: Tag[]
|
||||
created: Timestamp
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface PuzzleInfo {
|
||||
table: PuzzleTable
|
||||
targetTiles: number
|
||||
imageUrl?: string // deprecated, use image.url instead
|
||||
image?: ImageInfo
|
||||
targetTiles: number,
|
||||
imageUrl: string
|
||||
|
||||
width: number
|
||||
height: number
|
||||
|
|
|
|||
|
|
@ -133,7 +133,6 @@ function encodeGame(data: Game): EncodedGame {
|
|||
data.scoreMode,
|
||||
data.shapeMode,
|
||||
data.snapMode,
|
||||
data.creatorUserId,
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -150,7 +149,6 @@ function decodeGame(data: EncodedGame): Game {
|
|||
scoreMode: data[6],
|
||||
shapeMode: data[7],
|
||||
snapMode: data[8],
|
||||
creatorUserId: data[9],
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,45 +0,0 @@
|
|||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
||||
created TIMESTAMP NOT NULL,
|
||||
|
||||
client_id TEXT NOT NULL,
|
||||
client_secret TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE images_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uploader_user_id INTEGER,
|
||||
|
||||
created TIMESTAMP NOT NULL,
|
||||
|
||||
filename TEXT NOT NULL UNIQUE,
|
||||
filename_original TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
|
||||
width INTEGER NOT NULL,
|
||||
height INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE image_x_category_new (
|
||||
image_id INTEGER NOT NULL,
|
||||
category_id INTEGER NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO images_new
|
||||
SELECT id, NULL, created, filename, filename_original, title, width, height
|
||||
FROM images;
|
||||
|
||||
INSERT INTO image_x_category_new
|
||||
SELECT image_id, category_id
|
||||
FROM image_x_category;
|
||||
|
||||
PRAGMA foreign_keys = OFF;
|
||||
|
||||
DROP TABLE images;
|
||||
DROP TABLE image_x_category;
|
||||
|
||||
ALTER TABLE images_new RENAME TO images;
|
||||
ALTER TABLE image_x_category_new RENAME TO image_x_category;
|
||||
|
||||
PRAGMA foreign_keys = ON;
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
CREATE TABLE games (
|
||||
id TEXT PRIMARY KEY,
|
||||
|
||||
creator_user_id INTEGER,
|
||||
image_id INTEGER NOT NULL,
|
||||
|
||||
created TIMESTAMP NOT NULL,
|
||||
finished TIMESTAMP NOT NULL,
|
||||
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
|
|
@ -3,7 +3,6 @@
|
|||
import { ClientEvent, EncodedGame, GameEvent, ReplayData, ServerEvent } from '../common/Types'
|
||||
import Util, { logger } from '../common/Util'
|
||||
import Protocol from './../common/Protocol'
|
||||
import xhr from './xhr'
|
||||
|
||||
const log = logger('Communication.js')
|
||||
|
||||
|
|
@ -118,7 +117,7 @@ async function requestReplayData(
|
|||
offset: number
|
||||
): Promise<ReplayData> {
|
||||
const args = { gameId, offset }
|
||||
const res = await xhr.get(`/api/replay-data${Util.asQueryArgs(args)}`, {})
|
||||
const res = await fetch(`/api/replay-data${Util.asQueryArgs(args)}`)
|
||||
const json: ReplayData = await res.json()
|
||||
return json
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,177 +0,0 @@
|
|||
import Protocol from "../common/Protocol"
|
||||
import { GameEvent } from "../common/Types"
|
||||
import { MODE_REPLAY } from "./game"
|
||||
|
||||
function EventAdapter (
|
||||
canvas: HTMLCanvasElement,
|
||||
window: any,
|
||||
viewport: any,
|
||||
MODE: string
|
||||
) {
|
||||
let events: Array<GameEvent> = []
|
||||
|
||||
let KEYS_ON = true
|
||||
|
||||
let LEFT = false
|
||||
let RIGHT = false
|
||||
let UP = false
|
||||
let DOWN = false
|
||||
let ZOOM_IN = false
|
||||
let ZOOM_OUT = false
|
||||
let SHIFT = false
|
||||
|
||||
const toWorldPoint = (x: number, y: number): [number, number] => {
|
||||
const pos = viewport.viewportToWorld({x, y})
|
||||
return [pos.x, pos.y]
|
||||
}
|
||||
|
||||
const mousePos = (ev: MouseEvent) => toWorldPoint(ev.offsetX, ev.offsetY)
|
||||
const canvasCenter = () => toWorldPoint(canvas.width / 2, canvas.height / 2)
|
||||
|
||||
const key = (state: boolean, ev: KeyboardEvent) => {
|
||||
if (!KEYS_ON) {
|
||||
return
|
||||
}
|
||||
|
||||
if (ev.code === 'ShiftLeft' || ev.code === 'ShiftRight') {
|
||||
SHIFT = state
|
||||
} else if (ev.code === 'ArrowUp' || ev.code === 'KeyW') {
|
||||
UP = state
|
||||
} else if (ev.code === 'ArrowDown' || ev.code === 'KeyS') {
|
||||
DOWN = state
|
||||
} else if (ev.code === 'ArrowLeft' || ev.code === 'KeyA') {
|
||||
LEFT = state
|
||||
} else if (ev.code === 'ArrowRight' || ev.code === 'KeyD') {
|
||||
RIGHT = state
|
||||
} else if (ev.code === 'KeyQ') {
|
||||
ZOOM_OUT = state
|
||||
} else if (ev.code === 'KeyE') {
|
||||
ZOOM_IN = state
|
||||
}
|
||||
}
|
||||
|
||||
let lastMouse: [number, number]|null = null
|
||||
canvas.addEventListener('mousedown', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
if (ev.button === 0) {
|
||||
addEvent([Protocol.INPUT_EV_MOUSE_DOWN, ...lastMouse])
|
||||
}
|
||||
})
|
||||
|
||||
canvas.addEventListener('mouseup', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
if (ev.button === 0) {
|
||||
addEvent([Protocol.INPUT_EV_MOUSE_UP, ...lastMouse])
|
||||
}
|
||||
})
|
||||
|
||||
canvas.addEventListener('mousemove', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
addEvent([Protocol.INPUT_EV_MOUSE_MOVE, ...lastMouse])
|
||||
})
|
||||
|
||||
canvas.addEventListener('wheel', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
if (viewport.canZoom(ev.deltaY < 0 ? 'in' : 'out')) {
|
||||
const evt = ev.deltaY < 0
|
||||
? Protocol.INPUT_EV_ZOOM_IN
|
||||
: Protocol.INPUT_EV_ZOOM_OUT
|
||||
addEvent([evt, ...lastMouse])
|
||||
}
|
||||
})
|
||||
|
||||
window.addEventListener('keydown', (ev: KeyboardEvent) => key(true, ev))
|
||||
window.addEventListener('keyup', (ev: KeyboardEvent) => key(false, ev))
|
||||
|
||||
window.addEventListener('keypress', (ev: KeyboardEvent) => {
|
||||
if (!KEYS_ON) {
|
||||
return
|
||||
}
|
||||
if (ev.code === 'Space') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_PREVIEW])
|
||||
}
|
||||
|
||||
if (MODE === MODE_REPLAY) {
|
||||
if (ev.code === 'KeyI') {
|
||||
addEvent([Protocol.INPUT_EV_REPLAY_SPEED_UP])
|
||||
}
|
||||
|
||||
if (ev.code === 'KeyO') {
|
||||
addEvent([Protocol.INPUT_EV_REPLAY_SPEED_DOWN])
|
||||
}
|
||||
|
||||
if (ev.code === 'KeyP') {
|
||||
addEvent([Protocol.INPUT_EV_REPLAY_TOGGLE_PAUSE])
|
||||
}
|
||||
}
|
||||
if (ev.code === 'KeyF') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_FIXED_PIECES])
|
||||
}
|
||||
if (ev.code === 'KeyG') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_LOOSE_PIECES])
|
||||
}
|
||||
if (ev.code === 'KeyM') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_SOUNDS])
|
||||
}
|
||||
if (ev.code === 'KeyN') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_PLAYER_NAMES])
|
||||
}
|
||||
if (ev.code === 'KeyC') {
|
||||
addEvent([Protocol.INPUT_EV_CENTER_FIT_PUZZLE])
|
||||
}
|
||||
})
|
||||
|
||||
const addEvent = (event: GameEvent) => {
|
||||
events.push(event)
|
||||
}
|
||||
|
||||
const consumeAll = (): GameEvent[] => {
|
||||
if (events.length === 0) {
|
||||
return []
|
||||
}
|
||||
const all = events.slice()
|
||||
events = []
|
||||
return all
|
||||
}
|
||||
|
||||
const createKeyEvents = (): void => {
|
||||
const w = (LEFT ? 1 : 0) - (RIGHT ? 1 : 0)
|
||||
const h = (UP ? 1 : 0) - (DOWN ? 1 : 0)
|
||||
if (w !== 0 || h !== 0) {
|
||||
const amount = (SHIFT ? 24 : 12) * Math.sqrt(viewport.getCurrentZoom())
|
||||
const pos = viewport.viewportDimToWorld({w: w * amount, h: h * amount})
|
||||
addEvent([Protocol.INPUT_EV_MOVE, pos.w, pos.h])
|
||||
if (lastMouse) {
|
||||
lastMouse[0] -= pos.w
|
||||
lastMouse[1] -= pos.h
|
||||
}
|
||||
}
|
||||
|
||||
if (ZOOM_IN && ZOOM_OUT) {
|
||||
// cancel each other out
|
||||
} else if (ZOOM_IN) {
|
||||
if (viewport.canZoom('in')) {
|
||||
const target = lastMouse || canvasCenter()
|
||||
addEvent([Protocol.INPUT_EV_ZOOM_IN, ...target])
|
||||
}
|
||||
} else if (ZOOM_OUT) {
|
||||
if (viewport.canZoom('out')) {
|
||||
const target = lastMouse || canvasCenter()
|
||||
addEvent([Protocol.INPUT_EV_ZOOM_OUT, ...target])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const setHotkeys = (state: boolean) => {
|
||||
KEYS_ON = state
|
||||
}
|
||||
|
||||
return {
|
||||
addEvent,
|
||||
consumeAll,
|
||||
createKeyEvents,
|
||||
setHotkeys,
|
||||
}
|
||||
}
|
||||
|
||||
export default EventAdapter
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
import Geometry, { Rect } from '../common/Geometry'
|
||||
import Graphics from './Graphics'
|
||||
import Util, { logger } from './../common/Util'
|
||||
import { Puzzle, PuzzleInfo, PieceShape, EncodedPiece } from './../common/Types'
|
||||
import { Puzzle, PuzzleInfo, PieceShape, EncodedPiece } from './../common/GameCommon'
|
||||
|
||||
const log = logger('PuzzleGraphics.js')
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
class="imageteaser"
|
||||
:style="style"
|
||||
@click="onClick">
|
||||
<div class="btn edit" v-if="canEdit" @click.stop="onEditClick">✏️</div>
|
||||
<div class="btn edit" @click.stop="onEditClick">✏️</div>
|
||||
</div>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
|
|
@ -24,12 +24,6 @@ export default defineComponent({
|
|||
'backgroundImage': `url("${url}")`,
|
||||
}
|
||||
},
|
||||
canEdit(): boolean {
|
||||
if (!this.$me.id) {
|
||||
return false
|
||||
}
|
||||
return this.$me.id === this.image.uploaderUserId
|
||||
},
|
||||
},
|
||||
emits: {
|
||||
click: null,
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
<template>
|
||||
<div class="overlay transparent" @click="$emit('bgclick')">
|
||||
<table class="overlay-content help" @click.stop="">
|
||||
<tr>
|
||||
<td colspan="2">Info about this puzzle</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Image Title: </td>
|
||||
<td>{{game.puzzle.info.image.title}}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Scoring: </td>
|
||||
<td><span :title="snapMode[1]">{{scoreMode[0]}}</span></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Shapes: </td>
|
||||
<td><span :title="snapMode[1]">{{shapeMode[0]}}</span></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Snapping: </td>
|
||||
<td><span :title="snapMode[1]">{{snapMode[0]}}</span></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, PropType } from 'vue'
|
||||
import { Game, ScoreMode, ShapeMode, SnapMode } from '../../common/Types'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'help-overlay',
|
||||
emits: {
|
||||
bgclick: null,
|
||||
},
|
||||
props: {
|
||||
game: {
|
||||
type: Object as PropType<Game>,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
computed: {
|
||||
scoreMode () {
|
||||
switch (this.game.scoreMode) {
|
||||
case ScoreMode.ANY: return ['Any', 'Score when pieces are connected to each other or on final location']
|
||||
case ScoreMode.FINAL:
|
||||
default: return ['Final', 'Score when pieces are put to their final location']
|
||||
}
|
||||
},
|
||||
shapeMode () {
|
||||
switch (this.game.shapeMode) {
|
||||
case ShapeMode.FLAT: return ['Flat', 'All pieces flat on all sides']
|
||||
case ShapeMode.ANY: return ['Any', 'Flat pieces can occur anywhere']
|
||||
case ShapeMode.NORMAL:
|
||||
default:
|
||||
return ['Normal', '']
|
||||
}
|
||||
},
|
||||
snapMode () {
|
||||
switch (this.game.snapMode) {
|
||||
case SnapMode.REAL: return ['Real', 'Pieces snap only to corners, already snapped pieces and to each other']
|
||||
case SnapMode.NORMAL:
|
||||
default:
|
||||
return ['Normal', 'Pieces snap to final destination and to each other']
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
|
@ -35,20 +35,20 @@
|
|||
Normal</label>
|
||||
<br />
|
||||
<label><input type="radio" v-model="shapeMode" value="1" />
|
||||
Any (Flat pieces can occur anywhere)</label>
|
||||
Any (flat pieces can occur anywhere)</label>
|
||||
<br />
|
||||
<label><input type="radio" v-model="shapeMode" value="2" />
|
||||
Flat (All pieces flat on all sides)</label>
|
||||
Flat (all pieces flat on all sides)</label>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><label>Snapping: </label></td>
|
||||
<td>
|
||||
<label><input type="radio" v-model="snapMode" value="0" />
|
||||
Normal (Pieces snap to final destination and to each other)</label>
|
||||
Normal (pieces snap to final destination and to each other)</label>
|
||||
<br />
|
||||
<label><input type="radio" v-model="snapMode" value="1" />
|
||||
Real (Pieces snap only to corners, already snapped pieces and to each other)</label>
|
||||
Real (pieces snap only to corners, already snapped pieces and to each other)</label>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@
|
|||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
import xhr from '../xhr'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'upload',
|
||||
|
|
@ -22,7 +21,8 @@ export default defineComponent({
|
|||
if (!file) return;
|
||||
const formData = new FormData();
|
||||
formData.append('file', file, file.name);
|
||||
const res = await xhr.post('/upload', {
|
||||
const res = await fetch('/upload', {
|
||||
method: 'post',
|
||||
body: formData,
|
||||
})
|
||||
const j = await res.json()
|
||||
|
|
|
|||
|
|
@ -22,9 +22,9 @@ import {
|
|||
EncodedGame,
|
||||
ReplayData,
|
||||
Timestamp,
|
||||
GameEvent,
|
||||
ServerEvent,
|
||||
} from '../common/Types'
|
||||
import EventAdapter from './EventAdapter'
|
||||
declare global {
|
||||
interface Window {
|
||||
DEBUG?: boolean
|
||||
|
|
@ -96,6 +96,180 @@ function addCanvasToDom(TARGET_EL: HTMLElement, canvas: HTMLCanvasElement) {
|
|||
return canvas
|
||||
}
|
||||
|
||||
function EventAdapter (
|
||||
canvas: HTMLCanvasElement,
|
||||
window: any,
|
||||
viewport: any,
|
||||
MODE: string
|
||||
) {
|
||||
let events: Array<GameEvent> = []
|
||||
|
||||
let KEYS_ON = true
|
||||
|
||||
let LEFT = false
|
||||
let RIGHT = false
|
||||
let UP = false
|
||||
let DOWN = false
|
||||
let ZOOM_IN = false
|
||||
let ZOOM_OUT = false
|
||||
let SHIFT = false
|
||||
|
||||
const toWorldPoint = (x: number, y: number): [number, number] => {
|
||||
const pos = viewport.viewportToWorld({x, y})
|
||||
return [pos.x, pos.y]
|
||||
}
|
||||
|
||||
const mousePos = (ev: MouseEvent) => toWorldPoint(ev.offsetX, ev.offsetY)
|
||||
const canvasCenter = () => toWorldPoint(canvas.width / 2, canvas.height / 2)
|
||||
|
||||
const key = (state: boolean, ev: KeyboardEvent) => {
|
||||
if (!KEYS_ON) {
|
||||
return
|
||||
}
|
||||
|
||||
if (ev.code === 'ShiftLeft' || ev.code === 'ShiftRight') {
|
||||
SHIFT = state
|
||||
} else if (ev.code === 'ArrowUp' || ev.code === 'KeyW') {
|
||||
UP = state
|
||||
} else if (ev.code === 'ArrowDown' || ev.code === 'KeyS') {
|
||||
DOWN = state
|
||||
} else if (ev.code === 'ArrowLeft' || ev.code === 'KeyA') {
|
||||
LEFT = state
|
||||
} else if (ev.code === 'ArrowRight' || ev.code === 'KeyD') {
|
||||
RIGHT = state
|
||||
} else if (ev.code === 'KeyQ') {
|
||||
ZOOM_OUT = state
|
||||
} else if (ev.code === 'KeyE') {
|
||||
ZOOM_IN = state
|
||||
}
|
||||
}
|
||||
|
||||
let lastMouse: [number, number]|null = null
|
||||
canvas.addEventListener('mousedown', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
if (ev.button === 0) {
|
||||
addEvent([Protocol.INPUT_EV_MOUSE_DOWN, ...lastMouse])
|
||||
}
|
||||
})
|
||||
|
||||
canvas.addEventListener('mouseup', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
if (ev.button === 0) {
|
||||
addEvent([Protocol.INPUT_EV_MOUSE_UP, ...lastMouse])
|
||||
}
|
||||
})
|
||||
|
||||
canvas.addEventListener('mousemove', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
addEvent([Protocol.INPUT_EV_MOUSE_MOVE, ...lastMouse])
|
||||
})
|
||||
|
||||
canvas.addEventListener('wheel', (ev) => {
|
||||
lastMouse = mousePos(ev)
|
||||
if (viewport.canZoom(ev.deltaY < 0 ? 'in' : 'out')) {
|
||||
const evt = ev.deltaY < 0
|
||||
? Protocol.INPUT_EV_ZOOM_IN
|
||||
: Protocol.INPUT_EV_ZOOM_OUT
|
||||
addEvent([evt, ...lastMouse])
|
||||
}
|
||||
})
|
||||
|
||||
window.addEventListener('keydown', (ev: KeyboardEvent) => key(true, ev))
|
||||
window.addEventListener('keyup', (ev: KeyboardEvent) => key(false, ev))
|
||||
|
||||
window.addEventListener('keypress', (ev: KeyboardEvent) => {
|
||||
if (!KEYS_ON) {
|
||||
return
|
||||
}
|
||||
if (ev.code === 'Space') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_PREVIEW])
|
||||
}
|
||||
|
||||
if (MODE === MODE_REPLAY) {
|
||||
if (ev.code === 'KeyI') {
|
||||
addEvent([Protocol.INPUT_EV_REPLAY_SPEED_UP])
|
||||
}
|
||||
|
||||
if (ev.code === 'KeyO') {
|
||||
addEvent([Protocol.INPUT_EV_REPLAY_SPEED_DOWN])
|
||||
}
|
||||
|
||||
if (ev.code === 'KeyP') {
|
||||
addEvent([Protocol.INPUT_EV_REPLAY_TOGGLE_PAUSE])
|
||||
}
|
||||
}
|
||||
if (ev.code === 'KeyF') {
|
||||
PIECE_VIEW_FIXED = !PIECE_VIEW_FIXED
|
||||
RERENDER = true
|
||||
}
|
||||
if (ev.code === 'KeyG') {
|
||||
PIECE_VIEW_LOOSE = !PIECE_VIEW_LOOSE
|
||||
RERENDER = true
|
||||
}
|
||||
if (ev.code === 'KeyM') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_SOUNDS])
|
||||
}
|
||||
if (ev.code === 'KeyN') {
|
||||
addEvent([Protocol.INPUT_EV_TOGGLE_PLAYER_NAMES])
|
||||
}
|
||||
if (ev.code === 'KeyC') {
|
||||
addEvent([Protocol.INPUT_EV_CENTER_FIT_PUZZLE])
|
||||
}
|
||||
})
|
||||
|
||||
const addEvent = (event: GameEvent) => {
|
||||
events.push(event)
|
||||
}
|
||||
|
||||
const consumeAll = (): GameEvent[] => {
|
||||
if (events.length === 0) {
|
||||
return []
|
||||
}
|
||||
const all = events.slice()
|
||||
events = []
|
||||
return all
|
||||
}
|
||||
|
||||
const createKeyEvents = (): void => {
|
||||
const w = (LEFT ? 1 : 0) - (RIGHT ? 1 : 0)
|
||||
const h = (UP ? 1 : 0) - (DOWN ? 1 : 0)
|
||||
if (w !== 0 || h !== 0) {
|
||||
const amount = (SHIFT ? 24 : 12) * Math.sqrt(viewport.getCurrentZoom())
|
||||
const pos = viewport.viewportDimToWorld({w: w * amount, h: h * amount})
|
||||
addEvent([Protocol.INPUT_EV_MOVE, pos.w, pos.h])
|
||||
if (lastMouse) {
|
||||
lastMouse[0] -= pos.w
|
||||
lastMouse[1] -= pos.h
|
||||
}
|
||||
}
|
||||
|
||||
if (ZOOM_IN && ZOOM_OUT) {
|
||||
// cancel each other out
|
||||
} else if (ZOOM_IN) {
|
||||
if (viewport.canZoom('in')) {
|
||||
const target = lastMouse || canvasCenter()
|
||||
addEvent([Protocol.INPUT_EV_ZOOM_IN, ...target])
|
||||
}
|
||||
} else if (ZOOM_OUT) {
|
||||
if (viewport.canZoom('out')) {
|
||||
const target = lastMouse || canvasCenter()
|
||||
addEvent([Protocol.INPUT_EV_ZOOM_OUT, ...target])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const setHotkeys = (state: boolean) => {
|
||||
KEYS_ON = state
|
||||
}
|
||||
|
||||
return {
|
||||
addEvent,
|
||||
consumeAll,
|
||||
createKeyEvents,
|
||||
setHotkeys,
|
||||
}
|
||||
}
|
||||
|
||||
export async function main(
|
||||
gameId: string,
|
||||
clientId: string,
|
||||
|
|
@ -572,12 +746,6 @@ export async function main(
|
|||
HUD.togglePlayerNames()
|
||||
} else if (type === Protocol.INPUT_EV_CENTER_FIT_PUZZLE) {
|
||||
centerPuzzle()
|
||||
} else if (type === Protocol.INPUT_EV_TOGGLE_FIXED_PIECES) {
|
||||
PIECE_VIEW_FIXED = !PIECE_VIEW_FIXED
|
||||
RERENDER = true
|
||||
} else if (type === Protocol.INPUT_EV_TOGGLE_LOOSE_PIECES) {
|
||||
PIECE_VIEW_LOOSE = !PIECE_VIEW_LOOSE
|
||||
RERENDER = true
|
||||
}
|
||||
|
||||
// LOCAL + SERVER CHANGES
|
||||
|
|
@ -650,12 +818,6 @@ export async function main(
|
|||
HUD.togglePlayerNames()
|
||||
} else if (type === Protocol.INPUT_EV_CENTER_FIT_PUZZLE) {
|
||||
centerPuzzle()
|
||||
} else if (type === Protocol.INPUT_EV_TOGGLE_FIXED_PIECES) {
|
||||
PIECE_VIEW_FIXED = !PIECE_VIEW_FIXED
|
||||
RERENDER = true
|
||||
} else if (type === Protocol.INPUT_EV_TOGGLE_LOOSE_PIECES) {
|
||||
PIECE_VIEW_LOOSE = !PIECE_VIEW_LOOSE
|
||||
RERENDER = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -807,7 +969,6 @@ export async function main(
|
|||
soundsVolume: playerSoundVolume(),
|
||||
showPlayerNames: showPlayerNames(),
|
||||
},
|
||||
game: Game.get(gameId),
|
||||
disconnect: Communication.disconnect,
|
||||
connect: connect,
|
||||
unload: unload,
|
||||
|
|
|
|||
|
|
@ -7,36 +7,19 @@ import NewGame from './views/NewGame.vue'
|
|||
import Game from './views/Game.vue'
|
||||
import Replay from './views/Replay.vue'
|
||||
import Util from './../common/Util'
|
||||
import settings from './settings'
|
||||
import xhr from './xhr'
|
||||
|
||||
(async () => {
|
||||
function initClientSecret() {
|
||||
let SECRET = settings.getStr('SECRET', '')
|
||||
if (!SECRET) {
|
||||
SECRET = Util.uniqId()
|
||||
settings.setStr('SECRET', SECRET)
|
||||
}
|
||||
return SECRET
|
||||
}
|
||||
function initClientId() {
|
||||
let ID = settings.getStr('ID', '')
|
||||
const res = await fetch(`/api/conf`)
|
||||
const conf = await res.json()
|
||||
|
||||
function initme() {
|
||||
let ID = localStorage.getItem('ID')
|
||||
if (!ID) {
|
||||
ID = Util.uniqId()
|
||||
settings.setStr('ID', ID)
|
||||
localStorage.setItem('ID', ID)
|
||||
}
|
||||
return ID
|
||||
}
|
||||
const clientId = initClientId()
|
||||
const clientSecret = initClientSecret()
|
||||
xhr.setClientId(clientId)
|
||||
xhr.setClientSecret(clientSecret)
|
||||
|
||||
const meRes = await xhr.get(`/api/me`, {})
|
||||
const me = await meRes.json()
|
||||
|
||||
const confRes = await xhr.get(`/api/conf`, {})
|
||||
const conf = await confRes.json()
|
||||
|
||||
const router = VueRouter.createRouter({
|
||||
history: VueRouter.createWebHashHistory(),
|
||||
|
|
@ -56,9 +39,8 @@ import xhr from './xhr'
|
|||
})
|
||||
|
||||
const app = Vue.createApp(App)
|
||||
app.config.globalProperties.$me = me
|
||||
app.config.globalProperties.$config = conf
|
||||
app.config.globalProperties.$clientId = clientId
|
||||
app.config.globalProperties.$clientId = initme()
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
})()
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
<div id="game">
|
||||
<settings-overlay v-show="overlay === 'settings'" @bgclick="toggle('settings', true)" v-model="g.player" />
|
||||
<preview-overlay v-show="overlay === 'preview'" @bgclick="toggle('preview', false)" :img="g.previewImageUrl" />
|
||||
<info-overlay v-if="g.game" v-show="overlay === 'info'" @bgclick="toggle('info', true)" :game="g.game" />
|
||||
<help-overlay v-show="overlay === 'help'" @bgclick="toggle('help', true)" />
|
||||
|
||||
<div class="overlay" v-if="cuttingPuzzle">
|
||||
|
|
@ -28,8 +27,7 @@
|
|||
<router-link class="opener" :to="{name: 'index'}" target="_blank">🧩 Puzzles</router-link>
|
||||
<div class="opener" @click="toggle('preview', false)">🖼️ Preview</div>
|
||||
<div class="opener" @click="toggle('settings', true)">🛠️ Settings</div>
|
||||
<div class="opener" @click="toggle('info', true)">ℹ️ Info</div>
|
||||
<div class="opener" @click="toggle('help', true)">⌨️ Hotkeys</div>
|
||||
<div class="opener" @click="toggle('help', true)">ℹ️ Hotkeys</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -43,12 +41,11 @@ import Scores from './../components/Scores.vue'
|
|||
import PuzzleStatus from './../components/PuzzleStatus.vue'
|
||||
import SettingsOverlay from './../components/SettingsOverlay.vue'
|
||||
import PreviewOverlay from './../components/PreviewOverlay.vue'
|
||||
import InfoOverlay from './../components/InfoOverlay.vue'
|
||||
import ConnectionOverlay from './../components/ConnectionOverlay.vue'
|
||||
import HelpOverlay from './../components/HelpOverlay.vue'
|
||||
|
||||
import { main, MODE_PLAY } from './../game'
|
||||
import { Game, Player } from '../../common/Types'
|
||||
import { Player } from '../../common/Types'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'game',
|
||||
|
|
@ -57,7 +54,6 @@ export default defineComponent({
|
|||
Scores,
|
||||
SettingsOverlay,
|
||||
PreviewOverlay,
|
||||
InfoOverlay,
|
||||
ConnectionOverlay,
|
||||
HelpOverlay,
|
||||
},
|
||||
|
|
@ -85,7 +81,6 @@ export default defineComponent({
|
|||
soundsVolume: 100,
|
||||
showPlayerNames: true,
|
||||
},
|
||||
game: null as Game|null,
|
||||
previewImageUrl: '',
|
||||
setHotkeys: (v: boolean) => {},
|
||||
onBgChange: (v: string) => {},
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@
|
|||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
import xhr from '../xhr'
|
||||
|
||||
import GameTeaser from './../components/GameTeaser.vue'
|
||||
|
||||
|
|
@ -28,7 +27,7 @@ export default defineComponent({
|
|||
}
|
||||
},
|
||||
async created() {
|
||||
const res = await xhr.get('/api/index-data', {})
|
||||
const res = await fetch('/api/index-data')
|
||||
const json = await res.json()
|
||||
this.gamesRunning = json.gamesRunning
|
||||
this.gamesFinished = json.gamesFinished
|
||||
|
|
|
|||
|
|
@ -133,7 +133,7 @@ export default defineComponent({
|
|||
this.filtersChanged()
|
||||
},
|
||||
async loadImages () {
|
||||
const res = await xhr.get(`/api/newgame-data${Util.asQueryArgs(this.filters)}`, {})
|
||||
const res = await fetch(`/api/newgame-data${Util.asQueryArgs(this.filters)}`)
|
||||
const json = await res.json()
|
||||
this.images = json.images
|
||||
this.tags = json.tags
|
||||
|
|
@ -165,7 +165,8 @@ export default defineComponent({
|
|||
return await res.json()
|
||||
},
|
||||
async saveImage (data: any) {
|
||||
const res = await xhr.post('/api/save-image', {
|
||||
const res = await fetch('/api/save-image', {
|
||||
method: 'post',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
|
|
@ -179,13 +180,9 @@ export default defineComponent({
|
|||
return await res.json()
|
||||
},
|
||||
async onSaveImageClick(data: any) {
|
||||
const res = await this.saveImage(data)
|
||||
if (res.ok) {
|
||||
await this.saveImage(data)
|
||||
this.dialog = ''
|
||||
await this.loadImages()
|
||||
} else {
|
||||
alert(res.error)
|
||||
}
|
||||
},
|
||||
async postToGalleryClick(data: any) {
|
||||
this.uploading = 'postToGallery'
|
||||
|
|
@ -203,7 +200,8 @@ export default defineComponent({
|
|||
this.dialog = 'new-game'
|
||||
},
|
||||
async onNewGame(gameSettings: GameSettings) {
|
||||
const res = await xhr.post('/api/newgame', {
|
||||
const res = await fetch('/api/newgame', {
|
||||
method: 'post',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
<div id="replay">
|
||||
<settings-overlay v-show="overlay === 'settings'" @bgclick="toggle('settings', true)" v-model="g.player" />
|
||||
<preview-overlay v-show="overlay === 'preview'" @bgclick="toggle('preview', false)" :img="g.previewImageUrl" />
|
||||
<info-overlay v-if="g.game" v-show="overlay === 'info'" @bgclick="toggle('info', true)" :game="g.game" />
|
||||
<help-overlay v-show="overlay === 'help'" @bgclick="toggle('help', true)" />
|
||||
|
||||
<div class="overlay" v-if="cuttingPuzzle">
|
||||
|
|
@ -30,8 +29,7 @@
|
|||
<router-link class="opener" :to="{name: 'index'}" target="_blank">🧩 Puzzles</router-link>
|
||||
<div class="opener" @click="toggle('preview', false)">🖼️ Preview</div>
|
||||
<div class="opener" @click="toggle('settings', true)">🛠️ Settings</div>
|
||||
<div class="opener" @click="toggle('info', true)">ℹ️ Info</div>
|
||||
<div class="opener" @click="toggle('help', true)">⌨️ Hotkeys</div>
|
||||
<div class="opener" @click="toggle('help', true)">ℹ️ Hotkeys</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -45,11 +43,10 @@ import Scores from './../components/Scores.vue'
|
|||
import PuzzleStatus from './../components/PuzzleStatus.vue'
|
||||
import SettingsOverlay from './../components/SettingsOverlay.vue'
|
||||
import PreviewOverlay from './../components/PreviewOverlay.vue'
|
||||
import InfoOverlay from './../components/InfoOverlay.vue'
|
||||
import HelpOverlay from './../components/HelpOverlay.vue'
|
||||
|
||||
import { main, MODE_REPLAY } from './../game'
|
||||
import { Game, Player } from '../../common/Types'
|
||||
import { Player } from '../../common/Types'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'replay',
|
||||
|
|
@ -58,7 +55,6 @@ export default defineComponent({
|
|||
Scores,
|
||||
SettingsOverlay,
|
||||
PreviewOverlay,
|
||||
InfoOverlay,
|
||||
HelpOverlay,
|
||||
},
|
||||
data() {
|
||||
|
|
@ -85,7 +81,6 @@ export default defineComponent({
|
|||
soundsVolume: 100,
|
||||
showPlayerNames: true,
|
||||
},
|
||||
game: null as Game|null,
|
||||
previewImageUrl: '',
|
||||
setHotkeys: (v: boolean) => {},
|
||||
onBgChange: (v: string) => {},
|
||||
|
|
|
|||
|
|
@ -10,8 +10,6 @@ export interface Options {
|
|||
onUploadProgress?: (ev: ProgressEvent<XMLHttpRequestEventTarget>) => any,
|
||||
}
|
||||
|
||||
let xhrClientId: string = ''
|
||||
let xhrClientSecret: string = ''
|
||||
const request = async (
|
||||
method: string,
|
||||
url: string,
|
||||
|
|
@ -24,10 +22,6 @@ const request = async (
|
|||
for (const k in options.headers || {}) {
|
||||
xhr.setRequestHeader(k, options.headers[k])
|
||||
}
|
||||
|
||||
xhr.setRequestHeader('Client-Id', xhrClientId)
|
||||
xhr.setRequestHeader('Client-Secret', xhrClientSecret)
|
||||
|
||||
xhr.addEventListener('load', function (ev: ProgressEvent<XMLHttpRequestEventTarget>
|
||||
) {
|
||||
resolve({
|
||||
|
|
@ -47,7 +41,7 @@ const request = async (
|
|||
}
|
||||
})
|
||||
}
|
||||
xhr.send(options.body || null)
|
||||
xhr.send(options.body)
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -59,10 +53,4 @@ export default {
|
|||
post: (url: string, options: any): Promise<Response> => {
|
||||
return request('post', url, options)
|
||||
},
|
||||
setClientId: (clientId: string): void => {
|
||||
xhrClientId = clientId
|
||||
},
|
||||
setClientSecret: (clientSecret: string): void => {
|
||||
xhrClientSecret = clientSecret
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import GameCommon from './../common/GameCommon'
|
||||
import { Change, Game, Input, ScoreMode, ShapeMode, SnapMode,ImageInfo, Timestamp, GameSettings } from './../common/Types'
|
||||
import { Change, Game, Input, ScoreMode, ShapeMode, SnapMode, Timestamp } from './../common/Types'
|
||||
import Util, { logger } from './../common/Util'
|
||||
import { Rng } from './../common/Rng'
|
||||
import GameLog from './GameLog'
|
||||
import { createPuzzle } from './Puzzle'
|
||||
import { createPuzzle, PuzzleCreationImageInfo } from './Puzzle'
|
||||
import Protocol from './../common/Protocol'
|
||||
import GameStorage from './GameStorage'
|
||||
|
||||
|
|
@ -12,18 +12,16 @@ const log = logger('Game.ts')
|
|||
async function createGameObject(
|
||||
gameId: string,
|
||||
targetTiles: number,
|
||||
image: ImageInfo,
|
||||
image: PuzzleCreationImageInfo,
|
||||
ts: Timestamp,
|
||||
scoreMode: ScoreMode,
|
||||
shapeMode: ShapeMode,
|
||||
snapMode: SnapMode,
|
||||
creatorUserId: number|null
|
||||
snapMode: SnapMode
|
||||
): Promise<Game> {
|
||||
const seed = Util.hash(gameId + ' ' + ts)
|
||||
const rng = new Rng(seed)
|
||||
return {
|
||||
id: gameId,
|
||||
creatorUserId,
|
||||
rng: { type: 'Rng', obj: rng },
|
||||
puzzle: await createPuzzle(rng, targetTiles, image, ts, shapeMode),
|
||||
players: [],
|
||||
|
|
@ -34,25 +32,23 @@ async function createGameObject(
|
|||
}
|
||||
}
|
||||
|
||||
async function createNewGame(
|
||||
gameSettings: GameSettings,
|
||||
async function createGame(
|
||||
gameId: string,
|
||||
targetTiles: number,
|
||||
image: PuzzleCreationImageInfo,
|
||||
ts: Timestamp,
|
||||
creatorUserId: number
|
||||
): Promise<string> {
|
||||
let gameId;
|
||||
do {
|
||||
gameId = Util.uniqId()
|
||||
} while (GameCommon.exists(gameId))
|
||||
|
||||
scoreMode: ScoreMode,
|
||||
shapeMode: ShapeMode,
|
||||
snapMode: SnapMode
|
||||
): Promise<void> {
|
||||
const gameObject = await createGameObject(
|
||||
gameId,
|
||||
gameSettings.tiles,
|
||||
gameSettings.image,
|
||||
targetTiles,
|
||||
image,
|
||||
ts,
|
||||
gameSettings.scoreMode,
|
||||
gameSettings.shapeMode,
|
||||
gameSettings.snapMode,
|
||||
creatorUserId
|
||||
scoreMode,
|
||||
shapeMode,
|
||||
snapMode
|
||||
)
|
||||
|
||||
GameLog.create(gameId, ts)
|
||||
|
|
@ -60,19 +56,16 @@ async function createNewGame(
|
|||
gameId,
|
||||
Protocol.LOG_HEADER,
|
||||
1,
|
||||
gameSettings.tiles,
|
||||
gameSettings.image,
|
||||
targetTiles,
|
||||
image,
|
||||
ts,
|
||||
gameSettings.scoreMode,
|
||||
gameSettings.shapeMode,
|
||||
gameSettings.snapMode,
|
||||
gameObject.creatorUserId
|
||||
scoreMode,
|
||||
shapeMode,
|
||||
snapMode
|
||||
)
|
||||
|
||||
GameCommon.setGame(gameObject.id, gameObject)
|
||||
GameStorage.setDirty(gameId)
|
||||
|
||||
return gameId
|
||||
}
|
||||
|
||||
function addPlayer(gameId: string, playerId: string, ts: Timestamp): void {
|
||||
|
|
@ -107,7 +100,7 @@ function handleInput(
|
|||
|
||||
export default {
|
||||
createGameObject,
|
||||
createNewGame,
|
||||
createGame,
|
||||
addPlayer,
|
||||
handleInput,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,7 +90,6 @@ const get = (
|
|||
log[0][5] = DefaultScoreMode(log[0][5])
|
||||
log[0][6] = DefaultShapeMode(log[0][6])
|
||||
log[0][7] = DefaultSnapMode(log[0][7])
|
||||
log[0][8] = log[0][8] || null // creatorUserId
|
||||
}
|
||||
return log
|
||||
}
|
||||
|
|
@ -101,6 +100,4 @@ export default {
|
|||
exists,
|
||||
log: _log,
|
||||
get,
|
||||
filename,
|
||||
idxname,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import Util, { logger } from './../common/Util'
|
|||
import { Rng } from './../common/Rng'
|
||||
import { DATA_DIR } from './Dirs'
|
||||
import Time from './../common/Time'
|
||||
import Db from './Db'
|
||||
|
||||
const log = logger('GameStorage.js')
|
||||
|
||||
|
|
@ -16,73 +15,8 @@ function setDirty(gameId: string): void {
|
|||
function setClean(gameId: string): void {
|
||||
delete dirtyGames[gameId]
|
||||
}
|
||||
function loadGamesFromDb(db: Db): void {
|
||||
const gameRows = db.getMany('games')
|
||||
for (const gameRow of gameRows) {
|
||||
loadGameFromDb(db, gameRow.id)
|
||||
}
|
||||
}
|
||||
|
||||
function loadGameFromDb(db: Db, gameId: string): void {
|
||||
const gameRow = db.get('games', {id: gameId})
|
||||
|
||||
let game
|
||||
try {
|
||||
game = JSON.parse(gameRow.data)
|
||||
} catch {
|
||||
log.log(`[ERR] unable to load game from db ${gameId}`);
|
||||
}
|
||||
if (typeof game.puzzle.data.started === 'undefined') {
|
||||
game.puzzle.data.started = gameRow.created
|
||||
}
|
||||
if (typeof game.puzzle.data.finished === 'undefined') {
|
||||
game.puzzle.data.finished = gameRow.finished
|
||||
}
|
||||
if (!Array.isArray(game.players)) {
|
||||
game.players = Object.values(game.players)
|
||||
}
|
||||
|
||||
const gameObject: Game = storeDataToGame(game, game.creator_user_id)
|
||||
GameCommon.setGame(gameObject.id, gameObject)
|
||||
}
|
||||
|
||||
function persistGamesToDb(db: Db): void {
|
||||
for (const gameId of Object.keys(dirtyGames)) {
|
||||
persistGameToDb(db, gameId)
|
||||
}
|
||||
}
|
||||
|
||||
function persistGameToDb(db: Db, gameId: string): void {
|
||||
const game: Game|null = GameCommon.get(gameId)
|
||||
if (!game) {
|
||||
log.error(`[ERROR] unable to persist non existing game ${gameId}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (game.id in dirtyGames) {
|
||||
setClean(game.id)
|
||||
}
|
||||
|
||||
db.upsert('games', {
|
||||
id: game.id,
|
||||
|
||||
creator_user_id: game.creatorUserId,
|
||||
image_id: game.puzzle.info.image?.id,
|
||||
|
||||
created: game.puzzle.data.started,
|
||||
finished: game.puzzle.data.finished,
|
||||
|
||||
data: gameToStoreData(game)
|
||||
}, {
|
||||
id: game.id,
|
||||
})
|
||||
log.info(`[INFO] persisted game ${game.id}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
function loadGamesFromDisk(): void {
|
||||
function loadGames(): void {
|
||||
const files = fs.readdirSync(DATA_DIR)
|
||||
for (const f of files) {
|
||||
const m = f.match(/^([a-z0-9]+)\.json$/)
|
||||
|
|
@ -90,14 +24,11 @@ function loadGamesFromDisk(): void {
|
|||
continue
|
||||
}
|
||||
const gameId = m[1]
|
||||
loadGameFromDisk(gameId)
|
||||
loadGame(gameId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
function loadGameFromDisk(gameId: string): void {
|
||||
function loadGame(gameId: string): void {
|
||||
const file = `${DATA_DIR}/${gameId}.json`
|
||||
const contents = fs.readFileSync(file, 'utf-8')
|
||||
let game
|
||||
|
|
@ -118,29 +49,39 @@ function loadGameFromDisk(gameId: string): void {
|
|||
if (!Array.isArray(game.players)) {
|
||||
game.players = Object.values(game.players)
|
||||
}
|
||||
const gameObject: Game = storeDataToGame(game, null)
|
||||
const gameObject: Game = {
|
||||
id: game.id,
|
||||
rng: {
|
||||
type: game.rng ? game.rng.type : '_fake_',
|
||||
obj: game.rng ? Rng.unserialize(game.rng.obj) : new Rng(0),
|
||||
},
|
||||
puzzle: game.puzzle,
|
||||
players: game.players,
|
||||
evtInfos: {},
|
||||
scoreMode: DefaultScoreMode(game.scoreMode),
|
||||
shapeMode: DefaultShapeMode(game.shapeMode),
|
||||
snapMode: DefaultSnapMode(game.snapMode),
|
||||
}
|
||||
GameCommon.setGame(gameObject.id, gameObject)
|
||||
}
|
||||
|
||||
function storeDataToGame(storeData: any, creatorUserId: number|null): Game {
|
||||
return {
|
||||
id: storeData.id,
|
||||
creatorUserId,
|
||||
rng: {
|
||||
type: storeData.rng ? storeData.rng.type : '_fake_',
|
||||
obj: storeData.rng ? Rng.unserialize(storeData.rng.obj) : new Rng(0),
|
||||
},
|
||||
puzzle: storeData.puzzle,
|
||||
players: storeData.players,
|
||||
evtInfos: {},
|
||||
scoreMode: DefaultScoreMode(storeData.scoreMode),
|
||||
shapeMode: DefaultShapeMode(storeData.shapeMode),
|
||||
snapMode: DefaultSnapMode(storeData.snapMode),
|
||||
function persistGames(): void {
|
||||
for (const gameId of Object.keys(dirtyGames)) {
|
||||
persistGame(gameId)
|
||||
}
|
||||
}
|
||||
|
||||
function gameToStoreData(game: Game): string {
|
||||
return JSON.stringify({
|
||||
function persistGame(gameId: string): void {
|
||||
const game = GameCommon.get(gameId)
|
||||
if (!game) {
|
||||
log.error(`[ERROR] unable to persist non existing game ${gameId}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (game.id in dirtyGames) {
|
||||
setClean(game.id)
|
||||
}
|
||||
fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, JSON.stringify({
|
||||
id: game.id,
|
||||
rng: {
|
||||
type: game.rng.type,
|
||||
|
|
@ -151,18 +92,14 @@ function gameToStoreData(game: Game): string {
|
|||
scoreMode: game.scoreMode,
|
||||
shapeMode: game.shapeMode,
|
||||
snapMode: game.snapMode,
|
||||
});
|
||||
}))
|
||||
log.info(`[INFO] persisted game ${game.id}`)
|
||||
}
|
||||
|
||||
export default {
|
||||
// disk functions are deprecated
|
||||
loadGamesFromDisk,
|
||||
loadGameFromDisk,
|
||||
|
||||
loadGamesFromDb,
|
||||
loadGameFromDb,
|
||||
persistGamesToDb,
|
||||
persistGameToDb,
|
||||
|
||||
loadGames,
|
||||
loadGame,
|
||||
persistGames,
|
||||
persistGame,
|
||||
setDirty,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,11 +6,31 @@ import sharp from 'sharp'
|
|||
import {UPLOAD_DIR, UPLOAD_URL} from './Dirs'
|
||||
import Db, { OrderBy, WhereRaw } from './Db'
|
||||
import { Dim } from '../common/Geometry'
|
||||
import Util, { logger } from '../common/Util'
|
||||
import { Tag, ImageInfo } from '../common/Types'
|
||||
import { logger } from '../common/Util'
|
||||
import { Timestamp } from '../common/Types'
|
||||
|
||||
const log = logger('Images.ts')
|
||||
|
||||
interface Tag
|
||||
{
|
||||
id: number
|
||||
slug: string
|
||||
title: string
|
||||
}
|
||||
|
||||
interface ImageInfo
|
||||
{
|
||||
id: number
|
||||
filename: string
|
||||
file: string
|
||||
url: string
|
||||
title: string
|
||||
tags: Tag[]
|
||||
created: Timestamp
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
const resizeImage = async (filename: string): Promise<void> => {
|
||||
if (!filename.toLowerCase().match(/\.(jpe?g|webp|png)$/)) {
|
||||
return
|
||||
|
|
@ -85,8 +105,8 @@ const imageFromDb = (db: Db, imageId: number): ImageInfo => {
|
|||
const i = db.get('images', { id: imageId })
|
||||
return {
|
||||
id: i.id,
|
||||
uploaderUserId: i.uploader_user_id,
|
||||
filename: i.filename,
|
||||
file: `${UPLOAD_DIR}/${i.filename}`,
|
||||
url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`,
|
||||
title: i.title,
|
||||
tags: getTags(db, i.id),
|
||||
|
|
@ -131,8 +151,8 @@ inner join images i on i.id = ixc.image_id ${where.sql};
|
|||
|
||||
return images.map(i => ({
|
||||
id: i.id as number,
|
||||
uploaderUserId: i.uploader_user_id,
|
||||
filename: i.filename,
|
||||
file: `${UPLOAD_DIR}/${i.filename}`,
|
||||
url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`,
|
||||
title: i.title,
|
||||
tags: getTags(db, i.id),
|
||||
|
|
@ -153,8 +173,8 @@ const allImagesFromDisk = (
|
|||
.filter(f => f.toLowerCase().match(/\.(jpe?g|webp|png)$/))
|
||||
.map(f => ({
|
||||
id: 0,
|
||||
uploaderUserId: null,
|
||||
filename: f,
|
||||
file: `${UPLOAD_DIR}/${f}`,
|
||||
url: `${UPLOAD_URL}/${encodeURIComponent(f)}`,
|
||||
title: f.replace(/\.[a-z]+$/, ''),
|
||||
tags: [] as Tag[],
|
||||
|
|
@ -166,13 +186,13 @@ const allImagesFromDisk = (
|
|||
switch (sort) {
|
||||
case 'alpha_asc':
|
||||
images = images.sort((a, b) => {
|
||||
return a.filename > b.filename ? 1 : -1
|
||||
return a.file > b.file ? 1 : -1
|
||||
})
|
||||
break;
|
||||
|
||||
case 'alpha_desc':
|
||||
images = images.sort((a, b) => {
|
||||
return a.filename < b.filename ? 1 : -1
|
||||
return a.file < b.file ? 1 : -1
|
||||
})
|
||||
break;
|
||||
|
||||
|
|
@ -209,20 +229,6 @@ async function getDimensions(imagePath: string): Promise<Dim> {
|
|||
}
|
||||
}
|
||||
|
||||
const setTags = (db: Db, imageId: number, tags: string[]): void => {
|
||||
db.delete('image_x_category', { image_id: imageId })
|
||||
tags.forEach((tag: string) => {
|
||||
const slug = Util.slug(tag)
|
||||
const id = db.upsert('categories', { slug, title: tag }, { slug }, 'id')
|
||||
if (id) {
|
||||
db.insert('image_x_category', {
|
||||
image_id: imageId,
|
||||
category_id: id,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export default {
|
||||
allImagesFromDisk,
|
||||
imageFromDb,
|
||||
|
|
@ -230,5 +236,4 @@ export default {
|
|||
getAllTags,
|
||||
resizeImage,
|
||||
getDimensions,
|
||||
setTags,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
import Util from './../common/Util'
|
||||
import { Rng } from './../common/Rng'
|
||||
import Images from './Images'
|
||||
import { EncodedPiece, EncodedPieceShape, PieceShape, Puzzle, ShapeMode, ImageInfo } from '../common/Types'
|
||||
import { EncodedPiece, EncodedPieceShape, PieceShape, Puzzle, ShapeMode } from '../common/Types'
|
||||
import { Dim, Point } from '../common/Geometry'
|
||||
import { UPLOAD_DIR } from './Dirs'
|
||||
|
||||
export interface PuzzleCreationImageInfo {
|
||||
file: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface PuzzleCreationInfo {
|
||||
width: number
|
||||
|
|
@ -23,11 +27,11 @@ const TILE_SIZE = 64
|
|||
async function createPuzzle(
|
||||
rng: Rng,
|
||||
targetTiles: number,
|
||||
image: ImageInfo,
|
||||
image: PuzzleCreationImageInfo,
|
||||
ts: number,
|
||||
shapeMode: ShapeMode
|
||||
): Promise<Puzzle> {
|
||||
const imagePath = `${UPLOAD_DIR}/${image.filename}`
|
||||
const imagePath = image.file
|
||||
const imageUrl = image.url
|
||||
|
||||
// determine puzzle information from the image dimensions
|
||||
|
|
@ -135,8 +139,7 @@ async function createPuzzle(
|
|||
},
|
||||
// information that was used to create the puzzle
|
||||
targetTiles: targetTiles,
|
||||
imageUrl, // todo: remove
|
||||
image: image,
|
||||
imageUrl,
|
||||
|
||||
width: info.width, // actual puzzle width (same as bitmap.width)
|
||||
height: info.height, // actual puzzle height (same as bitmap.height)
|
||||
|
|
|
|||
|
|
@ -1,36 +0,0 @@
|
|||
import Time from '../common/Time'
|
||||
import Db from './Db'
|
||||
|
||||
const TABLE = 'users'
|
||||
|
||||
const HEADER_CLIENT_ID = 'client-id'
|
||||
const HEADER_CLIENT_SECRET = 'client-secret'
|
||||
|
||||
const getOrCreateUser = (db: Db, req: any): any => {
|
||||
let user = getUser(db, req)
|
||||
if (!user) {
|
||||
db.insert(TABLE, {
|
||||
'client_id': req.headers[HEADER_CLIENT_ID],
|
||||
'client_secret': req.headers[HEADER_CLIENT_SECRET],
|
||||
'created': Time.timestamp(),
|
||||
})
|
||||
user = getUser(db, req)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
const getUser = (db: Db, req: any): any => {
|
||||
const user = db.get(TABLE, {
|
||||
'client_id': req.headers[HEADER_CLIENT_ID],
|
||||
'client_secret': req.headers[HEADER_CLIENT_SECRET],
|
||||
})
|
||||
if (user) {
|
||||
user.id = parseInt(user.id, 10)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
export default {
|
||||
getOrCreateUser,
|
||||
getUser,
|
||||
}
|
||||
|
|
@ -19,10 +19,9 @@ import {
|
|||
UPLOAD_DIR,
|
||||
} from './Dirs'
|
||||
import GameCommon from '../common/GameCommon'
|
||||
import { ServerEvent, Game as GameType, GameSettings } from '../common/Types'
|
||||
import { ServerEvent, Game as GameType, GameSettings, ScoreMode, ShapeMode, SnapMode } from '../common/Types'
|
||||
import GameStorage from './GameStorage'
|
||||
import Db from './Db'
|
||||
import Users from './Users'
|
||||
|
||||
const db = new Db(DB_FILE, DB_PATCHES_DIR)
|
||||
db.patch()
|
||||
|
|
@ -58,14 +57,6 @@ const storage = multer.diskStorage({
|
|||
})
|
||||
const upload = multer({storage}).single('file');
|
||||
|
||||
app.get('/api/me', (req, res): void => {
|
||||
let user = Users.getUser(db, req)
|
||||
res.send({
|
||||
id: user ? user.id : null,
|
||||
created: user ? user.created : null,
|
||||
})
|
||||
})
|
||||
|
||||
app.get('/api/conf', (req, res): void => {
|
||||
res.send({
|
||||
WS_ADDRESS: config.ws.connectstring,
|
||||
|
|
@ -96,12 +87,11 @@ app.get('/api/replay-data', async (req, res): Promise<void> => {
|
|||
game = await Game.createGameObject(
|
||||
gameId,
|
||||
log[0][2],
|
||||
log[0][3], // must be ImageInfo
|
||||
log[0][3],
|
||||
log[0][4],
|
||||
log[0][5],
|
||||
log[0][6],
|
||||
log[0][7],
|
||||
log[0][8], // creatorUserId
|
||||
)
|
||||
}
|
||||
res.send({ log, game: game ? Util.encodeGame(game) : null })
|
||||
|
|
@ -143,27 +133,32 @@ interface SaveImageRequestData {
|
|||
tags: string[]
|
||||
}
|
||||
|
||||
const setImageTags = (db: Db, imageId: number, tags: string[]): void => {
|
||||
tags.forEach((tag: string) => {
|
||||
const slug = Util.slug(tag)
|
||||
const id = db.upsert('categories', { slug, title: tag }, { slug }, 'id')
|
||||
if (id) {
|
||||
db.insert('image_x_category', {
|
||||
image_id: imageId,
|
||||
category_id: id,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
app.post('/api/save-image', express.json(), (req, res): void => {
|
||||
const user = Users.getUser(db, req)
|
||||
if (!user || !user.id) {
|
||||
res.status(403).send({ ok: false, error: 'forbidden' })
|
||||
return
|
||||
}
|
||||
|
||||
const data = req.body as SaveImageRequestData
|
||||
const image = db.get('images', {id: data.id})
|
||||
if (parseInt(image.uploader_user_id, 10) !== user.id) {
|
||||
res.status(403).send({ ok: false, error: 'forbidden' })
|
||||
return
|
||||
}
|
||||
|
||||
db.update('images', {
|
||||
title: data.title,
|
||||
}, {
|
||||
id: data.id,
|
||||
})
|
||||
|
||||
Images.setTags(db, data.id, data.tags || [])
|
||||
db.delete('image_x_category', { image_id: data.id })
|
||||
|
||||
if (data.tags) {
|
||||
setImageTags(db, data.id, data.tags)
|
||||
}
|
||||
|
||||
res.send({ ok: true })
|
||||
})
|
||||
|
|
@ -171,25 +166,20 @@ app.post('/api/upload', (req, res): void => {
|
|||
upload(req, res, async (err: any): Promise<void> => {
|
||||
if (err) {
|
||||
log.log(err)
|
||||
res.status(400).send("Something went wrong!")
|
||||
return
|
||||
res.status(400).send("Something went wrong!");
|
||||
}
|
||||
|
||||
try {
|
||||
await Images.resizeImage(req.file.filename)
|
||||
} catch (err) {
|
||||
log.log(err)
|
||||
res.status(400).send("Something went wrong!")
|
||||
return
|
||||
res.status(400).send("Something went wrong!");
|
||||
}
|
||||
|
||||
const user = Users.getOrCreateUser(db, req)
|
||||
|
||||
const dim = await Images.getDimensions(
|
||||
`${UPLOAD_DIR}/${req.file.filename}`
|
||||
)
|
||||
const imageId = db.insert('images', {
|
||||
uploader_user_id: user.id,
|
||||
filename: req.file.filename,
|
||||
filename_original: req.file.originalname,
|
||||
title: req.body.title || '',
|
||||
|
|
@ -200,7 +190,7 @@ app.post('/api/upload', (req, res): void => {
|
|||
|
||||
if (req.body.tags) {
|
||||
const tags = req.body.tags.split(',').filter((tag: string) => !!tag)
|
||||
Images.setTags(db, imageId as number, tags)
|
||||
setImageTags(db, imageId as number, tags)
|
||||
}
|
||||
|
||||
res.send(Images.imageFromDb(db, imageId as number))
|
||||
|
|
@ -208,12 +198,21 @@ app.post('/api/upload', (req, res): void => {
|
|||
})
|
||||
|
||||
app.post('/api/newgame', express.json(), async (req, res): Promise<void> => {
|
||||
const user = Users.getOrCreateUser(db, req)
|
||||
const gameId = await Game.createNewGame(
|
||||
req.body as GameSettings,
|
||||
Time.timestamp(),
|
||||
user.id
|
||||
const gameSettings = req.body as GameSettings
|
||||
log.log(gameSettings)
|
||||
const gameId = Util.uniqId()
|
||||
if (!GameCommon.exists(gameId)) {
|
||||
const ts = Time.timestamp()
|
||||
await Game.createGame(
|
||||
gameId,
|
||||
gameSettings.tiles,
|
||||
gameSettings.image,
|
||||
ts,
|
||||
gameSettings.scoreMode,
|
||||
gameSettings.shapeMode,
|
||||
gameSettings.snapMode,
|
||||
)
|
||||
}
|
||||
res.send({ id: gameId })
|
||||
})
|
||||
|
||||
|
|
@ -311,7 +310,7 @@ wss.on('message', async (
|
|||
}
|
||||
})
|
||||
|
||||
GameStorage.loadGamesFromDb(db)
|
||||
GameStorage.loadGames()
|
||||
const server = app.listen(
|
||||
port,
|
||||
hostname,
|
||||
|
|
@ -334,7 +333,7 @@ memoryUsageHuman()
|
|||
// persist games in fixed interval
|
||||
const persistInterval = setInterval(() => {
|
||||
log.log('Persisting games...')
|
||||
GameStorage.persistGamesToDb(db)
|
||||
GameStorage.persistGames()
|
||||
|
||||
memoryUsageHuman()
|
||||
}, config.persistence.interval)
|
||||
|
|
@ -346,7 +345,7 @@ const gracefulShutdown = (signal: string): void => {
|
|||
clearInterval(persistInterval)
|
||||
|
||||
log.log('persisting games...')
|
||||
GameStorage.persistGamesToDb(db)
|
||||
GameStorage.persistGames()
|
||||
|
||||
log.log('shutting down webserver...')
|
||||
server.close()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue