summaryrefslogtreecommitdiff
path: root/Services/MediaService.cs
blob: 460e0c7127a2a6ea7ff3c3fd94543e86ca87e369 (plain)
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
using Microsoft.EntityFrameworkCore;
using MimeDetective;
using MimeDetective.Definitions;
using System.Security.Cryptography;

namespace HyperBooru.Services;

public interface IMediaService {
    public void SetDescription(
        Media media,
        string? shortDescription,
        string? longDescription);

    public void SetIngest(Media media, bool ingest);

    public Media Create(
        Stream fileData,
        string fileName,
        string? checksum = null,
        DateTime? lastAccessTime = null,
        DateTime? lastWriteTime = null,
        DateTime? createTime = null);

    public void Delete(Guid media);
    public void Delete(Media media);
    public string GetPath(Media media);
    public string GetPath(Media media, int width, int height);

}

public class MediaService : IMediaService {
    private IDbContextFactory<HBContext> dbFactory;
    private IConfigService               config;

    private ContentInspector inspector;

    public MediaService(IDbContextFactory<HBContext> dbFactory,
        IConfigService config) {

        this.dbFactory = dbFactory;
        this.config    = config;

        ContentInspectorBuilder inspectorBuilder = new() {
            Definitions =
                Default.FileTypes.Images.All()
                .Union(Default.FileTypes.Video.All())
                .ToList()
        };

        inspector = inspectorBuilder.Build();
    }

    public void SetIngest(Media media, bool ingest) {
        using var db = dbFactory.CreateDbContext();
        media = db.Media
            .Include(m => m.Tags)
            .ThenInclude(t => t.TagDefinition)
            .First(m => m.Guid == media.Guid);
        var ingestTag = db.TagDefinitions
            .First(td => td.Guid == HBContext.IngestTag);

        if(ingest) {
            if(!media.Tags.Select(t => t.TagDefinition.Guid).Contains(HBContext.IngestTag))
                media.Tags.Add(new(ingestTag));
        } else {
            media.Tags.RemoveAll(t => t.TagDefinition.Guid == HBContext.IngestTag);
        }

        db.SaveChanges();
    }

    public void SetDescription(
        Media media,
        string? shortDescription,
        string? longDescription) {

        using var db = dbFactory.CreateDbContext();
        var m = db.Media.First(m => m.Guid == media.Guid);

        shortDescription = shortDescription?.Trim();
        longDescription  = longDescription?.Trim();

        if(string.IsNullOrEmpty(shortDescription))
            shortDescription = null;
        if(string.IsNullOrEmpty(longDescription))
            longDescription = null;

        m.ShortDescription = shortDescription;
        m.LongDescription  = longDescription;

        db.SaveChanges();
    }

    public Media Create(
        Stream fileData,
        string fileName,
        string? checksum = null,
        DateTime? lastAccessTime = null,
        DateTime? lastWriteTime = null,
        DateTime? createTime = null) {

        using var db = dbFactory.CreateDbContext();
        using var transaction = db.Database.BeginTransaction();

        if(fileData.Length == 0)
            throw new MediaCreateException("File is empty");

        // Calculate the checksum using the in-memory file contents
        var hash = BitConverter
            .ToString(MD5.Create().ComputeHash(fileData))
            .Replace("-", "")
            .ToLower();

        if(checksum is not null && hash != checksum.ToLower())
            throw new MediaCreateException("Checksum does not match");

        var fileRecord = new UploadedFile() {
            Filename         = fileName,
            OriginalChecksum = hash,
            UploadTime       = DateTime.UtcNow,
            LastAccessTime   = lastAccessTime,
            LastWriteTime    = lastWriteTime,
            CreateTime       = createTime
        };

        fileData.Seek(0, SeekOrigin.Begin);
        var defs = inspector.Inspect(fileData);

        var mime = defs.ByMimeType().FirstOrDefault()?.MimeType;
        if(mime is null)
            throw new MediaCreateException("Unsupported file type");

        var media = db.Media
            .FirstOrDefault(m => m.Checksum == hash);

        if(media is null) {
            var ingestTagDef = db.TagDefinitions
                .First(td => td.Guid == HBContext.IngestTag);

            media = new() {
                UploadedFiles = new() {
                    fileRecord
                },
                Tags = new() {
                    new() { TagDefinition = ingestTagDef }
                }
            };

            using var newFile = System.IO.File.Create(GetPath(media));

            fileData.Seek(0, SeekOrigin.Begin);
            fileData.CopyTo(newFile);
            newFile.Flush();

            db.Media.Add(media);
            db.SaveChanges();
            media.CurrentUploadedFile = fileRecord;
            db.SaveChanges();
        } else {
            media.UploadedFiles.Add(fileRecord);
            db.Update(media);
            db.SaveChanges();
        }

        transaction.Commit();

        return media;
    }

    public void Delete(Guid media) {
        using var db = dbFactory.CreateDbContext();
        var m = db.Media.First(m => m.Guid == media);

        try {
            System.IO.File.Delete(
                Path.Join(
                    config.MediaBasePath,
                    m.Guid.ToString().Substring(0, 2),
                    m.Guid.ToString().Substring(2, 2),
                    m.Guid.ToString()));
        } catch(IOException) {}

        try {
            System.IO.Directory.Delete(
                Path.Join(
                    config.MediaBasePath,
                    m.Guid.ToString().Substring(0, 2),
                    m.Guid.ToString().Substring(2, 2)));
        } catch(IOException) {}

        try {
            System.IO.Directory.Delete(
                Path.Join(
                    config.MediaBasePath,
                    m.Guid.ToString().Substring(0, 2)));
        } catch(IOException) {}

        db.Media.Remove(m);
        db.SaveChanges();
    }

    public void Delete(Media media) =>
        Delete(media.Guid);

    public string GetPath(Media media) {
        var fileInfo = new FileInfo(
            Path.Join(
                config.MediaBasePath,
                media.Guid.ToString().Substring(0, 2),
                media.Guid.ToString().Substring(2, 2),
                media.Guid.ToString()));

        Directory.CreateDirectory(fileInfo.Directory.FullName);
        return fileInfo.FullName;
    }

    public string GetPath(Media media, int width, int height) {
        var fileInfo = new FileInfo(Path.Join(
            config.ThumbnailBasePath,
            media.Guid.ToString().Substring(0, 2),
            media.Guid.ToString().Substring(2, 2),
            $"{media.Guid.ToString()}-{width}-{height}"));

        Directory.CreateDirectory(fileInfo.Directory.FullName);
        return fileInfo.FullName;
    }
}