/
FrontEndFunctions.cs
139 lines (122 loc) · 4.7 KB
/
FrontEndFunctions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
using AzureLocationTracking.Functions.Services;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Text;
namespace AzureLocationTracking.Functions;
public class FrontEndFunctions
{
private static string CachedIndexHtml;
private static DateTime CachedIndexHtmlLastWrite;
private readonly string _staticFilesDirectory;
private readonly AzureMapsService _azureMapsService;
public FrontEndFunctions(
AzureMapsService azureMapsService)
{
var localRootDirectory = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
var azureRootDirectory = $"{Environment.GetEnvironmentVariable("HOME")}/site/wwwroot";
_staticFilesDirectory = localRootDirectory != null
? Path.Combine(localRootDirectory, @"..\..\..\", "static")
: Path.Combine(azureRootDirectory, "static");
_azureMapsService = azureMapsService;
}
[Function(nameof(GetIndex))]
public async Task<HttpResponseData> GetIndex(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/")] HttpRequestData req)
{
var lastIndexWrite = File.GetLastWriteTime(Path.Combine(_staticFilesDirectory, "index.html"));
if (CachedIndexHtml == null || lastIndexWrite > CachedIndexHtmlLastWrite)
{
var indexTemplate = await File.ReadAllTextAsync(Path.Combine(_staticFilesDirectory, "index.html"));
CachedIndexHtml = indexTemplate;
CachedIndexHtmlLastWrite = lastIndexWrite;
}
var res = req.CreateResponse(HttpStatusCode.OK);
res.Headers.Add("Content-Type", "text/html; charset=utf-8");
await res.WriteStringAsync(CachedIndexHtml, Encoding.UTF8);
return res;
}
[Function(nameof(GetStaticFile))]
public async Task<HttpResponseData> GetStaticFile(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "static/{**filePath}")] HttpRequestData req,
string filePath,
FunctionContext functionContext)
{
var logger = functionContext.GetLogger(nameof(GetStaticFile));
var mappedFilePath = GetStaticFilePath(filePath);
try
{
var res = req.CreateResponse(HttpStatusCode.OK);
res.Headers.Add("Content-Type", GetContentType(mappedFilePath));
await res.WriteBytesAsync(await File.ReadAllBytesAsync(mappedFilePath));
return res;
}
catch (FileNotFoundException)
{
logger.LogWarning("Unable to find static file at path {filePath}", filePath);
return req.CreateResponse(HttpStatusCode.NotFound);
}
}
private string GetStaticFilePath(string filePath)
{
var fullPath = Path.GetFullPath(Path.Combine(_staticFilesDirectory, filePath));
if (!IsInDirectory(_staticFilesDirectory, fullPath))
{
throw new ArgumentException("Invalid path");
}
var isDirectory = Directory.Exists(fullPath);
if (isDirectory)
{
throw new ArgumentException("Invalid path");
}
return fullPath;
}
private static bool IsInDirectory(string parentPath, string childPath)
{
var parent = new DirectoryInfo(parentPath);
var child = new DirectoryInfo(childPath);
var dir = child;
do
{
if (dir.FullName == parent.FullName)
{
return true;
}
dir = dir.Parent;
} while (dir != null);
return false;
}
private string GetContentType(string filePath)
{
var ext = Path.GetExtension(filePath).ToLowerInvariant();
return ext switch
{
".css" => "text/css",
".js" => "application/javascript",
".png" => "image/png",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".ico" => "image/x-icon",
".json" => "application/json",
".woff" => "font/woff",
".woff2" => "font/woff2",
".ttf" => "font/ttf",
".eot" => "font/eot",
".otf" => "font/otf",
".txt" => "text/plain",
_ => "application/octet-stream",
};
}
[Function(nameof(GetMapsAccessToken))]
public async Task<HttpResponseData> GetMapsAccessToken(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "api/mapsToken")] HttpRequestData req)
{
var res = req.CreateResponse(HttpStatusCode.OK);
var token = await _azureMapsService.GetRenderTokenAsync();
await res.WriteStringAsync(token);
return res;
}
}