aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Providers/Books/ComicBookInfo/ComicBookInfoProvider.cs
blob: 787d2ad8787a006164293b2ac75a2c667c617e3f (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
228
229
230
231
232
233
234
235
236
237
238
using System;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions.Json;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Books.ComicBookInfo.Models;
using Microsoft.Extensions.Logging;

namespace MediaBrowser.Providers.Books.ComicBookInfo;

/// <summary>
/// ComicBookInfo provider.
/// </summary>
public class ComicBookInfoProvider : IComicProvider
{
    private readonly ILogger<ComicBookInfoProvider> _logger;
    private readonly IFileSystem _fileSystem;

    /// <summary>
    /// Initializes a new instance of the <see cref="ComicBookInfoProvider"/> class.
    /// </summary>
    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
    /// <param name="logger">Instance of the <see cref="ILogger{ComicBookInfoProvider}"/> interface.</param>
    public ComicBookInfoProvider(IFileSystem fileSystem, ILogger<ComicBookInfoProvider> logger)
    {
        _fileSystem = fileSystem;
        _logger = logger;
    }

    /// <inheritdoc />
    public async ValueTask<MetadataResult<Book>> ReadMetadata(ItemInfo info, IDirectoryService directoryService, CancellationToken cancellationToken)
    {
        var path = GetComicBookFile(info.Path)?.FullName;

        if (path is null)
        {
            _logger.LogError("could not load comic: {Path}", info.Path);
            return new MetadataResult<Book> { HasMetadata = false };
        }

        try
        {
            Stream stream = AsyncFile.OpenRead(path);
            await using (stream.ConfigureAwait(false))
            {
                var archive = await ZipArchive.CreateAsync(stream, ZipArchiveMode.Read, false, null, cancellationToken).ConfigureAwait(false);
                await using (archive.ConfigureAwait(false))
                {
                    if (archive.Comment is null)
                    {
                        _logger.LogInformation("missing ComicBookInfo in archive comment: {Path}", info.Path);
                        return new MetadataResult<Book> { HasMetadata = false };
                    }

                    var comicBookMetadata = JsonSerializer.Deserialize<ComicBookInfoFormat>(archive.Comment, JsonDefaults.Options);
                    if (comicBookMetadata is null)
                    {
                        _logger.LogError("ComicBookInfo deserialization failure: {Path}", info.Path);
                        return new MetadataResult<Book> { HasMetadata = false };
                    }

                    return SaveMetadata(comicBookMetadata);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "failed to load ComicBookInfo metadata: {Path}", info.Path);
            return new MetadataResult<Book> { HasMetadata = false };
        }
    }

    /// <inheritdoc />
    public bool HasItemChanged(BaseItem item)
    {
        var file = GetComicBookFile(item.Path);

        if (file is null)
        {
            return false;
        }

        return file.Exists && _fileSystem.GetLastWriteTimeUtc(file) > item.DateLastSaved;
    }

    private MetadataResult<Book> SaveMetadata(ComicBookInfoFormat comic)
    {
        if (comic.Metadata is null)
        {
            return new MetadataResult<Book> { HasMetadata = false };
        }

        var book = ReadComicBookMetadata(comic.Metadata);

        if (book is null)
        {
            return new MetadataResult<Book> { HasMetadata = false };
        }

        var metadataResult = new MetadataResult<Book> { Item = book, HasMetadata = true };

        if (comic.Metadata.Language is not null)
        {
            metadataResult.ResultLanguage = ReadCultureInfoInto(comic.Metadata.Language);
        }

        if (comic.Metadata.Credits.Count > 0)
        {
            ReadPeopleMetadata(comic.Metadata, metadataResult);
        }

        return metadataResult;
    }

    private FileSystemMetadata? GetComicBookFile(string path)
    {
        var fileInfo = _fileSystem.GetFileSystemInfo(path);

        if (fileInfo.IsDirectory)
        {
            return null;
        }

        // only parse files that are known to have ComicBookInfo metadata
        return fileInfo.Extension.Equals(".cbz", StringComparison.OrdinalIgnoreCase) ? fileInfo : null;
    }

    private static Book? ReadComicBookMetadata(ComicBookInfoMetadata comic)
    {
        var book = new Book();
        var hasFoundMetadata = false;

        hasFoundMetadata |= ReadStringInto(comic.Title, title => book.Name = title);
        hasFoundMetadata |= ReadStringInto(comic.Series, series => book.SeriesName = series);
        hasFoundMetadata |= ReadStringInto(comic.Genre, genre => book.AddGenre(genre));
        hasFoundMetadata |= ReadStringInto(comic.Comments, overview => book.Overview = overview);
        hasFoundMetadata |= ReadStringInto(comic.Publisher, publisher => book.SetStudios([publisher]));

        if (comic.PublicationYear is not null)
        {
            book.ProductionYear = comic.PublicationYear;
            hasFoundMetadata = true;
        }

        if (comic.Issue is not null)
        {
            book.IndexNumber = comic.Issue;
            hasFoundMetadata = true;
        }

        if (comic.Tags.Count > 0)
        {
            book.Tags = comic.Tags.ToArray();
            hasFoundMetadata = true;
        }

        if (comic.PublicationYear is not null && comic.PublicationMonth is not null)
        {
            book.PremiereDate = ReadTwoPartDateInto(comic.PublicationYear.Value, comic.PublicationMonth.Value);
            hasFoundMetadata = true;
        }

        return hasFoundMetadata ? book : null;
    }

    private static void ReadPeopleMetadata(ComicBookInfoMetadata comic, MetadataResult<Book> metadataResult)
    {
        foreach (var person in comic.Credits)
        {
            if (person.Person is null || person.Role is null)
            {
                continue;
            }

            if (person.Person.Contains(',', StringComparison.InvariantCultureIgnoreCase))
            {
                var name = person.Person.Split(',');
                person.Person = name[1].Trim(' ') + " " + name[0].Trim(' ');
            }

            if (!Enum.TryParse(person.Role, out PersonKind personKind))
            {
                personKind = PersonKind.Unknown;
            }

            if (string.Equals("Colorer", person.Role, StringComparison.OrdinalIgnoreCase))
            {
                personKind = PersonKind.Colorist;
            }

            metadataResult.AddPerson(new PersonInfo { Name = person.Person, Type = personKind });
        }
    }

    private static string? ReadCultureInfoInto(string language)
    {
        try
        {
            return CultureInfo.GetCultureInfo(language).DisplayName;
        }
        catch (CultureNotFoundException)
        {
            return null;
        }
    }

    private static bool ReadStringInto(string? data, Action<string> commitResult)
    {
        if (!string.IsNullOrWhiteSpace(data))
        {
            commitResult(data);
            return true;
        }

        return false;
    }

    private static DateTime? ReadTwoPartDateInto(int year, int month)
    {
        try
        {
            // use first day of the month because this format doesn't include a day
            return new DateTime(year, month, 1, 0, 0, 0, DateTimeKind.Unspecified);
        }
        catch (ArgumentOutOfRangeException)
        {
            return null;
        }
    }
}