Repository navigation
Expand file tree
/
Copy pathImagesHandler.cs
More file actions
84 lines (69 loc) · 2.55 KB
/
Copy pathImagesHandler.cs
File metadata and controls
84 lines (69 loc) · 2.55 KB
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
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ServiceStack.Auth;
using ServiceStack.Host.Handlers;
using ServiceStack.IO;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack;
/// <summary>
/// Handler to manage in memory collection of images
/// </summary>
public class ImagesHandler : HttpAsyncTaskHandler
{
public string Path { get; }
public Dictionary<string, StaticContent> ImageContents { get; } = new();
public StaticContent Fallback { get; }
public ImagesHandler(string path, StaticContent fallback)
{
Path = path ?? throw new ArgumentNullException(nameof(path));
Fallback = fallback ?? throw new ArgumentNullException(nameof(fallback));
}
public virtual string? RewriteImageUri(string imageUri)
{
var content = StaticContent.CreateFromDataUri(imageUri);
if (content == null)
return null;
var file = imageUri.ToMd5Hash() + '.' + MimeTypes.GetExtension(content.MimeType);
Save(file, content);
return Path.CombineWith(file);
}
public virtual void Save(string path, StaticContent content) =>
ImageContents[path] = content;
public virtual StaticContent? Get(string path) =>
ImageContents.TryGetValue(path, out var imageUri) ? imageUri : null;
public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
{
var path = httpReq.PathInfo.RightPart(Path).TrimStart('/');
var content = Get(path) ?? Fallback;
httpRes.ContentType = content.MimeType;
await httpRes.OutputStream.WriteAsync(content.Data).ConfigAwait();
}
}
/// <summary>
/// Handler to manage persistent images
/// </summary>
public class PersistentImagesHandler : ImagesHandler
{
public IVirtualFiles VirtualFiles { get; }
public string DirPath { get; }
public PersistentImagesHandler(string path, StaticContent fallback, IVirtualFiles virtualFiles, string dirPath)
: base(path, fallback)
{
VirtualFiles = virtualFiles;
DirPath = dirPath;
}
public override StaticContent? Get(string path)
{
var file = VirtualFiles.GetFile(DirPath.CombineWith(path));
if (file == null)
return null;
return new StaticContent(file.GetBytesContentsAsMemory(), MimeTypes.GetExtension(file.Extension));
}
public override void Save(string path, StaticContent content)
{
VirtualFiles.WriteFile(DirPath.CombineWith(path), content.Data);
}
}