Reload custom locale when file is modified

Affects issues:
- Close #2311
This commit is contained in:
Aurora Lahtela 2023-09-29 08:28:57 +03:00
parent a1d5e4dc4f
commit 30a8da3c3b
18 changed files with 184 additions and 2 deletions

View File

@ -23,6 +23,8 @@ import com.djrapitops.plan.delivery.webserver.auth.FailReason;
import com.djrapitops.plan.settings.config.PlanConfig;
import com.djrapitops.plan.settings.config.paths.PluginSettings;
import com.djrapitops.plan.settings.locale.lang.*;
import com.djrapitops.plan.settings.upkeep.FileWatcher;
import com.djrapitops.plan.settings.upkeep.WatchedFile;
import com.djrapitops.plan.storage.file.FileResource;
import com.djrapitops.plan.storage.file.PlanFiles;
import com.djrapitops.plan.utilities.logging.ErrorContext;
@ -54,6 +56,7 @@ public class LocaleSystem implements SubSystem {
private final ErrorLogger errorLogger;
private final Locale locale;
private FileWatcher fileWatcher;
@Inject
public LocaleSystem(
@ -123,6 +126,8 @@ public class LocaleSystem implements SubSystem {
if (localeFile.exists()) {
writeNewDefaultLocale(localeFile);
loaded = loadFromFile(localeFile);
fileWatcher = prepareFileWatcher(localeFile);
fileWatcher.start();
} else {
loaded = loadSettingLocale();
}
@ -132,6 +137,20 @@ public class LocaleSystem implements SubSystem {
logger.info("Locale: '" + langCode.getName() + "' by " + langCode.getAuthors());
}
public FileWatcher prepareFileWatcher(File localeFile) {
FileWatcher watcher = new FileWatcher(files.getDataDirectory(), errorLogger);
watcher.addToWatchlist(new WatchedFile(localeFile, this::reloadCustomLocale));
return watcher;
}
private void reloadCustomLocale() {
File localeFile = files.getLocaleFile();
if (localeFile.exists()) {
loadFromFile(localeFile).ifPresent(locale::loadFromAnotherLocale);
logger.info(locale.getString(PluginLang.RELOAD_LOCALE));
}
}
private void writeNewDefaultLocale(File localeFile) {
try {
Locale writing = loadSettingLocale().orElse(locale);
@ -217,7 +236,9 @@ public class LocaleSystem implements SubSystem {
@Override
public void disable() {
// No action necessary on disable.
if (fileWatcher != null) {
fileWatcher.interrupt();
}
}
public Locale getLocale() {

View File

@ -27,6 +27,7 @@ public enum PluginLang implements Lang {
ENABLED_DATABASE("plugin.enable.database", "Enable - Database", "${0}-database connection established."),
API_ADD_RESOURCE_JS("plugin.apiJSAdded", "API - js+", "PageExtension: ${0} added javascript(s) to ${1}, ${2}"),
API_ADD_RESOURCE_CSS("plugin.apiCSSAdded", "API - css+", "PageExtension: ${0} added stylesheet(s) to ${1}, ${2}"),
RELOAD_LOCALE("plugin.localeReloaded", "API - locale reload", "Custom locale.yml was modified so it was reloaded and is now in use."),
ENABLE_NOTIFY_STORING_PRESERVED_SESSIONS("plugin.enable.notify.storeSessions", "Enable - Storing preserved sessions", "Storing sessions that were preserved before previous shutdown."),
ENABLE_NOTIFY_EMPTY_IP("plugin.enable.notify.emptyIP", "Enable - Notify Empty IP", "IP in server.properties is empty & Alternative_IP is not in use. Incorrect links might be given!"),
@ -109,7 +110,7 @@ public enum PluginLang implements Lang {
}
@Override
public String getKey() { return key; }
public String getKey() {return key;}
@Override
public String getDefault() {

View File

@ -880,6 +880,7 @@ plugin:
unknown: "位置"
yes: "是"
yesterday: "'昨天'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "无法检查最新版本号"
checkFailGithub: "无法从 Github/versions.txt 加载版本信息"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Neznámé"
yes: "Ano"
yesterday: "'Včera'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Selhalo zjištění čísla nejnovější verze"
checkFailGithub: "Informace o verzi z Github/versions.txt nemůže být nalezena."

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Unbekannt"
yes: "Ja"
yesterday: "'Gestern'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Überprüfung auf die neuste Versionsnummer fehlgeschlagen."
checkFailGithub: "Versionsinformationen konnten nicht ovn Github/versions.txt gelesen werden."

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Unknown"
yes: "Yes"
yesterday: "'Yesterday'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Failed to check newest version number"
checkFailGithub: "Version information could not be loaded from Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Desconocido"
yes: "Si"
yesterday: "'Ayer'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Error en comprobar el numero de la nueva versión."
checkFailGithub: "La información de la versión no se ha podido cargar desde Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Tuntematon"
yes: "Kyllä"
yesterday: "'Eilen'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Uuden version tarkistus epäonnistui"
checkFailGithub: "Uuden version tarkistus epäonnistui Github/versions.txt:ta"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Inconnu"
yes: "Oui"
yesterday: "'Hier'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Impossible de vérifier le dernier numéro de la version"
checkFailGithub: "Les informations de la version n'ont pas pu être chargées depuis Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Sconosciuto"
yes: "Sì"
yesterday: "'Ieri'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Impossibile controllare nuove versioni"
checkFailGithub: "Informazioni sulla vesione non trovate su Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "不明"
yes: "はい"
yesterday: "'昨日'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "新しいバージョンのチェックに失敗しました"
checkFailGithub: "Github/versions.txtに存在するバージョン情報のロードに失敗しました"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "알 수 없음"
yes: "예"
yesterday: "'어제'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "최신 버전을 확인하지 못했습니다."
checkFailGithub: "Github/versions.txt 에서 버전 정보를 불러올 수 없습니다."

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Onbekend"
yes: "Ja"
yesterday: "'Gisteren'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Het nieuwste versienummer kan niet worden gecontroleerd"
checkFailGithub: "Versie-informatie kon niet worden geladen vanuit Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Desconhecido"
yes: "Sim"
yesterday: "'Ontem'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Falha ao verificar disponibilidade de atualização"
checkFailGithub: "Informação da versão não pode ser carregada de Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Неизвестный"
yes: "Да"
yesterday: "'Вчера'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Не удалось проверить номер последней версии"
checkFailGithub: "Информация о версии не может быть загружена из Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "Bilinmeyen"
yes: "Evet"
yesterday: "'Dün'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "En yeni sürüm numarası kontrol edilemedi"
checkFailGithub: "Sürüm bilgileri Github/versions.txt kısmından indirilemedi"

View File

@ -23,6 +23,9 @@ command:
feature:
description: "Тип датабази для відключення: ${0}"
name: "функція"
group:
description: "Web Permission Group, case sensitive."
name: "group"
importKind: "вид імпорту"
nameOrUUID:
description: "Нікнейм чи UUID гравця"
@ -150,6 +153,9 @@ command:
export:
description: "Експортувати HTML або JSON файли самостійно"
inDepth: "Виконує експорт у місце експорту, вказане в конфігурації."
groups:
description: "List web permission groups."
inDepth: "List available web permission groups that are managed on the web interface."
import:
description: "Імпортувати дату"
inDepth: "Виконує імпорт для завантаження даних у дата базу."
@ -193,6 +199,9 @@ command:
servers:
description: "Список серверів у базі даних"
inDepth: "Список айді, нікнеймів і UUID серверів у базі даних."
setgroup:
description: "Change users web permission group."
inDepth: "Allows you to change a users web permission group to an existing web group. Use /plan groups for list of available groups."
unregister:
description: "Видалити веб-користувача"
inDepth: "Використовуйте без аргументів, щоб скасувати реєстрацію користувача."
@ -262,8 +271,10 @@ html:
emptyForm: "Ім`я користувача та пароль не вказані"
expiredCookie: "Термін дії файлу cookie користувача закінчився"
generic: "Помилка під час авторизації"
groupNotFound: "Web Permission Group does not exist"
loginFailed: "Користувач і пароль не збігаються"
noCookie: "Користувацький файл cookie відсутній"
noPermissionGroup: "Registration failed, player did not have any 'plan.webgroup.{name}' permission"
registrationFailed: "Реєстрація не вдалася, спробуйте ще раз (Код перестане діяти через 15 хвилин)"
userNotFound: "Користувач не існує"
authFailed: "Помилка аутентифікації."
@ -320,9 +331,11 @@ html:
deaths: "Смерті"
disk: "Дисковий простір"
diskSpace: "Вільний дисковий простір"
docs: "Swagger Docs"
downtime: "Час простою"
duringLowTps: "Під час низького TPS:"
entities: "Об`єкти"
errors: "Plan Error Logs"
exported: "Час експорту даних"
favoriteServer: "Улюблений сервер"
firstSession: "Перша сесія"
@ -336,6 +349,8 @@ html:
miller: "Міллер"
ortographic: "Орфографічний"
geolocations: "Геолокація"
groupPermissions: "Manage Groups"
groupUsers: "Manage Group Users"
help:
activityIndexBasis: "Індекс активності базується на ігровому часі за останні 3 тижні (21 день). Кожен тиждень розглядається окремо."
activityIndexExample1: "Якщо хтось грає більше порогу щотижня, він отримує індекс активності ~3."
@ -348,6 +363,23 @@ html:
labels: "Ви можете приховати/показати групу, натиснувши на ярлик внизу."
title: "Графік"
zoom: "Ви можете збільшити масштаб, клацнувши і перетягнувши графік."
manage:
groups:
line-1: "This view allows you to modify web group permissions."
line-10: "{{permission}} permissions determine what parts of the page are visible. These permissions also limit requests to the related data endpoints."
line-11: "{{permission1}} permissions are not required for data: {{permission2}} allows request to /v1/network/overview even without {{permission3}}."
line-12: "Saving changes"
line-13: "When you add a group or delete a group that action is saved immediately after confirm (no undo)."
line-14: "When you modify permissions those changes need to be saved by pressing the Save-button"
line-15: "Documentation can be found from {{link}}"
line-2: "User's web group is determined during {{command}} by checking if Player has {{permission}} permission."
line-3: "You can use {{command}} to change permission group after registering."
line-4: "{{icon}} If you ever accidentally delete all groups with {{permission}}} permission just {{command}}."
line-5: "Permission inheritance"
line-6: "Permissions follow inheritance model, where higher level permission grants all lower ones, eg. {{permission1}} also gives {{permission2}}, etc."
line-7: "Access vs Page -permissions"
line-8: "You need to assign both access and page permissions for users."
line-9: "{{permission1}} permissions allow user make the request to specific address, eg. {{permission2}} allows request to /network."
playtimeUnit: "годин"
retention:
calculationStep1: "Спочатку дані фільтруються за допомогою опції '<>'. Гравці з параметром 'registerDate' за межами часового діапазону ігноруються."
@ -407,6 +439,30 @@ html:
longestSession: "Найдовша сесія"
lowTpsSpikes: "Низький TPS"
lowTpsSpikes7days: "Низькі піки TPS (7 днів)"
manage: "Manage"
managePage:
addGroup:
header: "Add group"
invalidName: "Group name can be 100 characters maximum."
name: "Name of the group"
alert:
groupAddFail: "Failed to add group: {{error}}"
groupAddSuccess: "Added group '{{groupName}}'"
groupDeleteFail: "Failed to delete group: {{error}}"
groupDeleteSuccess: "Deleted group '{{groupName}}'"
saveFail: "Failed to save changes: {{error}}"
saveSuccess: "Changes saved successfully!"
changes:
discard: "Discard Changes"
save: "Save"
unsaved: "Unsaved changes"
deleteGroup:
confirm: "Confirm & Delete {{groupName}}"
confirmDescription: "This will move all users of '{{groupName}}' to group '{{moveTo}}'. There is no undo!"
header: "Delete '{{groupName}}'"
moveToSelect: "Move remaining users to group"
groupHeader: "Manage Group Permissions"
groupPermissions: "Permissions of {{groupName}}"
maxFreeDisk: "Макс. вільний диск"
medianSessionLength: "Середня тривалість сеансу"
minFreeDisk: "Мін. вільний диск"
@ -511,6 +567,10 @@ html:
sessions: "Сесії"
sortBy: "Сортувати за"
stacked: "Складено"
table:
showNofM: "Showing {{n}} of {{mn}} entries"
showPerPage: "Show per page"
visibleColumns: "Visible columns"
themeSelect: "Вибір теми"
thirdDeadliestWeapon: "3-тя PvP зброя"
thirtyDays: "30 днів"
@ -542,6 +602,7 @@ html:
unit:
percentage: "Відсоток"
playerCount: "Кількість гравців"
users: "Manage Users"
veryActive: "Дуже активний"
weekComparison: "Порівняння за тиждень"
weekdays: "'Понеділок', 'Вівторок', 'Середа', 'Четвер', 'П`ятниця', 'Субота', 'Неділя'"
@ -562,6 +623,89 @@ html:
password: "Пароль"
register: "Створіть акаунт!"
username: "Ім'я користувача"
manage:
permission:
description:
access: "Controls access to pages"
access_docs: "Allows accessing /docs page"
access_errors: "Allows accessing /errors page"
access_network: "Allows accessing /network page"
access_player: "Allows accessing any /player pages"
access_player_self: "Allows accessing own /player page"
access_players: "Allows accessing /players page"
access_query: "Allows accessing /query and Query results pages"
access_raw_player_data: "Allows accessing /player/{uuid}/raw json data. Follows 'access.player' permissions."
access_server: "Allows accessing all /server pages"
manage_groups: "Allows modifying group permissions & Access to /manage/groups page"
manage_users: "Allows modifying what users belong to what group"
page: "Controls what is visible on pages"
page_network: "See all of network page"
page_network_geolocations: "See Geolocations tab"
page_network_geolocations_map: "See Geolocations Map"
page_network_geolocations_ping_per_country: "See Ping Per Country table"
page_network_join_addresses: "See Join Addresses -tab"
page_network_join_addresses_graphs: "See Join Address graphs"
page_network_join_addresses_graphs_pie: "See Latest Join Addresses graph"
page_network_join_addresses_graphs_time: "See Join Addresses over time graph"
page_network_overview: "See Network Overview -tab"
page_network_overview_graphs: "See Network Overview graphs"
page_network_overview_graphs_day_by_day: "See Day by Day graph"
page_network_overview_graphs_hour_by_hour: "See Hour by Hour graph"
page_network_overview_graphs_online: "See Players Online graph"
page_network_overview_numbers: "See Network Overview numbers"
page_network_performance: "See network Performance tab"
page_network_playerbase: "See Playerbase Overview -tab"
page_network_playerbase_graphs: "See Playerbase Overview graphs"
page_network_playerbase_overview: "See Playerbase Overview numbers"
page_network_players: "See Player list -tab"
page_network_plugins: "See Plugins tab of Proxy"
page_network_retention: "See Player Retention -tab"
page_network_server_list: "See list of servers"
page_network_sessions: "See Sessions tab"
page_network_sessions_list: "See list of sessions"
page_network_sessions_overview: "See Session insights"
page_network_sessions_server_pie: "See Server Pie graph"
page_network_sessions_world_pie: "See World Pie graph"
page_player: "See all of player page"
page_player_overview: "See Player Overview -tab"
page_player_plugins: "See Plugins -tabs"
page_player_servers: "See Servers -tab"
page_player_sessions: "See Player Sessions -tab"
page_player_versus: "See PvP & PvE -tab"
page_server: "See all of server page"
page_server_geolocations: "See Geolocations tab"
page_server_geolocations_map: "See Geolocations Map"
page_server_geolocations_ping_per_country: "See Ping Per Country table"
page_server_join_addresses: "See Join Addresses -tab"
page_server_join_addresses_graphs: "See Join Address graphs"
page_server_join_addresses_graphs_pie: "See Latest Join Addresses graph"
page_server_join_addresses_graphs_time: "See Join Addresses over time graph"
page_server_online_activity: "See Online Activity -tab"
page_server_online_activity_graphs: "See Online Activity graphs"
page_server_online_activity_graphs_calendar: "See Server calendar"
page_server_online_activity_graphs_day_by_day: "See Day by Day graph"
page_server_online_activity_graphs_hour_by_hour: "See Hour by Hour graph"
page_server_online_activity_graphs_punchcard: "See Punchcard graph"
page_server_online_activity_overview: "See Online Activity numbers"
page_server_overview: "See Server Overview -tab"
page_server_overview_numbers: "See Server Overview numbers"
page_server_overview_players_online_graph: "See Players Online graph"
page_server_performance: "See Performance tab"
page_server_performance_graphs: "See Performance graphs"
page_server_performance_overview: "See Performance numbers"
page_server_player_versus: "See PvP & PvE -tab"
page_server_player_versus_kill_list: "See Player kill and death lists"
page_server_player_versus_overview: "See PvP & PvE numbers"
page_server_playerbase: "See Playerbase Overview -tab"
page_server_playerbase_graphs: "See Playerbase Overview graphs"
page_server_playerbase_overview: "See Playerbase Overview numbers"
page_server_players: "See Player list -tab"
page_server_plugins: "See Plugins -tabs of servers"
page_server_retention: "See Player Retention -tab"
page_server_sessions: "See Sessions tab"
page_server_sessions_list: "See list of sessions"
page_server_sessions_overview: "See Session insights"
page_server_sessions_world_pie: "See World Pie graph"
modal:
info:
bugs: "Повідомити про проблеми"
@ -736,6 +880,7 @@ plugin:
unknown: "Невідомий"
yes: "Так"
yesterday: "'Вчора'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "Не вдалося перевірити номер останньої версії"
checkFailGithub: "Інформація про версію не може бути завантажена з Github/versions.txt"

View File

@ -880,6 +880,7 @@ plugin:
unknown: "未知"
yes: "是"
yesterday: "'昨天'"
localeReloaded: "Custom locale.yml was modified so it was reloaded and is now in use."
version:
checkFail: "無法檢查最新版本號"
checkFailGithub: "無法從 Github/versions.txt 載入版本訊息"