Skip to content

Commit

Permalink
Attempt at cache busting
Browse files Browse the repository at this point in the history
  • Loading branch information
codemonkey85 committed Dec 4, 2024
1 parent cb0da5f commit 58c5608
Show file tree
Hide file tree
Showing 13 changed files with 174 additions and 11 deletions.
12 changes: 12 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ jobs:
# uses GitHub's checkout action to checkout code form the main branch
- uses: actions/[email protected]

- name: UpdateVersionInMainLayout
uses: datamonsters/replace-action@v2
with:
files: 'TiredDoctorManhattan.Wasm/Pages/Index.razor.cs'
replacements: '%%CACHE_VERSION%%=${{ github.run_id }}'

# sets up .NET SDK
- name: Setup .NET Core SDK
uses: actions/[email protected]
Expand Down Expand Up @@ -41,6 +47,12 @@ jobs:
- name: Add .nojekyll file
run: touch release/wwwroot/.nojekyll

- name: UpdateVersion
uses: datamonsters/replace-action@v2
with:
files: 'release/wwwroot/service-worker.published.js'
replacements: '%%CACHE_VERSION%%=${{ github.run_id }}'

- name: Commit wwwroot to GitHub Pages
uses: JamesIves/[email protected]
with:
Expand Down
2 changes: 2 additions & 0 deletions TiredDoctorManhattan.Wasm/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
global using Microsoft.AspNetCore.Components;
global using Microsoft.AspNetCore.Components.Web;
global using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
global using Microsoft.JSInterop;
global using SixLabors.Fonts;
global using SixLabors.ImageSharp;
global using SixLabors.ImageSharp.Drawing;
Expand All @@ -11,4 +12,5 @@
global using System.Diagnostics;
global using System.Diagnostics.CodeAnalysis;
global using TiredDoctorManhattan.Wasm;
global using TiredDoctorManhattan.Wasm.Services;
global using TiredDoctorManhattan.Wasm.Shared;
13 changes: 13 additions & 0 deletions TiredDoctorManhattan.Wasm/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@
@PageTitle
</PageTitle>

@if (IsUpdateAvailable)
{
<div class="alert alert-warning alert-dismissible fade show"
role="alert">
A new version of the app is available. Please refresh the page to update.
<button type="button"
class="btn-close"
data-bs-dismiss="alert"
aria-label="Close">
</button>
</div>
}

<h1>
@PageTitle
</h1>
Expand Down
19 changes: 18 additions & 1 deletion TiredDoctorManhattan.Wasm/Pages/Index.razor.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
namespace TiredDoctorManhattan.Wasm.Pages;

public partial class Index
public partial class Index : IDisposable
{
private const string BackgroundImageLocation = "assets/background.png";
private const string FontLocation = "assets/KMKDSPK_.ttf";

#pragma warning disable IDE0051 // Remove unused private members
private const string DeploymentId = "%%CACHE_VERSION%%";
#pragma warning restore IDE0051 // Remove unused private members

[Parameter] public string? TextToRender { get; set; }

private static string PageTitle => "Tired Doctor Manhattan";
Expand All @@ -13,6 +17,8 @@ public partial class Index

private byte[]? ImageBytes { get; set; }

private bool IsUpdateAvailable { get; set; } = false;

private string? GetImageBase64 => ImageBytes is null
? null
: Convert.ToBase64String(ImageBytes);
Expand All @@ -21,6 +27,17 @@ public partial class Index

private TimeSpan? GenerationTime { get; set; }

protected override void OnInitialized() => UpdateAlertService.OnUpdateAvailable += ShowUpdateMessage;

public void Dispose() => UpdateAlertService.OnUpdateAvailable -= ShowUpdateMessage;

public void ShowUpdateMessage()
{
// Display the alert when an update is available
IsUpdateAvailable = true;
StateHasChanged();
}

private async Task GenerateImage()
{
IsWorking = true;
Expand Down
11 changes: 7 additions & 4 deletions TiredDoctorManhattan.Wasm/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
var builder = WebAssemblyHostBuilder.CreateDefault(args);
var services = builder.Services;

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(_ => new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
services
.AddSingleton(_ => new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
})
.AddSingleton<IUpdateAlertService, UpdateAlertService>();

await builder.Build().RunAsync();
8 changes: 8 additions & 0 deletions TiredDoctorManhattan.Wasm/Services/IUpdateAlertService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace TiredDoctorManhattan.Wasm.Services;

public interface IUpdateAlertService
{
event Action? OnUpdateAvailable;

void ShowUpdateMessage();
}
15 changes: 15 additions & 0 deletions TiredDoctorManhattan.Wasm/Services/UpdateAlertService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace TiredDoctorManhattan.Wasm.Services;

public class UpdateAlertService : IUpdateAlertService
{
public static UpdateAlertService? Instance { get; private set; }

public event Action? OnUpdateAvailable;

public UpdateAlertService() => Instance = this;

void IUpdateAlertService.ShowUpdateMessage() => ShowUpdateMessage();

[JSInvokable(nameof(ShowUpdateMessage))]
public static void ShowUpdateMessage() => Instance?.OnUpdateAvailable?.Invoke();
}
7 changes: 7 additions & 0 deletions TiredDoctorManhattan.Wasm/TiredDoctorManhattan.Wasm.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
<EmccMaximumHeapSize>268435456</EmccMaximumHeapSize>
<WasmEnableSIMD>false</WasmEnableSIMD>
<InvariantGlobalization>true</InvariantGlobalization>
<BlazorWebAssemblyEnableLinking>true</BlazorWebAssemblyEnableLinking>
<BlazorEnableCompression>true</BlazorEnableCompression>
<GenerateServiceWorkerAssetsManifest>true</GenerateServiceWorkerAssetsManifest>
</PropertyGroup>

<ItemGroup>
Expand All @@ -24,6 +27,10 @@
<ServiceWorker Include="wwwroot\service-worker.js" PublishedContent="wwwroot\service-worker.published.js" />
</ItemGroup>

<Target Name="CopyServiceWorkerPublished" AfterTargets="Publish">
<Copy SourceFiles="wwwroot\service-worker.published.js" DestinationFiles="$(PublishDir)wwwroot\service-worker.published.js" />
</Target>

<ItemGroup>
<Content Update="wwwroot\assets\background.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
Expand Down
2 changes: 2 additions & 0 deletions TiredDoctorManhattan.Wasm/_Imports.razor
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.JSInterop
@using TiredDoctorManhattan.Wasm
@using TiredDoctorManhattan.Wasm.Services
@using TiredDoctorManhattan.Wasm.Shared

@inject HttpClient HttpClient
@inject IUpdateAlertService UpdateAlertService
22 changes: 22 additions & 0 deletions TiredDoctorManhattan.Wasm/wwwroot/BrowserNotSupported.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tired Doctor Manhattan</title>
<link rel="icon" type="image/png" sizes="512x512" href="icon-512.png" />
<link rel="icon" type="image/png" sizes="192x192" href="icon-192.png" />
<link rel="apple-touch-icon" sizes="512x512" href="icon-512.png" />
<link rel="apple-touch-icon" sizes="192x192" href="icon-192.png" />
</head>

<body>
<h1>
Tired Doctor Manhattan
</h1>

Tired Doctor Manhattan is not supported in the current browser. For a list of compatible browsers, see here: <a href="https://caniuse.com/wasm" target="_blank">https://caniuse.com/wasm</a>
</body>

</html>
58 changes: 55 additions & 3 deletions TiredDoctorManhattan.Wasm/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tired Doctor Manhattan</title>
<base href="/" />
<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
Expand All @@ -17,6 +17,9 @@
</head>

<body>

<div class="status-bar-safe-area"></div>

<div id="app">
<svg class="loading-progress">
<circle r="40%" cx="50%" cy="50%" />
Expand All @@ -30,8 +33,57 @@
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
<script>navigator.serviceWorker.register('service-worker.js');</script>
<!--prevent autostarting-->
<script src="_framework/blazor.webassembly.js" autostart="false"></script>
<script>
navigator.serviceWorker.register('service-worker.published.js', { updateViaCache: 'none' }).then(registration => {
setInterval(() => registration.update(), 1 * 60 * 60 * 1000); // check for updates every hour
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed' && navigator.serviceWorker.controller) {
// Notify Blazor about the update
window.dispatchEvent(new CustomEvent('updateAvailable'));
}
};
};
});
</script>

