Skip to content

Commit

Permalink
Started work on the backend
Browse files Browse the repository at this point in the history
  • Loading branch information
majora2007 committed Jul 27, 2023
1 parent 3ec6c52 commit fc605e9
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 13 deletions.
28 changes: 28 additions & 0 deletions API/Controllers/LocaleController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.Services;
using Microsoft.AspNetCore.Mvc;

namespace API.Controllers;

public class LocaleController : BaseApiController
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILocalizationService _localizationService;
private static readonly IReadOnlyList<string> AllLocales = new List<string>() { "en" };

public LocaleController(IUnitOfWork unitOfWork, ILocalizationService localizationService)
{
_unitOfWork = unitOfWork;
_localizationService = localizationService;
}

[HttpGet]
public ActionResult<IEnumerable<string>> GetAllLocales()
{
return Ok(AllLocales);
}
}
3 changes: 3 additions & 0 deletions API/Data/DataContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<AppUserPreferences>()
.Property(b => b.BookReaderWritingStyle)
.HasDefaultValue(WritingStyle.Horizontal);
builder.Entity<AppUserPreferences>()
.Property(b => b.Locale)
.HasDefaultValue("en");

builder.Entity<Library>()
.Property(b => b.AllowScrobbling)
Expand Down
4 changes: 4 additions & 0 deletions API/Entities/AppUserPreferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ public class AppUserPreferences
/// UI Site Global Setting: Should series reviews be shared with all users in the server
/// </summary>
public bool ShareReviews { get; set; } = false;
/// <summary>
/// UI Site Global Setting: The language locale that should be used for the user
/// </summary>
public string Locale { get; set; }

public AppUser AppUser { get; set; } = null!;
public int AppUserId { get; set; }
Expand Down
2 changes: 2 additions & 0 deletions API/Extensions/ApplicationServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ public static void AddApplicationServices(this IServiceCollection services, ICon
services.AddScoped<IPresenceTracker, PresenceTracker>();
services.AddScoped<IImageService, ImageService>();

services.AddScoped<ILocalizationService, LocalizationService>();


services.AddScoped<IScrobblingService, ScrobblingService>();
services.AddScoped<ILicenseService, LicenseService>();
Expand Down
56 changes: 43 additions & 13 deletions API/Services/LocalizationService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Hosting;

namespace API.Services;
Expand All @@ -8,19 +11,21 @@ namespace API.Services;

public interface ILocalizationService
{
void LoadLanguage(string languageCode);
//string Get(string key);
Task<Dictionary<string, string>> LoadLanguage(string languageCode);
Task<string> Get(string locale, string key, params object[] args);
}

public class LocalizationService : ILocalizationService
{
private readonly IDirectoryService _directoryService;
private readonly IMemoryCache _cache;
private readonly string _localizationDirectory;
private dynamic? _languageLocale;

public LocalizationService(IDirectoryService directoryService, IHostEnvironment environment)

public LocalizationService(IDirectoryService directoryService, IHostEnvironment environment, IMemoryCache cache)
{
_directoryService = directoryService;
_cache = cache;
if (environment.IsDevelopment())
{
_localizationDirectory = directoryService.FileSystem.Path.Join(
Expand All @@ -40,20 +45,45 @@ public LocalizationService(IDirectoryService directoryService, IHostEnvironment
/// </summary>
/// <param name="languageCode"></param>
/// <returns></returns>
public void LoadLanguage(string languageCode)
public async Task<Dictionary<string, string>> LoadLanguage(string languageCode)
{
var languageFile = _directoryService.FileSystem.Path.Join(_localizationDirectory, languageCode + ".json");
if (!_directoryService.FileSystem.FileInfo.New(languageFile).Exists)
throw new ArgumentException($"Language {languageCode} does not exist");

var json = _directoryService.FileSystem.File.ReadAllText(languageFile);
_languageLocale = JsonSerializer.Deserialize<dynamic>(json);
var json = await _directoryService.FileSystem.File.ReadAllTextAsync(languageFile);
return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}

// public string Get(string key)
// {
// if (_languageLocale == null) return key;
// return _languageLocale.
//
// }
public async Task<string> Get(string locale, string key, params object[] args)
{
// Check if the translation for the given locale is cached
if (!_cache.TryGetValue($"{locale}_{key}", out string translatedString))
{
// Load the locale JSON file
var translationData = await LoadLanguage(locale);

// Find the translation for the given key
if (translationData.TryGetValue(key, out string value))
{
translatedString = value;

// Cache the translation for subsequent requests
_cache.Set($"{locale}_{key}", translatedString, TimeSpan.FromMinutes(15)); // Cache for 15 minutes
}
else
{
// If the key is not found, use the key as the translated string
translatedString = key;
}
}

// Format the translated string with arguments
if (args.Length > 0)
{
translatedString = string.Format(translatedString, args);
}

return translatedString;
}
}

0 comments on commit fc605e9

Please sign in to comment.