Skip to content

Commit 3de9f2b

Browse files
author
Rick Butterfield
committed
Fix issue where resource-checker.js couldn't be found
1 parent 126b671 commit 3de9f2b

File tree

10 files changed

+179
-46
lines changed

10 files changed

+179
-46
lines changed

src/Umbraco.Community.Sustainability/Controllers/SustainabilityController.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22
using Microsoft.AspNetCore.Mvc;
33
using Umbraco.Cms.Core;
44
using Umbraco.Cms.Core.Models.PublishedContent;
5-
using Umbraco.Cms.Web.Common.Controllers;
5+
using Umbraco.Cms.Web.BackOffice.Controllers;
66
using Umbraco.Community.Sustainability.Models;
77
using Umbraco.Community.Sustainability.Schemas;
88
using Umbraco.Community.Sustainability.Services;
99
using Umbraco.Extensions;
1010

1111
namespace Umbraco.Community.Sustainability.Controllers
1212
{
13-
public class SustainabilityController : UmbracoApiController
13+
public class SustainabilityController : UmbracoAuthorizedApiController
1414
{
1515
private readonly IPublishedContentQuery _contentQuery;
1616
private readonly IPageMetricService _pageMetricService;
@@ -27,9 +27,9 @@ public SustainabilityController(
2727
}
2828

2929
[HttpGet]
30-
public IActionResult GetPageData([FromQuery] int pageId)
30+
public async Task<IActionResult> GetPageData([FromQuery] int pageId)
3131
{
32-
var pageMetrics = _pageMetricService.GetPageMetrics(pageId);
32+
var pageMetrics = await _pageMetricService.GetPageMetrics(pageId);
3333
var mostRecent = pageMetrics.OrderByDescending(x => x.RequestDate).FirstOrDefault();
3434
if (mostRecent?.PageData == null)
3535
{
@@ -56,7 +56,7 @@ public async Task<IActionResult> CheckPage([FromQuery] int pageId)
5656
}
5757

5858
[HttpPost]
59-
public IActionResult SavePageData([FromQuery] int pageId, [FromBody] SustainabilityResponse data)
59+
public async Task<IActionResult> SavePageData([FromQuery] int pageId, [FromBody] SustainabilityResponse data)
6060
{
6161
if (data.TotalSize == 0)
6262
{
@@ -74,7 +74,7 @@ public IActionResult SavePageData([FromQuery] int pageId, [FromBody] Sustainabil
7474
PageData = JsonSerializer.Serialize(data),
7575
};
7676

77-
_pageMetricService.AddPageMetric(pageMetric);
77+
await _pageMetricService.AddPageMetric(pageMetric);
7878
return Ok(true);
7979
}
8080
}

src/Umbraco.Community.Sustainability/Models/ExternalResource.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1+
using Newtonsoft.Json;
2+
13
namespace Umbraco.Community.Sustainability.Models
24
{
35
public class ExternalResource
46
{
7+
[JsonProperty("url")]
58
public string? Url { get; set; }
9+
10+
[JsonProperty("size")]
611
public decimal Size { get; set; } = 0;
712

813
public ExternalResource() { }

src/Umbraco.Community.Sustainability/Models/ExternalResourceGroup.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
11
using System.ComponentModel.DataAnnotations;
2+
using Newtonsoft.Json;
23
using Umbraco.Community.Sustainability.Extensions;
34

45
namespace Umbraco.Community.Sustainability.Models
56
{
67
public class ExternalResourceGroup
78
{
9+
[JsonProperty("type")]
810
public ResourceGroupType Type { get; set; }
11+
12+
[JsonProperty("name")]
913
public string? Name { get; set; }
14+
15+
[JsonProperty("totalSize")]
1016
public decimal TotalSize { get; set; } = 0;
17+
18+
[JsonProperty("resources")]
1119
public List<ExternalResource>? Resources { get; set; } = new List<ExternalResource>();
1220

1321
public ExternalResourceGroup() { }
Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
1+
using Newtonsoft.Json;
2+
13
namespace Umbraco.Community.Sustainability.Models
24
{
35
public class SustainabilityResponse
46
{
7+
[JsonProperty("lastRunDate")]
58
public DateTime LastRunDate { get; set; } = DateTime.UtcNow;
9+
10+
[JsonProperty("totalSize")]
611
public decimal TotalSize { get; set; } = 0;
12+
13+
[JsonProperty("totalEmissions")]
714
public float TotalEmissions { get; set; } = 0;
8-
public string CarbonRating { get; set; }
15+
16+
[JsonProperty("carbonRating")]
17+
public string? CarbonRating { get; set; }
18+
19+
[JsonProperty("resourceGroups")]
920
public List<ExternalResourceGroup>? ResourceGroups { get; set; }
1021
}
1122
}

src/Umbraco.Community.Sustainability/Services/PageMetricService.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ namespace Umbraco.Community.Sustainability.Services
55
{
66
public interface IPageMetricService
77
{
8-
IEnumerable<PageMetric> GetPageMetrics(int pageId);
9-
void AddPageMetric(PageMetric pageMetric);
8+
Task<IEnumerable<PageMetric>> GetPageMetrics(int pageId);
9+
Task AddPageMetric(PageMetric pageMetric);
1010
}
1111

1212
public class PageMetricService : IPageMetricService
@@ -18,19 +18,19 @@ public PageMetricService(IScopeProvider scopeProvider)
1818
_scopeProvider = scopeProvider;
1919
}
2020

21-
public IEnumerable<PageMetric> GetPageMetrics(int pageId)
21+
public async Task<IEnumerable<PageMetric>> GetPageMetrics(int pageId)
2222
{
2323
using var scope = _scopeProvider.CreateScope();
24-
var queryResults = scope.Database.Fetch<PageMetric>($"SELECT * FROM {PageMetric.TableName} WHERE NodeId = @0", pageId);
24+
var queryResults = await scope.Database.FetchAsync<PageMetric>($"SELECT * FROM {PageMetric.TableName} WHERE NodeId = @0", pageId);
2525
scope.Complete();
2626

2727
return queryResults;
2828
}
2929

30-
public void AddPageMetric(PageMetric pageMetric)
30+
public async Task AddPageMetric(PageMetric pageMetric)
3131
{
3232
using var scope = _scopeProvider.CreateScope();
33-
scope.Database.Insert(pageMetric);
33+
await scope.Database.InsertAsync(pageMetric);
3434
scope.Complete();
3535
}
3636
}

src/Umbraco.Community.Sustainability/Services/SustainabilityService.cs

Lines changed: 36 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Reflection;
12
using System.Text.Json;
23
using Microsoft.Playwright;
34
using Umbraco.Community.Sustainability.Models;
@@ -21,40 +22,50 @@ public async Task<SustainabilityResponse> GetSustainabilityData(string url)
2122
var page = await context.NewPageAsync();
2223
await page.GotoAsync(url);
2324

24-
// Add our script to report data
25-
await page.AddScriptTagAsync(new PageAddScriptTagOptions()
25+
string? buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
26+
string? fullPath = Path.Combine(buildDir, "wwwroot\\Umbraco.Community.Sustainability\\js\\resource-checker.js");
27+
28+
bool fileExists = File.Exists(fullPath);
29+
30+
if (fileExists)
2631
{
27-
Path = "./App_Plugins/Umbraco.Community.Sustainability/js/resource-checker.js",
28-
Type = "module"
29-
});
32+
// Add our script to report data
33+
await page.AddScriptTagAsync(new PageAddScriptTagOptions()
34+
{
35+
Path = fullPath,
36+
Type = "module"
37+
});
3038

31-
// Retrieve data from page
32-
var data = await page.GetByTestId("sustainabilityData").TextContentAsync();
33-
var sustainabilityData = JsonSerializer.Deserialize<SustainabilityData>(data);
39+
// Retrieve data from page
40+
var data = await page.GetByTestId("sustainabilityData").TextContentAsync();
41+
var sustainabilityData = JsonSerializer.Deserialize<SustainabilityData>(data);
3442

35-
var resourceGroups = new List<ExternalResourceGroup>();
43+
var resourceGroups = new List<ExternalResourceGroup>();
3644

37-
var scripts = GetExternalResourceGroup(ResourceGroupType.Scripts, sustainabilityData.resources);
38-
resourceGroups.Add(scripts);
45+
var scripts = GetExternalResourceGroup(ResourceGroupType.Scripts, sustainabilityData.resources);
46+
resourceGroups.Add(scripts);
3947

40-
var images = GetExternalResourceGroup(ResourceGroupType.Images, sustainabilityData.resources);
41-
resourceGroups.Add(images);
48+
var images = GetExternalResourceGroup(ResourceGroupType.Images, sustainabilityData.resources);
49+
resourceGroups.Add(images);
4250

43-
var styles = GetExternalResourceGroup(ResourceGroupType.Styles, sustainabilityData.resources);
44-
resourceGroups.Add(styles);
51+
var styles = GetExternalResourceGroup(ResourceGroupType.Styles, sustainabilityData.resources);
52+
resourceGroups.Add(styles);
4553

46-
var other = GetExternalResourceGroup(ResourceGroupType.Other, sustainabilityData.resources);
47-
resourceGroups.Add(other);
54+
var other = GetExternalResourceGroup(ResourceGroupType.Other, sustainabilityData.resources);
55+
resourceGroups.Add(other);
4856

49-
await browser.CloseAsync();
57+
await browser.CloseAsync();
5058

51-
return new SustainabilityResponse()
52-
{
53-
TotalSize = sustainabilityData.pageWeight,
54-
TotalEmissions = sustainabilityData.emissions.co2,
55-
CarbonRating = sustainabilityData.carbonRating,
56-
ResourceGroups = resourceGroups
57-
};
59+
return new SustainabilityResponse()
60+
{
61+
TotalSize = sustainabilityData.pageWeight,
62+
TotalEmissions = sustainabilityData.emissions.co2,
63+
CarbonRating = sustainabilityData.carbonRating,
64+
ResourceGroups = resourceGroups
65+
};
66+
}
67+
68+
return default;
5869
}
5970

6071
private ExternalResourceGroup GetExternalResourceGroup(ResourceGroupType groupType, IList<Resource> resources)

src/Umbraco.Community.Sustainability/Umbraco.Community.Sustainability.csproj

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project Sdk="Microsoft.NET.Sdk.Razor">
22
<PropertyGroup>
3-
<TargetFramework>net6.0</TargetFramework>
3+
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
44
<ImplicitUsings>enable</ImplicitUsings>
55
<Nullable>enable</Nullable>
66
<StaticWebAssetBasePath>App_Plugins</StaticWebAssetBasePath>
@@ -12,7 +12,8 @@
1212
<PackageTags>umbraco;umbraco-marketplace</PackageTags>
1313
<RootNamespace>Umbraco.Community.Sustainability</RootNamespace>
1414
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
15-
<Version>0.1.0</Version>
15+
<VersionPrefix>0.1.0</VersionPrefix>
16+
<VersionSuffix>alpha</VersionSuffix>
1617
<Authors>Umbraco Sustainability Community Team</Authors>
1718
<Copyright>$([System.DateTime]::UtcNow.ToString(`yyyy`)) © Umbraco Sustainability Community Team</Copyright>
1819
<PackageProjectUrl>https://github.com/rickbutterfield/Umbraco.Community.Sustainability</PackageProjectUrl>
@@ -24,8 +25,21 @@
2425

2526
<ItemGroup>
2627
<PackageReference Include="Microsoft.Playwright" Version="1.40.0" />
27-
<PackageReference Include="Umbraco.Cms.Web.Website" Version="10.0.0" />
28-
<PackageReference Include="Umbraco.Cms.Web.BackOffice" Version="10.0.0" />
28+
</ItemGroup>
29+
30+
<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
31+
<PackageReference Include="Umbraco.Cms.Web.Website" Version="[10.0.0, 11.0.0)" />
32+
<PackageReference Include="Umbraco.Cms.Web.BackOffice" Version="[10.0.0, 11.0.0)" />
33+
</ItemGroup>
34+
35+
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
36+
<PackageReference Include="Umbraco.Cms.Web.Website" Version="[11.0.0, 13.0.0)" />
37+
<PackageReference Include="Umbraco.Cms.Web.BackOffice" Version="[11.0.0, 13.0.0)" />
38+
</ItemGroup>
39+
40+
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
41+
<PackageReference Include="Umbraco.Cms.Web.Website" Version="[13.0.0, 14.0.0)" />
42+
<PackageReference Include="Umbraco.Cms.Web.BackOffice" Version="[13.0.0, 14.0.0)" />
2943
</ItemGroup>
3044

3145
<ItemGroup>
@@ -35,4 +49,10 @@
3549
</None>
3650
</ItemGroup>
3751

52+
<ItemGroup>
53+
<Content Update="wwwroot\Umbraco.Community.Sustainability\js\resource-checker.js">
54+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
55+
</Content>
56+
</ItemGroup>
57+
3858
</Project>
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { co2, hosting } from 'https://cdn.skypack.dev/@tgwf/co2';
2+
3+
scrollPage();
4+
5+
export function scrollPage() {
6+
window.scrollTo({
7+
top: document.body.scrollHeight,
8+
behavior: 'smooth'
9+
});
10+
11+
setTimeout(reportEmissions, 2000);
12+
}
13+
14+
export async function reportEmissions() {
15+
const emissionsData = await getEmissionsData();
16+
17+
const emissionsDiv = document.createElement("div");
18+
emissionsDiv.setAttribute("data-testid", "sustainabilityData");
19+
emissionsDiv.innerHTML = JSON.stringify(emissionsData);
20+
21+
document.body.appendChild(emissionsDiv);
22+
}
23+
24+
export async function getEmissionsData() {
25+
const resources = getResources();
26+
const bytesSent = getTransferSize(resources);
27+
const hostCheck = await hosting.check(window.location.hostname);
28+
29+
const co2Emission = new co2({ model: "swd" });
30+
const emissions = co2Emission.perVisitTrace(bytesSent, hostCheck);
31+
32+
return {
33+
pageWeight: bytesSent,
34+
carbonRating: calculateGrade(emissions.co2),
35+
emissions: emissions,
36+
resources: resources
37+
};
38+
}
39+
40+
export function getResources() {
41+
return window.performance.getEntriesByType("resource");
42+
}
43+
44+
export function filterResourceByType(resources, entryType) {
45+
return resources.filter(
46+
(entry) => entry.initiatorType === entryType,
47+
);
48+
}
49+
50+
export function getTransferSize(resources) {
51+
let bytesSent = 0;
52+
resources.forEach((entry) => {
53+
bytesSent += entry.transferSize;
54+
});
55+
56+
return bytesSent;
57+
}
58+
59+
export function calculateGrade(score) {
60+
// grade using swd digital carbon ratings
61+
// https://sustainablewebdesign.org/digital-carbon-ratings/
62+
if (score < 0.095) {
63+
return 'A+';
64+
} else if (score < 0.186) {
65+
return 'A';
66+
} else if (score < 0.341) {
67+
return 'B';
68+
} else if (score < 0.493) {
69+
return 'C';
70+
} else if (score < 0.656) {
71+
return 'D';
72+
} else if (score < 0.846) {
73+
return 'E';
74+
} else {
75+
return 'F';
76+
}
77+
}

src/Umbraco.Community.Sustainability/wwwroot/Umbraco.Community.Sustainability/js/sustainability.resource.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33

44
function sustainabilityResource($http, umbRequestHelper) {
55

6-
let apiUrl = "/umbraco/api/Sustainability/";
6+
let apiUrl = "/umbraco/backoffice/api/Sustainability/";
7+
78
let resource = {
89
getData: getData,
910
checkPage: checkPage,

src/Umbraco.Community.Sustainability/wwwroot/Umbraco.Community.Sustainability/views/sustainability-content-app.html

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@
1515
</umb-box-content>
1616
</umb-box>
1717
<umb-box ng-repeat="group in sustainabilityData.resourceGroups" ng-if="!loading">
18-
<umb-box-header title="{{group.name}}" description="Total size: {{(group.totalSize / 1024).toFixed(2)}}kb"></umb-box-header>
18+
<umb-box-header title="{{group.name}}" description="Total size: {{(group.totalSize / 1024).toFixed(2)}}KB"></umb-box-header>
1919
<umb-box-content>
2020
<ul>
2121
<li ng-repeat="resource in group.resources">
22-
{{resource.url}} ({{(resource.size / 1024).toFixed(2)}}kb)
22+
{{resource.url}} ({{(resource.size / 1024).toFixed(2)}}KB)
2323
</li>
2424
</ul>
2525
</umb-box-content>
@@ -43,7 +43,7 @@
4343
<div class="umb-box-row">
4444
<umb-box>
4545
<umb-box-header title="Page size"></umb-box-header>
46-
<umb-box-content>{{(sustainabilityData.totalSize / 1024).toFixed(2)}}kb</umb-box-content>
46+
<umb-box-content>{{(sustainabilityData.totalSize / 1024).toFixed(2)}}KB</umb-box-content>
4747
</umb-box>
4848
<umb-box>
4949
<umb-box-header title="CO₂ per page view"></umb-box-header>

0 commit comments

Comments
 (0)