Kavita/API/Services/Tasks/SiteThemeService.cs
Joseph Milazzo 2723a6cd10
Book Reader Redesign with e-ink focus (#1246)
* Refactored the drawer into offcanvas component. Had to write some hacks to emulate how bootstrap's javascript implementation works as ngBootstrap doesn't have a component yet.

* Cleaned up some of the code

* Rewrote drawer to align it with the new design

* First pass, refactored table of content into it's own component

* Refactored all of the settings logic into a separate component. Everything is broken.

* More settings on on reactive form

* More code cleanup on settings

* Misc fixes around the drawer code. Fixed a bug where range sliders were inheriting background color of normal text inputs

* Fixed dark mode with book reader.

We now clear the theme from the main app so book reader is self-contained. Styles for dark mode are injected into the reading-section. Styles that were previously in scss are now only for the actual menu system.

* Cleaned up drawer styling on header

* Removed an ngIf statement for click to paginate

* Tweaked the accent style to have smaller font size and adjusted style on light mode. Cleaned up some clearTimeout code in a further effort to streamline codebase.

* Refactored Dark mode into a basic theme. Currently styles are hardcoded.

* Patched book theme in from themes branch

* Patched in the backend for Book Theme (not tested yet)

* Fixed a bug in seeding code for book themes. Started integration of themes into the reader settings

* Everything except managing themes is working. Themes are a bit shakey, having second thoughts if we should have them or not.

* Reverted the ability to do custom user book themes. Code is stable with system themes.

* Stablize the Styles (#1128)

* Fixed a bug where adding multiple series to reading list would throw an error on UI, but it was successful.

* When a series has a reading list, we now show the connection on Series detail.

* Removed all baseurl code from UI and not-connected component since we no longer use it.

* Fixed tag badges not showing a border. Added last read time to the series detail page

* Fixed up error interceptor to remove no-connection code

* Changed implementation for series detail. Book libraries will never send chapters back. Volume 0 volumes will not be sent in volumes ever. Fixed up more renaming logic on books to send more accurate representations to the UI.

* Cleaned up the selected tab and tab display logic

* Fixed a bad where statement in reading lists for series

* Fixed up tab logic again

* Fixed a small margin on search backdrop

* Made badge expander button smaller to align with badges

* Fixed a few UIs due to .form-group and .form-row being removed

* Updated Theme component page to help with style testing

* Added more components to theme tester

* Cleaned up some styling

* Fixed opacity on search item hover

* Bump versions by dotnet-bump-version.

* Tweaked the accordion styles for light mode

* Set dark book theme as default. Refactored resetSettings to be much cleaner

* Started the refactor to allow book themes to affect global css variables

* Fixed some issues with my css variable declarations

* Fixed a close model state update

* Lots of work, but dark mode on the book reader is basically done. We have to code the themes much like the site themes

* Some black theme enhancements

* Started working on column layout in book reader.

* Cleaned up the CSS on Reader Settings

* Hooked up reading direction

* Got column and double column layout working

* Implemented some basic virtual paging and hooked in book color theme and layout mode into user preferences.

* Migration wrote, can edit page layout and color theme on book reader. Removed book dark mode since no longer needed.

Fixed a bug on login/register forms where when input is focused, text is white and not black.

* When loading book reader, apply column layout.

* Lots of work around 2 column layout, working on images not splitting. Still not working, committing so i can merge develop in and validate code with new manga reader.

* Fixed images being split into 2 BUT regression on each page boundary, total reading height is smaller and smaller

* Fixed some rendering bugs where toggling column layouts would shrink images on screen constantly.

Fixed a bug where bottom bar wouldn't render on column layout in some conditions (this might need to be reworked)

* Started progress on progress work

* Updated .NET to 6.0.4

* Fixed a bug where DataContextModelSnapshot was being removed on build thus new migrations were broken.

* Tweaked the code around progress saving so that we don't loose track of last scroll element on page load

* Trying to restore progress, but stuck

* Extra merge stuff

* Fixed a bug where volumes that are a range fail to generate series detail

* No gutters on whole app. Book reader backend now applies the image class automatically at the backend.

* Added wiki documentation into invite user flow and register admin user to help users understand email isn't required and they can host their own service.

* Removed bottom padding

* Refactored the document height to be set and removed on nav service, so the book reader and manga reader aren't broken.

* Fixed the height of the action bar to simplify logic and keep the code cleaner. Refactored book service image scoping to be much more streamlined and efficient

* Fixed the height of action bar to 62px and adjusted code to use the hardcoded px. (code commented)

* Removed commented out code from fixed action bar height

* Progress restoration seems to be working

* Code cleanup

* Ensure the bottom action bar is at the bottom of the viewport on small pages

* Fixed book fonts not setting properly and added OpenDyslexic font.

* Fixed up some font issues

* Updated drawer so all sections are open by default

* Switched some LINQ to use MinBy

* When navigating between pages and column layout, adjust the shift for the user.

* Removed some debug code

* Blacklist .qpkg folders and don't scan Recently-Snapshot or recycle folders.

* Renamed the scale width to be scoped to kavita to avoid conflicts.

* Refactored ngx-sliders out to use normal range instead. Changed up the preferences to separate image and book settinngs into own accordion.

* updated user preferences for new migration options (not committed yet)

* Removed some debug code

* Remove console.logs

* Migration committed, let's release this to users.

* A lot of crazy code just to ensure that when you close drawer the toggle reflectst that state.
2022-05-08 17:52:15 -07:00

169 lines
6.4 KiB
C#

using System;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.Entities;
using API.Entities.Enums.Theme;
using API.SignalR;
using Kavita.Common;
namespace API.Services.Tasks;
public interface IThemeService
{
Task<string> GetContent(int themeId);
Task Scan();
Task UpdateDefault(int themeId);
}
public class ThemeService : IThemeService
{
private readonly IDirectoryService _directoryService;
private readonly IUnitOfWork _unitOfWork;
private readonly IEventHub _eventHub;
public ThemeService(IDirectoryService directoryService, IUnitOfWork unitOfWork, IEventHub eventHub)
{
_directoryService = directoryService;
_unitOfWork = unitOfWork;
_eventHub = eventHub;
}
/// <summary>
/// Given a themeId, return the content inside that file
/// </summary>
/// <param name="themeId"></param>
/// <returns></returns>
public async Task<string> GetContent(int themeId)
{
var theme = await _unitOfWork.SiteThemeRepository.GetThemeDto(themeId);
if (theme == null) throw new KavitaException("Theme file missing or invalid");
var themeFile = _directoryService.FileSystem.Path.Join(_directoryService.SiteThemeDirectory, theme.FileName);
if (string.IsNullOrEmpty(themeFile) || !_directoryService.FileSystem.File.Exists(themeFile))
throw new KavitaException("Theme file missing or invalid");
return await _directoryService.FileSystem.File.ReadAllTextAsync(themeFile);
}
/// <summary>
/// Scans the site theme directory for custom css files and updates what the system has on store
/// </summary>
public async Task Scan()
{
_directoryService.ExistOrCreate(_directoryService.SiteThemeDirectory);
var reservedNames = Seed.DefaultThemes.Select(t => t.NormalizedName).ToList();
var themeFiles = _directoryService
.GetFilesWithExtension(Parser.Parser.NormalizePath(_directoryService.SiteThemeDirectory), @"\.css")
.Where(name => !reservedNames.Contains(Parser.Parser.Normalize(name))).ToList();
var allThemes = (await _unitOfWork.SiteThemeRepository.GetThemes()).ToList();
// First remove any files from allThemes that are User Defined and not on disk
var userThemes = allThemes.Where(t => t.Provider == ThemeProvider.User).ToList();
foreach (var userTheme in userThemes)
{
var filepath = Parser.Parser.NormalizePath(
_directoryService.FileSystem.Path.Join(_directoryService.SiteThemeDirectory, userTheme.FileName));
if (_directoryService.FileSystem.File.Exists(filepath)) continue;
// I need to do the removal different. I need to update all user preferences to use DefaultTheme
allThemes.Remove(userTheme);
await RemoveTheme(userTheme);
}
// Add new custom themes
var allThemeNames = allThemes.Select(t => t.NormalizedName).ToList();
foreach (var themeFile in themeFiles)
{
var themeName =
Parser.Parser.Normalize(_directoryService.FileSystem.Path.GetFileNameWithoutExtension(themeFile));
if (allThemeNames.Contains(themeName)) continue;
_unitOfWork.SiteThemeRepository.Add(new SiteTheme()
{
Name = _directoryService.FileSystem.Path.GetFileNameWithoutExtension(themeFile),
NormalizedName = themeName,
FileName = _directoryService.FileSystem.Path.GetFileName(themeFile),
Provider = ThemeProvider.User,
IsDefault = false,
});
await _eventHub.SendMessageAsync(MessageFactory.NotificationProgress,
MessageFactory.SiteThemeProgressEvent(_directoryService.FileSystem.Path.GetFileName(themeFile), themeName,
ProgressEventType.Updated));
}
if (_unitOfWork.HasChanges())
{
await _unitOfWork.CommitAsync();
}
// if there are no default themes, reselect Dark as default
var postSaveThemes = (await _unitOfWork.SiteThemeRepository.GetThemes()).ToList();
if (!postSaveThemes.Any(t => t.IsDefault))
{
var defaultThemeName = Seed.DefaultThemes.Single(t => t.IsDefault).NormalizedName;
var theme = postSaveThemes.SingleOrDefault(t => t.NormalizedName == defaultThemeName);
if (theme != null)
{
theme.IsDefault = true;
_unitOfWork.SiteThemeRepository.Update(theme);
await _unitOfWork.CommitAsync();
}
}
await _eventHub.SendMessageAsync(MessageFactory.NotificationProgress,
MessageFactory.SiteThemeProgressEvent("", "", ProgressEventType.Ended));
}
/// <summary>
/// Removes the theme and any references to it from Pref and sets them to the default at the time.
/// This commits to DB.
/// </summary>
/// <param name="theme"></param>
private async Task RemoveTheme(SiteTheme theme)
{
var prefs = await _unitOfWork.UserRepository.GetAllPreferencesByThemeAsync(theme.Id);
var defaultTheme = await _unitOfWork.SiteThemeRepository.GetDefaultTheme();
foreach (var pref in prefs)
{
pref.Theme = defaultTheme;
_unitOfWork.UserRepository.Update(pref);
}
_unitOfWork.SiteThemeRepository.Remove(theme);
await _unitOfWork.CommitAsync();
}
/// <summary>
/// Updates the themeId to the default theme, all others are marked as non-default
/// </summary>
/// <param name="themeId"></param>
/// <returns></returns>
/// <exception cref="KavitaException">If theme does not exist</exception>
public async Task UpdateDefault(int themeId)
{
try
{
var theme = await _unitOfWork.SiteThemeRepository.GetThemeDto(themeId);
if (theme == null) throw new KavitaException("Theme file missing or invalid");
foreach (var siteTheme in await _unitOfWork.SiteThemeRepository.GetThemes())
{
siteTheme.IsDefault = (siteTheme.Id == themeId);
_unitOfWork.SiteThemeRepository.Update(siteTheme);
}
if (!_unitOfWork.HasChanges()) return;
await _unitOfWork.CommitAsync();
}
catch (Exception)
{
await _unitOfWork.RollbackAsync();
throw;
}
}
}