Skip to content

Commit

Permalink
Lots of broken stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
qdraw committed Mar 7, 2024
1 parent 50936f3 commit e48b750
Show file tree
Hide file tree
Showing 18 changed files with 311 additions and 315 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,6 @@ internal DbContextOptions<ApplicationDbContext> BuilderDbFactorySwitch(
public void BuilderDb(string? foundationDatabaseName = "")
{
if ( _services == null ) throw new AggregateException("services is missing");
if ( _logger != null && _appSettings.IsVerbose() )
{
_logger.LogInformation($"Database connection: {_appSettings.DatabaseConnection}");
}

_services.AddScoped(_ =>
new ApplicationDbContext(BuilderDbFactorySwitch(foundationDatabaseName)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,20 +87,5 @@ public void BuilderDb_fail()
new SetupDatabaseTypes(appSettings).BuilderDb();
// expect exception
}

[TestMethod]
public void BuilderDb_console()
{
var console = new FakeIWebLogger();
var appSettings = new AppSettings
{
Verbose = true, DatabaseType = AppSettings.DatabaseTypeList.InMemoryDatabase
};
var services = new ServiceCollection();

new SetupDatabaseTypes(appSettings, services, console).BuilderDb();

Assert.IsTrue(console.TrackedInformation[0].Item2?.Contains("Database connection:"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as fs from "fs";
import * as readline from "readline";
import * as GetPortProxy from "../get-free-port/get-free-port";
import logger from "../logger/logger";
import { setupChildProcess } from "./setup-child-process";
import { SetupChildProcess } from "./setup-child-process";

jest.mock("child_process", () => {
return {
Expand Down Expand Up @@ -84,7 +84,7 @@ describe("setupChildProcess", () => {
return null;
});

await setupChildProcess();
await SetupChildProcess();

expect(mkdirSpy).toHaveBeenCalled();
expect(mkdirSpy).toHaveBeenCalledTimes(2);
Expand Down
213 changes: 107 additions & 106 deletions starskydesktop/src/app/child-process/setup-child-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as fs from "fs";
import * as path from "path";
import * as readline from "readline";
import { GetFreePort } from "../get-free-port/get-free-port";
import global, { SharedSettings } from "../global/global";
import logger from "../logger/logger";
import { isPackaged } from "../os-info/is-packaged";
import { childProcessPath } from "./child-process-path";
Expand All @@ -17,8 +18,8 @@ function spawnChildProcess(appStarskyPath: string) {
env: process.env,
});

starskyChild.on("exit", function (code) {
logger.info("EXIT: CODE: " + code);
starskyChild.on("exit", (code) => {
logger.info(`EXIT: CODE: ${code}`);
});

starskyChild.stdout.on("data", (data: string) => {
Expand All @@ -32,116 +33,116 @@ function spawnChildProcess(appStarskyPath: string) {
return starskyChild;
}

export function setupChildProcess() :Promise<number> {
return new Promise((resolve) => {
const thumbnailTempFolder = path.join(electronCacheLocation(), "thumbnailTempFolder");
if (!fs.existsSync(thumbnailTempFolder)) {
fs.mkdirSync(thumbnailTempFolder);
}

const tempFolder = path.join(electronCacheLocation(), "tempFolder");
if (!fs.existsSync(tempFolder)) {
fs.mkdirSync(tempFolder);
}

const appSettingsPath = path.join(electronCacheLocation(), "appsettings.json");
const databaseConnection = `Data Source=${path.join(electronCacheLocation(), "starsky.db")}`;

GetFreePort().then((appPort)=>{
logger.info(`next: port: ${appPort}`);
logger.info(`-appSettingsPath > ${appSettingsPath}`);

const env = {
ASPNETCORE_URLS: `http://localhost:${appPort}`,
app__thumbnailTempFolder: thumbnailTempFolder,
app__tempFolder: tempFolder,
app__appsettingspath: appSettingsPath,
app__NoAccountLocalhost: "true",
app__UseLocalDesktop: "true",
app__databaseConnection: databaseConnection,
app__ThumbnailGenerationIntervalInMinutes: !isPackaged() ? "-1" : "300",
app__AccountRegisterDefaultRole: "Administrator",
app__Verbose: !isPackaged() ? "true" : "false",
};
process.env = { ...process.env, ...env };

logger.info("env settings ->");
logger.info(env);
logger.info(`app data folder -> ${path.join(app.getPath("appData"), "starsky")}`);

const appStarskyPath = childProcessPath();

try {
fs.chmodSync(appStarskyPath, 0o755);
} catch (error) {
// do nothing
}

let starskyChild = spawnChildProcess(appStarskyPath);

starskyChild.addListener("exit", () => {
logger.info("restart process");

SpawnCleanMacOs(appStarskyPath, process.platform).then(() => {
starskyChild = spawnChildProcess(appStarskyPath);
starskyChild.stdout.on("data",()=> resolve(appPort))
function CreateFolder() {
const thumbnailTempFolder = path.join(electronCacheLocation(), "thumbnailTempFolder");
if (!fs.existsSync(thumbnailTempFolder)) {
fs.mkdirSync(thumbnailTempFolder);
}

const tempFolder = path.join(electronCacheLocation(), "tempFolder");
if (!fs.existsSync(tempFolder)) {
fs.mkdirSync(tempFolder);
}
return {
tempFolder,
thumbnailTempFolder,
};
}

function Env(appPort: number) {
const databaseConnection = `Data Source=${path.join(electronCacheLocation(), "starsky.db")}`;
const appSettingsPath = path.join(electronCacheLocation(), "appsettings.json");
const result = CreateFolder();

// Set Global Helper
(global.shared as SharedSettings).port = appPort;
(global.shared as SharedSettings).remote = false;
(global.shared as SharedSettings).baseUrl = `http://localhost:${appPort}`;

return {
ASPNETCORE_URLS: `http://localhost:${appPort}`,
app__thumbnailTempFolder: result.thumbnailTempFolder,
app__tempFolder: result.tempFolder,
app__appsettingspath: appSettingsPath,
app__NoAccountLocalhost: "true",
app__UseLocalDesktop: "true",
app__databaseConnection: databaseConnection,
app__ThumbnailGenerationIntervalInMinutes: !isPackaged() ? "-1" : "300",
app__AccountRegisterDefaultRole: "Administrator",
app__Verbose: !isPackaged() ? "true" : "false",
};
}

function StartProcess(): Promise<number> {
return new Promise((resolve, reject) => {
CreateFolder();
GetFreePort()
.then((appPort) => {
const env = Env(appPort);
process.env = { ...process.env, ...env };

const appStarskyPath = childProcessPath();

try {
fs.chmodSync(appStarskyPath, 0o755);
} catch (error) {
// do nothing
}

const starskyChild = spawnChildProcess(appStarskyPath);

starskyChild.on("exit", () => {
SpawnCleanMacOs(appStarskyPath, process.platform)
.then(() => {
reject(new Error("Retry please: process failed"));
})
.catch(reject);
});

});

starskyChild.stdout.on("data",()=> resolve(appPort))

starskyChild.addListener("close", () => {
logger.info("restart process");
// eslint-disable-next-line @typescript-eslint/no-floating-promises
GetFreePort().then((p) => {
appPort = p;
env.ASPNETCORE_URLS = `http://localhost:${appPort}`;
logger.info(`next: port: ${appPort}`);
starskyChild = spawnChildProcess(appStarskyPath);
starskyChild.stdout.on("data", () => {
resolve(appPort);
});
});

readline.emitKeypressEvents(process.stdin);

/**
* Needed for terminals
* @param {bool} modes true or false
*/
function setRawMode(modes: boolean) {
if (!process.stdin.setRawMode) return;
process.stdin.setRawMode(modes);
}

function kill() {
setRawMode(false);
if (!starskyChild) return;
starskyChild.stdin.end();
starskyChild.kill();
}

setRawMode(true);

process.stdin.on("keypress", (_, key: { name: string; ctrl: string }) => {
if (key.ctrl && key.name === "c") {

readline.emitKeypressEvents(process.stdin);

function setRawMode(modes: boolean) {
if (!process.stdin.setRawMode) return;
process.stdin.setRawMode(modes);
}

function kill() {
setRawMode(false);
if (!starskyChild) return;
starskyChild.stdin.end();
starskyChild.kill();
}

setRawMode(true);

process.stdin.on("keypress", (_, key: { name: string; ctrl: string }) => {
if (key.ctrl && key.name === "c") {
kill();
logger.info("=> (pressed ctrl & c) to the end of starsky");
setTimeout(() => {
process.exit(0);
}, 400);
}
});

app.on("before-quit", (event) => {
event.preventDefault();
logger.info("=> end default");
kill();
logger.info("=> (pressed ctrl & c) to the end of starsky");
setTimeout(() => {
process.exit(0);
}, 400);
}
});

app.on("before-quit", (event) => {
event.preventDefault();
logger.info("=> end default");
kill();
setTimeout(() => {
process.exit(0);
}, 400);
});
});


});
})
.catch(reject);
});
}

export async function SetupChildProcess(): Promise<number> {
// Start the process
return StartProcess();
}
8 changes: 4 additions & 4 deletions starskydesktop/src/app/child-process/spawn-clean-mac-os.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function executeCodesignCommand(appStarskyPath: string): Promise<void> {
const codeSignSpawn = spawn("codesign", args, options);

codeSignSpawn.on("exit", (code) => {
logger.info("code sign EXIT: CODE: " + code);
logger.info(`code sign EXIT: CODE: ${code}`);
if (code === 0) {
resolve();
} else {
Expand All @@ -68,15 +68,15 @@ function executeCodesignCommand(appStarskyPath: string): Promise<void> {
});
}

export function SpawnCleanMacOs(appStarskyPath: string, processPlatform: string): Promise<void> {
export function SpawnCleanMacOs(appStarskyPath: string, processPlatform: string): Promise<boolean> {
return new Promise((resolve, reject) => {
if (processPlatform !== "darwin") {
return resolve();
resolve(true);
}

Promise.all([executeXattrCommand(appStarskyPath), executeCodesignCommand(appStarskyPath)])
.then(() => {
resolve();
resolve(true);
})
.catch((err) => {
reject(err);
Expand Down
12 changes: 12 additions & 0 deletions starskydesktop/src/app/global/global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export interface SharedSettings {
port: number;
remote: boolean | undefined;
baseUrl: string;
}

global.shared = {
port: -1,
remote: undefined,
baseUrl: ``,
} as SharedSettings;
export default global;
21 changes: 12 additions & 9 deletions starskydesktop/src/app/main-window/create-main-window.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { BrowserWindow } from "electron";
import * as path from "path";
import { GetAppVersion } from "../config/get-app-version";
import logger from "../logger/logger";
import { windowStateKeeper } from "../window-state-keeper/window-state-keeper";
import { getNewFocusedWindow } from "./get-new-focused-window";
import { mainWindows } from "./main-windows.const";
import { removeRememberUrl, saveRememberUrl } from "./save-remember-url";
import { spellCheck } from "./spellcheck";

async function createMainWindow(openSpecificUrl: string, offset = 0): Promise<BrowserWindow> {
async function CreateMainWindow(openSpecificUrl: string, offset = 0): Promise<BrowserWindow> {
const mainWindowStateKeeper = await windowStateKeeper("main");

const { x, y } = getNewFocusedWindow(
Expand All @@ -24,7 +25,7 @@ async function createMainWindow(openSpecificUrl: string, offset = 0): Promise<Br
webPreferences: {
allowRunningInsecureContent: false,
nodeIntegration: false,
sandbox: false,
sandbox: true,
webviewTag: true,
spellcheck: true,
partition: "persist:main",
Expand All @@ -38,11 +39,12 @@ async function createMainWindow(openSpecificUrl: string, offset = 0): Promise<Br

mainWindowStateKeeper.track(newWindow);

const location = path.join(__dirname, "client/pages/start/start.html");
logger.info(`[CreateMainWindow] url: ${openSpecificUrl} l: ${location}`);

await newWindow.loadURL(openSpecificUrl)
// await newWindow.loadFile(location, {
// query: { "remember-url": openSpecificUrl },
// });
await newWindow.loadFile(location, {
query: { "remember-url": openSpecificUrl },
});

spellCheck(newWindow);

Expand All @@ -51,8 +53,7 @@ async function createMainWindow(openSpecificUrl: string, offset = 0): Promise<Br
});

newWindow.webContents.setWindowOpenHandler(({ url }) => {
console.log(url);

logger.info(`[setWindowOpenHandler] ${url}`);
return {
action: "allow",
overrideBrowserWindowOptions: {
Expand Down Expand Up @@ -91,7 +92,9 @@ async function createMainWindow(openSpecificUrl: string, offset = 0): Promise<Br
});

mainWindows.add(newWindow);
logger.info(`[CreateMainWindow] url / newWindow: ${openSpecificUrl}`);

return newWindow;
}

export default createMainWindow;
export default CreateMainWindow;
Loading

0 comments on commit e48b750

Please sign in to comment.