Skip to content

Commit

Permalink
fix: update button is never appearing in prod (#132)
Browse files Browse the repository at this point in the history
  • Loading branch information
MaSch0212 authored Jul 7, 2024
1 parent 9b39b79 commit cad1a86
Show file tree
Hide file tree
Showing 16 changed files with 140 additions and 66 deletions.
1 change: 0 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ ENV WEBPUSH__PRIVATEKEY=

COPY src/server/host/bin/Release/publish .
COPY src/client/dist/minigolf-friday/browser ./wwwroot/
RUN sed -i "s/\$VERSION/$BUILDTIME/g" wwwroot/index.html

HEALTHCHECK CMD wget --no-verbose --tries=1 --spider http://localhost/healthz || exit 1

Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@
"docker:build:inttest": "node src/scripts/docker-build-inttest.js",
"docker:push": "node src/scripts/docker-push.js",
"test:integration": "dotnet test test/MinigolfFriday.IntegrationTests/MinigolfFriday.IntegrationTests.csproj"
},
"devDependencies": {
"@types/node": "^20.14.10"
}
}
22 changes: 21 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 1 addition & 7 deletions src/client/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ <h1>{{ translations.playerEvents_greetings() | interpolate: { name: user.alias }
>
</ng-template>
</p-messages>
} @else {
} @else if (user()?.roles?.includes('player')) {
<div class="flex h-full w-full max-w-[40rem] flex-col gap-4 overflow-auto pb-4">
<h2 class="m-0">{{ translations.playerEvents_currentEvents() }}</h2>
<div class="rounded-lg border-[1px] border-solid border-surface-d bg-surface-a">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { RouterLink } from '@angular/router';
import { Store } from '@ngrx/store';
import { MessagesModule } from 'primeng/messages';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { map, timer } from 'rxjs';
Expand All @@ -28,7 +27,6 @@ const dayMillis = 24 * 60 * 60 * 1000;
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PlayerEventsComponent {
private readonly _store = inject(Store);
private readonly _translateService = inject(TranslateService);

protected readonly translations = this._translateService.translations;
Expand Down
4 changes: 1 addition & 3 deletions src/client/src/app/environments/environment.prod.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { Environment } from './environment.type';

const minigolfFriday: { version: string } = (window as any).minigolfFriday;

export const environment: Environment = {
getProviders: () => [],
authenticationRequired: true,
...minigolfFriday,
version: (document.head.querySelector('meta[name="version"]') as HTMLMetaElement)?.content ?? '',
};
12 changes: 7 additions & 5 deletions src/client/src/app/services/update.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { SwUpdate } from '@angular/service-worker';
import { merge, filter, map } from 'rxjs';
import { merge, filter, map, debounceTime } from 'rxjs';

import { RealtimeEventsService } from './realtime-events.service';
import { onDocumentVisibilityChange$ } from '../utils/event.utils';
Expand All @@ -24,10 +24,12 @@ export class UpdateService {
merge(
onDocumentVisibilityChange$().pipe(filter(isVisible => isVisible)),
this._realtimeEventsService.onReconnected$
).subscribe(() => {
console.info('Checking for updates...');
this._swUpdate.checkForUpdate().then(x => console.info('Update check result:', x));
});
)
.pipe(debounceTime(1000))
.subscribe(() => {
console.info('Checking for updates...');
this._swUpdate.checkForUpdate().then(x => console.info('Update check result:', x));
});
this._swUpdate.unrecoverable.subscribe(() => location.reload());
}
}
Expand Down
5 changes: 1 addition & 4 deletions src/client/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover"
/>
<link rel="manifest" href="manifest.webmanifest" />
<meta name="version" content="" />

<!-- Android -->
<meta name="mobile-web-app-capable" content="yes" />
Expand Down Expand Up @@ -40,10 +41,6 @@
if (theme === 'dark') {
document.body.classList.add('dark');
}

window.minigolfFriday = {
version: '$VERSION',
};
</script>
<app-root></app-root>
<noscript>Please enable JavaScript to continue using this application.</noscript>
Expand Down
2 changes: 1 addition & 1 deletion src/scripts/add-migration.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { spawnSync } from "child_process";
import { argv } from "process";
import { repoRootDir } from "./vars.js";
import { repoRootDir } from "./utils.js";
import path from "path";

const name = argv[2];
Expand Down
2 changes: 1 addition & 1 deletion src/scripts/docker-build-inttest.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { spawnSync } from "child_process";
import { repository, imageName, repoRootDir, getArg, getVersionTag } from "./vars.js";
import { repository, imageName, repoRootDir, getArg, getVersionTag } from "./utils.js";

const configuration = getArg("--configuration", "-c") ?? "Release";

Expand Down
31 changes: 18 additions & 13 deletions src/scripts/docker-build.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { spawnSync } from "child_process";
import { repository, imageName, repoRootDir, getVersionTag } from "./vars.js";
import { repository, imageName, repoRootDir, getVersionTag, setIndexHtmlVersion } from "./utils.js";

const buildtime = getVersionTag();
spawnSync(
"docker",
[
"build",
`-t=${repository}/${imageName}:latest`,
`-t=${repository}/${imageName}:${buildtime}`,
`--build-arg=BUILDTIME=${buildtime}`,
".",
],
{ cwd: repoRootDir, stdio: "inherit" }
);
(async () => {
const buildtime = getVersionTag();

await setIndexHtmlVersion("src/client/dist/minigolf-friday/browser", buildtime);

spawnSync(
"docker",
[
"build",
`-t=${repository}/${imageName}:latest`,
`-t=${repository}/${imageName}:${buildtime}`,
`--build-arg=BUILDTIME=${buildtime}`,
".",
],
{ cwd: repoRootDir, stdio: "inherit" }
);
})();
2 changes: 1 addition & 1 deletion src/scripts/docker-push.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { spawnSync } from "child_process";
import { repository, imageName, repoRootDir, getVersionTag } from "./vars.js";
import { repository, imageName, repoRootDir, getVersionTag } from "./utils.js";
import { appendFileSync } from "fs";

const inspectResult = spawnSync(
Expand Down
3 changes: 1 addition & 2 deletions src/scripts/remove-migration.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { spawnSync } from "child_process";
import { argv } from "process";
import { repoRootDir } from "./vars.js";
import { repoRootDir } from "./utils.js";
import path from "path";

const buildResult = spawnSync("dotnet", ["build"], {
Expand Down
83 changes: 83 additions & 0 deletions src/scripts/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import crypt from "crypto";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { argv } from "process";

export const repoRootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
export const imageName = "minigolf-friday";
export const repository = "masch0212";

export function getVersionTag() {
const dateIso = new Date().toISOString();
return dateIso.replace(/[-T:.Z]/g, (x) => (x === "T" ? "-" : "")).substring(0, 15);
}

export function getArg(longName, shortName) {
const longIndex = argv.indexOf(longName);
if (longIndex > -1) {
return argv[longIndex + 1];
}
const shortIndex = argv.indexOf(shortName);
if (shortIndex > -1) {
return argv[shortIndex + 1];
}
return null;
}

export async function setIndexHtmlVersion(distDir, version) {
const indexHtmlPath = path.resolve(distDir, "index.html");
if (!fs.existsSync(indexHtmlPath)) {
throw new Error(`File ${indexHtmlPath} not found`);
}

let indexHtml = fs.readFileSync(indexHtmlPath, "utf8");
indexHtml = indexHtml.replace(
/<meta name="version" content(="[^"]*")?\s*(\/)?>/,
`<meta name="version" content="${version}" \/>`
);
fs.writeFileSync(indexHtmlPath, indexHtml);
await rebuildNgswFileHash(distDir, "/index.html");
}

function rebuildNgswFileHash(distDir, file) {
const ngswPath = path.resolve(distDir, "ngsw.json");
if (!fs.existsSync(ngswPath)) {
console.error(`File ${ngswPath} not found`);
process.exit(1);
}

const ngsw = JSON.parse(fs.readFileSync(ngswPath, "utf8"));
if (!ngsw.hashTable[file]) {
console.error(`File ${file} not found in ngsw.json`);
process.exit(1);
}

const filePath = path.resolve(distDir, file.replace(/^\//, ""));
if (!fs.existsSync(filePath)) {
console.error(`File ${filePath} not found`);
process.exit(1);
}

const fd = fs.createReadStream(filePath);
const hash = crypt.createHash("sha1");
hash.setEncoding("hex");

return new Promise((resolve, reject) => {
fd.on("end", () => {
hash.end();

try {
console.log(`Old hash for ${file}: ${ngsw.hashTable[file]}`);
ngsw.hashTable[file] = hash.read();
console.log(`New hash for ${file}: ${ngsw.hashTable[file]}`);
fs.writeFileSync(ngswPath, JSON.stringify(ngsw, null, 2));
resolve();
} catch (error) {
reject(error);
}
});

fd.pipe(hash);
});
}
24 changes: 0 additions & 24 deletions src/scripts/vars.js

This file was deleted.

0 comments on commit cad1a86

Please sign in to comment.