<script>
//check if webassembly is supported
const webassemblySupported = (function () {
try {
if (typeof WebAssembly === "object"
&& typeof WebAssembly.instantiate === "function") {
const module = new WebAssembly.Module(
Uint8Array.of(0x0, 0x61, 0x73, 0x6d,
0x01, 0x00, 0x00, 0x00));
if (module instanceof WebAssembly.Module)
return new WebAssembly.Instance(module)
instanceof WebAssembly.Instance;
}
} catch (e) {
}
return false;
})();
// Modern browsers e.g. Microsoft Edge
if (webassemblySupported) {
Blazor.start({});
}
// Older browsers e.g. IE11
else {
window.location = window.location + "BrowserNotSupported.html";
}
</script>

<script>
window.addUpdateListener = () => {
window.addEventListener('updateAvailable', () => {
DotNet.invokeMethodAsync('TiredDoctorManhattan.Wasm', 'ShowUpdateMessage');
});
};
</script>
</body>

</html>
1 change: 1 addition & 0 deletions TiredDoctorManhattan.Wasm/wwwroot/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "Tired Doctor Manhattan",
"short_name": "Tired Dr Manhattan",
"start_url": "./",
"scope": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#03173d",
Expand Down
15 changes: 12 additions & 3 deletions TiredDoctorManhattan.Wasm/wwwroot/service-worker.published.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,21 @@
// offline support. See https://aka.ms/blazor-offline-considerations

self.importScripts('./service-worker-assets.js');
self.addEventListener('install', event => event.waitUntil(onInstall(event)));
self.addEventListener('activate', event => event.waitUntil(onActivate(event)));
self.addEventListener('install', event => {
self.skipWaiting();
event.waitUntil(onInstall(event));
});

self.addEventListener('activate', event => {
event.waitUntil(onActivate(event));
self.clients.claim();
});
self.addEventListener('fetch', event => event.respondWith(onFetch(event)));

const cacheNamePrefix = 'offline-cache-';
const cacheName = `${cacheNamePrefix}${self.assetsManifest.version}`;
const CACHE_VERSION = '%%CACHE_VERSION%%'
const cacheName = `${cacheNamePrefix}${self.assetsManifest.version}${CACHE_VERSION}`;

const offlineAssetsInclude = [ /\.dll$/, /\.pdb$/, /\.wasm/, /\.html/, /\.js$/, /\.json$/, /\.css$/, /\.woff$/, /\.png$/, /\.jpe?g$/, /\.gif$/, /\.ico$/, /\.blat$/, /\.dat$/ ];
const offlineAssetsExclude = [ /^service-worker\.js$/ ];

Expand Down

0 comments on commit 58c5608

Please sign in to comment.