Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0c33706b3 | ||
|
|
ae8c511a9a |
@@ -193,8 +193,12 @@ curl -fsSL https://gitea.hsrv.site/mrleo1nid/pzmanager/raw/branch/main/deploy/ge
|
|||||||
На вкладке «Профили» есть «Импорт пресета сборки»: выберите ZIP, и панель
|
На вкладке «Профили» есть «Импорт пресета сборки»: выберите ZIP, и панель
|
||||||
покажет, что в нём нашла — название сервера, сколько модов и пакетов
|
покажет, что в нём нашла — название сервера, сколько модов и пакетов
|
||||||
мастерской, какие карты, сколько параметров конфига и песочницы. Ничего не
|
мастерской, какие карты, сколько параметров конфига и песочницы. Ничего не
|
||||||
записывается, пока вы не нажмёте «Импортировать». Если наборов в архиве
|
записывается, пока вы не нажмёте «Импортировать».
|
||||||
несколько, появится список выбора.
|
|
||||||
|
Если наборов в архиве несколько, появится список выбора. Первым идёт самый
|
||||||
|
полный набор — тот, где есть конфиг сервера: только в нём лежат моды и карты.
|
||||||
|
Рядом с именем написано, что внутри, чтобы случайно не импортировать пресет
|
||||||
|
песочницы вместо комплекта сервера.
|
||||||
|
|
||||||
Импортировать можно в новый профиль (идентификатор предлагается по имени
|
Импортировать можно в новый профиль (идентификатор предлагается по имени
|
||||||
файлов из архива) или поверх существующего. Прежние конфиги остаются рядом с
|
файлов из архива) или поверх существующего. Прежние конфиги остаются рядом с
|
||||||
@@ -202,6 +206,11 @@ curl -fsSL https://gitea.hsrv.site/mrleo1nid/pzmanager/raw/branch/main/deploy/ge
|
|||||||
импорт не принимает — сначала остановите сервер, иначе PZ перезапишет файлы
|
импорт не принимает — сначала остановите сервер, иначе PZ перезапишет файлы
|
||||||
своими при выходе.
|
своими при выходе.
|
||||||
|
|
||||||
|
Галочка «Сделать этот профиль активным» включена по умолчанию: вкладки «Моды»
|
||||||
|
и «Конфиг сервера» показывают активный профиль, и без переключения кажется,
|
||||||
|
что импорт ничего не сделал. Если галочку снять, панель напомнит, под каким
|
||||||
|
профилем искать импортированное.
|
||||||
|
|
||||||
Галочки «Оставить свои значения» переносят в импортированный конфиг то, что
|
Галочки «Оставить свои значения» переносят в импортированный конфиг то, что
|
||||||
относится к вашей машине, а не к сборке:
|
относится к вашей машине, а не к сборке:
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ func (s *Server) handleImportPreset(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createNew := r.FormValue("target") != "existing"
|
createNew := r.FormValue("target") != "existing"
|
||||||
|
activate := r.FormValue("activate") == "1"
|
||||||
id := strings.TrimSpace(r.FormValue("profile"))
|
id := strings.TrimSpace(r.FormValue("profile"))
|
||||||
if id == "" && createNew {
|
if id == "" && createNew {
|
||||||
id = config.SanitizeProfileID(files.Name)
|
id = config.SanitizeProfileID(files.Name)
|
||||||
@@ -68,8 +69,9 @@ func (s *Server) handleImportPreset(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Живой сервер держит мир и конфиг в памяти и переписывает файлы при
|
// Живой сервер держит мир и конфиг в памяти и переписывает файлы при
|
||||||
// остановке — импорт под ним просто пропал бы.
|
// остановке — импорт под ним просто пропал бы. Переключать профиль на
|
||||||
if id == s.cfg.Active && s.sup.State() != pzserver.StateStopped {
|
// живом сервере нельзя по той же причине.
|
||||||
|
if s.sup.State() != pzserver.StateStopped && (id == s.cfg.Active || activate) {
|
||||||
writeError(w, r, http.StatusConflict, "сначала остановите игровой сервер")
|
writeError(w, r, http.StatusConflict, "сначала остановите игровой сервер")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -94,7 +96,17 @@ func (s *Server) handleImportPreset(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, r, http.StatusInternalServerError, err.Error())
|
writeError(w, r, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if createNew {
|
// Вкладки панели показывают активный профиль: без переключения импорт
|
||||||
|
// выглядит так, будто моды и настройки не подтянулись.
|
||||||
|
switched := false
|
||||||
|
if activate && s.cfg.Active != id {
|
||||||
|
if err := s.cfg.SetActive(id); err != nil {
|
||||||
|
writeError(w, r, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switched = true
|
||||||
|
}
|
||||||
|
if createNew || switched {
|
||||||
if err := s.cfg.Save(); err != nil {
|
if err := s.cfg.Save(); err != nil {
|
||||||
writeError(w, r, http.StatusInternalServerError, err.Error())
|
writeError(w, r, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
@@ -104,9 +116,13 @@ func (s *Server) handleImportPreset(w http.ResponseWriter, r *http.Request) {
|
|||||||
summary := files.Describe()
|
summary := files.Describe()
|
||||||
s.sup.AppendLog("manager", fmt.Sprintf("Импортирован пресет %q в профиль %q (модов: %d)",
|
s.sup.AppendLog("manager", fmt.Sprintf("Импортирован пресет %q в профиль %q (модов: %d)",
|
||||||
files.Name, id, summary.Mods))
|
files.Name, id, summary.Mods))
|
||||||
|
if switched {
|
||||||
|
s.sup.AppendLog("manager", fmt.Sprintf("Активный профиль: %s", s.cfg.ActiveProfile().Name()))
|
||||||
|
}
|
||||||
|
|
||||||
result["profile"] = id
|
result["profile"] = id
|
||||||
result["created"] = createNew
|
result["created"] = createNew
|
||||||
|
result["switched"] = switched
|
||||||
result["summary"] = summary
|
result["summary"] = summary
|
||||||
writeJSON(w, http.StatusOK, result)
|
writeJSON(w, http.StatusOK, result)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,10 @@ func (s *Server) handleConsole(w http.ResponseWriter, r *http.Request) {
|
|||||||
// handleLogs отдаёт историю консоли начиная с указанного номера строки.
|
// handleLogs отдаёт историю консоли начиная с указанного номера строки.
|
||||||
func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||||
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"lines": translateLines(r, s.sup.Lines(since))})
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"epoch": s.sup.LogEpoch(),
|
||||||
|
"lines": translateLines(r, s.sup.Lines(since)),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// translateLines переводит строки консоли на язык читающего. Буфер один на
|
// translateLines переводит строки консоли на язык читающего. Буфер один на
|
||||||
@@ -119,7 +122,13 @@ func (s *Server) handleLogStream(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
lang := i18n.FromRequest(r)
|
lang := i18n.FromRequest(r)
|
||||||
|
|
||||||
// Сначала отдаём хвост истории, чтобы вкладка не открывалась пустой.
|
// Метка запуска идёт первой: по ней вкладка понимает, что менеджер
|
||||||
|
// перезапустился и нумерация строк началась заново.
|
||||||
|
if !writeSSEEvent(w, "meta", map[string]string{"epoch": s.sup.LogEpoch()}) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Затем хвост истории, чтобы вкладка не открывалась пустой.
|
||||||
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||||
for _, line := range translateLines(r, s.sup.Lines(since)) {
|
for _, line := range translateLines(r, s.sup.Lines(since)) {
|
||||||
if !writeSSE(w, line) {
|
if !writeSSE(w, line) {
|
||||||
@@ -162,3 +171,14 @@ func writeSSE(w http.ResponseWriter, line pzserver.LogLine) bool {
|
|||||||
_, err = fmt.Fprintf(w, "data: %s\n\n", payload)
|
_, err = fmt.Fprintf(w, "data: %s\n\n", payload)
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// writeSSEEvent отправляет именованное событие: браузер ловит его отдельным
|
||||||
|
// слушателем и не путает со строками консоли.
|
||||||
|
func writeSSEEvent(w http.ResponseWriter, name string, value any) bool {
|
||||||
|
payload, err := json.Marshal(value)
|
||||||
|
if err != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
_, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", name, payload)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -160,10 +160,35 @@ func FromZip(data []byte) ([]Files, error) {
|
|||||||
if len(out) == 0 {
|
if len(out) == 0 {
|
||||||
return nil, ErrNoServerFiles
|
return nil, ErrNoServerFiles
|
||||||
}
|
}
|
||||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
// Первым идёт самый полный набор: панель предлагает его по умолчанию, а
|
||||||
|
// одинокий пресет песочницы переносит только значения песочницы — ни модов,
|
||||||
|
// ни карт в нём нет, и импорт выглядит как «ничего не подтянулось».
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
wi, wj := weight(out[i]), weight(out[j])
|
||||||
|
if wi != wj {
|
||||||
|
return wi > wj
|
||||||
|
}
|
||||||
|
return out[i].Name < out[j].Name
|
||||||
|
})
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// weight — насколько набор полон. Конфиг сервера перевешивает всё остальное:
|
||||||
|
// только в нём есть список модов, карты и настройки самого сервера.
|
||||||
|
func weight(f Files) int {
|
||||||
|
total := 0
|
||||||
|
if f.INI != nil {
|
||||||
|
total += 4
|
||||||
|
}
|
||||||
|
if f.Sandbox != nil {
|
||||||
|
total += 2
|
||||||
|
}
|
||||||
|
if f.SpawnRegions != nil {
|
||||||
|
total++
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
type kind int
|
type kind int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -192,3 +192,25 @@ func TestFromZipRejectsGarbage(t *testing.T) {
|
|||||||
t.Fatal("мусор принят за архив")
|
t.Fatal("мусор принят за архив")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// В пакете сборки рядом с конфигом сервера лежит и пресет песочницы для
|
||||||
|
// одиночной игры. Первым должен идти набор с конфигом: панель предлагает его по
|
||||||
|
// умолчанию, а из пресета песочницы моды и карты не возьмутся.
|
||||||
|
func TestFromZipServerSetGoesFirst(t *testing.T) {
|
||||||
|
data := buildZip(t, map[string]string{
|
||||||
|
// Имя пресета нарочно сортируется раньше по алфавиту.
|
||||||
|
"Sandbox Presets/Alpha-Sandbox.cfg": sandboxCFG,
|
||||||
|
"Server/zulu-server.ini": serverINI,
|
||||||
|
"Server/zulu-server_SandboxVars.lua": sandboxLua,
|
||||||
|
})
|
||||||
|
sets, err := FromZip(data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(sets) != 2 {
|
||||||
|
t.Fatalf("наборов: %d", len(sets))
|
||||||
|
}
|
||||||
|
if sets[0].INI == nil {
|
||||||
|
t.Fatalf("первым идёт набор без конфига сервера: %q", sets[0].Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
package pzserver
|
package pzserver
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ansiRe ловит управляющие последовательности терминала: SteamCMD и сам
|
// ansiRe ловит управляющие последовательности терминала: SteamCMD и сам
|
||||||
@@ -32,6 +36,7 @@ type logBuffer struct {
|
|||||||
lines []LogLine
|
lines []LogLine
|
||||||
capacity int
|
capacity int
|
||||||
nextSeq int64
|
nextSeq int64
|
||||||
|
epoch string
|
||||||
subs map[int]chan LogLine
|
subs map[int]chan LogLine
|
||||||
nextSub int
|
nextSub int
|
||||||
}
|
}
|
||||||
@@ -41,10 +46,25 @@ func newLogBuffer(capacity int) *logBuffer {
|
|||||||
lines: make([]LogLine, 0, capacity),
|
lines: make([]LogLine, 0, capacity),
|
||||||
capacity: capacity,
|
capacity: capacity,
|
||||||
nextSeq: 1,
|
nextSeq: 1,
|
||||||
|
epoch: newEpoch(),
|
||||||
subs: make(map[int]chan LogLine),
|
subs: make(map[int]chan LogLine),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newEpoch помечает этот запуск менеджера. Номера строк живут только в памяти
|
||||||
|
// и после перезапуска начинаются заново — открытая вкладка приняла бы новые
|
||||||
|
// строки за уже показанные и молчала бы до перезагрузки страницы. По смене
|
||||||
|
// метки браузер понимает, что нумерацию надо начать с нуля.
|
||||||
|
func newEpoch() string {
|
||||||
|
var raw [8]byte
|
||||||
|
if _, err := rand.Read(raw[:]); err != nil {
|
||||||
|
// Случайность здесь не нужна для безопасности: метку достаточно
|
||||||
|
// отличать от предыдущей, и время запуска с этим справляется.
|
||||||
|
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(raw[:])
|
||||||
|
}
|
||||||
|
|
||||||
// append кладёт строку в буфер и рассылает подписчикам.
|
// append кладёт строку в буфер и рассылает подписчикам.
|
||||||
func (b *logBuffer) append(line LogLine) {
|
func (b *logBuffer) append(line LogLine) {
|
||||||
// Чистим здесь, а не у каждого источника: через буфер проходят и вывод
|
// Чистим здесь, а не у каждого источника: через буфер проходят и вывод
|
||||||
|
|||||||
@@ -39,3 +39,21 @@ func TestAppendStripsANSI(t *testing.T) {
|
|||||||
t.Errorf("в буфер попала строка с кодами: %q", lines[0].Text)
|
t.Errorf("в буфер попала строка с кодами: %q", lines[0].Text)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Номера строк живут в памяти менеджера: после перезапуска они начинаются
|
||||||
|
// заново. Метка запуска должна это показывать, иначе открытая вкладка примет
|
||||||
|
// новые строки за уже показанные.
|
||||||
|
func TestLogBufferEpochDiffers(t *testing.T) {
|
||||||
|
first, second := newLogBuffer(8), newLogBuffer(8)
|
||||||
|
if first.epoch == "" {
|
||||||
|
t.Fatal("метка запуска пустая")
|
||||||
|
}
|
||||||
|
if first.epoch == second.epoch {
|
||||||
|
t.Fatalf("метки совпали: %q", first.epoch)
|
||||||
|
}
|
||||||
|
first.append(LogLine{Stream: "manager", Text: "первый запуск"})
|
||||||
|
second.append(LogLine{Stream: "manager", Text: "второй запуск"})
|
||||||
|
if got := second.since(0); len(got) != 1 || got[0].Seq != 1 {
|
||||||
|
t.Fatalf("нумерация нового буфера: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -157,6 +157,9 @@ func (s *Supervisor) AppendLog(stream, text string) {
|
|||||||
// Lines возвращает историю консоли начиная с номера seq.
|
// Lines возвращает историю консоли начиная с номера seq.
|
||||||
func (s *Supervisor) Lines(seq int64) []LogLine { return s.log.since(seq) }
|
func (s *Supervisor) Lines(seq int64) []LogLine { return s.log.since(seq) }
|
||||||
|
|
||||||
|
// LogEpoch — метка этого запуска менеджера. Меняется вместе с нумерацией строк.
|
||||||
|
func (s *Supervisor) LogEpoch() string { return s.log.epoch }
|
||||||
|
|
||||||
// Subscribe отдаёт канал новых строк консоли и функцию отписки.
|
// Subscribe отдаёт канал новых строк консоли и функцию отписки.
|
||||||
func (s *Supervisor) Subscribe() (<-chan LogLine, func()) { return s.log.subscribe(256) }
|
func (s *Supervisor) Subscribe() (<-chan LogLine, func()) { return s.log.subscribe(256) }
|
||||||
|
|
||||||
|
|||||||
+51
-6
@@ -398,17 +398,38 @@ $("#btn-task-cancel").addEventListener("click", async () => {
|
|||||||
|
|
||||||
let eventSource = null;
|
let eventSource = null;
|
||||||
let lastSeq = 0;
|
let lastSeq = 0;
|
||||||
|
// Метка запуска менеджера: номера строк живут в его памяти и после
|
||||||
|
// перезапуска начинаются заново.
|
||||||
|
let logEpoch = null;
|
||||||
const MAX_CONSOLE_LINES = 3000;
|
const MAX_CONSOLE_LINES = 3000;
|
||||||
|
|
||||||
function openConsoleStream() {
|
function openConsoleStream() {
|
||||||
closeConsoleStream();
|
closeConsoleStream();
|
||||||
eventSource = new EventSource(`/api/logs/stream?since=${lastSeq}`);
|
eventSource = new EventSource(`/api/logs/stream?since=${lastSeq}`);
|
||||||
|
eventSource.addEventListener("meta", (event) => handleConsoleMeta(JSON.parse(event.data)));
|
||||||
eventSource.onmessage = (event) => appendConsoleLine(JSON.parse(event.data));
|
eventSource.onmessage = (event) => appendConsoleLine(JSON.parse(event.data));
|
||||||
eventSource.onerror = () => {
|
eventSource.onerror = () => {
|
||||||
// Браузер переподключается сам; сообщать об этом каждый раз не нужно.
|
// Браузер переподключается сам; сообщать об этом каждый раз не нужно.
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handleConsoleMeta ловит перезапуск менеджера: без сброса счётчика вкладка
|
||||||
|
// приняла бы новые строки за уже показанные и осталась бы пустой до
|
||||||
|
// перезагрузки страницы.
|
||||||
|
function handleConsoleMeta(meta) {
|
||||||
|
if (logEpoch === meta.epoch) return;
|
||||||
|
const restarted = logEpoch !== null;
|
||||||
|
logEpoch = meta.epoch;
|
||||||
|
lastSeq = 0;
|
||||||
|
if (!restarted) return;
|
||||||
|
|
||||||
|
$("#console-output").innerHTML = "";
|
||||||
|
pushConsoleLine("manager", t("console.managerRestarted"));
|
||||||
|
// Переоткрываем поток: этот запрашивал историю с прежнего номера, а её у
|
||||||
|
// нового запуска нет.
|
||||||
|
openConsoleStream();
|
||||||
|
}
|
||||||
|
|
||||||
function closeConsoleStream() {
|
function closeConsoleStream() {
|
||||||
if (eventSource) eventSource.close();
|
if (eventSource) eventSource.close();
|
||||||
eventSource = null;
|
eventSource = null;
|
||||||
@@ -417,14 +438,19 @@ function closeConsoleStream() {
|
|||||||
function appendConsoleLine(line) {
|
function appendConsoleLine(line) {
|
||||||
if (line.seq <= lastSeq) return;
|
if (line.seq <= lastSeq) return;
|
||||||
lastSeq = line.seq;
|
lastSeq = line.seq;
|
||||||
|
pushConsoleLine(line.stream, line.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
// pushConsoleLine рисует строку на экране. Отдельно от нумерации: свои
|
||||||
|
// сообщения панель показывает без номера из буфера менеджера.
|
||||||
|
function pushConsoleLine(stream, text) {
|
||||||
const output = $("#console-output");
|
const output = $("#console-output");
|
||||||
const filter = $("#console-filter").value.trim().toLowerCase();
|
const filter = $("#console-filter").value.trim().toLowerCase();
|
||||||
|
|
||||||
const el = document.createElement("div");
|
const el = document.createElement("div");
|
||||||
el.className = `line-${line.stream}`;
|
el.className = `line-${stream}`;
|
||||||
el.textContent = line.text;
|
el.textContent = text;
|
||||||
el.dataset.text = line.text.toLowerCase();
|
el.dataset.text = text.toLowerCase();
|
||||||
if (filter && !el.dataset.text.includes(filter)) el.hidden = true;
|
if (filter && !el.dataset.text.includes(filter)) el.hidden = true;
|
||||||
output.appendChild(el);
|
output.appendChild(el);
|
||||||
|
|
||||||
@@ -1664,7 +1690,14 @@ function renderPresetSets() {
|
|||||||
|
|
||||||
const picker = $("#preset-set");
|
const picker = $("#preset-set");
|
||||||
picker.innerHTML = presetSets
|
picker.innerHTML = presetSets
|
||||||
.map((set) => `<option value="${escapeHTML(set.name)}">${escapeHTML(set.name)}</option>`)
|
.map((set) => {
|
||||||
|
// Подпись сразу говорит, что в наборе: пресет песочницы без конфига
|
||||||
|
// сервера не принесёт ни модов, ни карт.
|
||||||
|
const note = set.has_ini
|
||||||
|
? t("import.setServer", { mods: set.mods })
|
||||||
|
: t("import.setSandbox");
|
||||||
|
return `<option value="${escapeHTML(set.name)}">${escapeHTML(`${set.name} — ${note}`)}</option>`;
|
||||||
|
})
|
||||||
.join("");
|
.join("");
|
||||||
// Выбор нужен, только когда в архиве несколько наборов.
|
// Выбор нужен, только когда в архиве несколько наборов.
|
||||||
$("#preset-pick").hidden = presetSets.length < 2;
|
$("#preset-pick").hidden = presetSets.length < 2;
|
||||||
@@ -1736,7 +1769,11 @@ $("#btn-preset-import").addEventListener("click", async () => {
|
|||||||
|
|
||||||
const existing = $("#preset-target").value === "existing";
|
const existing = $("#preset-target").value === "existing";
|
||||||
const profile = existing ? $("#preset-profile").value : $("#preset-id").value.trim();
|
const profile = existing ? $("#preset-profile").value : $("#preset-id").value.trim();
|
||||||
if (!confirm(t("import.confirm", { name: set.name, profile }))) return;
|
const activate = $("#preset-activate").checked;
|
||||||
|
// Смена активного профиля — заметное действие: о нём предупреждаем заранее.
|
||||||
|
const question = t("import.confirm", { name: set.name, profile })
|
||||||
|
+ (activate && profile !== profiles.active ? "\n\n" + t("import.confirmActivate", { profile }) : "");
|
||||||
|
if (!confirm(question)) return;
|
||||||
|
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.append("file", file);
|
form.append("file", file);
|
||||||
@@ -1748,6 +1785,7 @@ $("#btn-preset-import").addEventListener("click", async () => {
|
|||||||
.filter((box) => box.checked)
|
.filter((box) => box.checked)
|
||||||
.map((box) => box.dataset.keep)
|
.map((box) => box.dataset.keep)
|
||||||
.join(","));
|
.join(","));
|
||||||
|
form.append("activate", activate ? "1" : "");
|
||||||
|
|
||||||
const button = $("#btn-preset-import");
|
const button = $("#btn-preset-import");
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
@@ -1760,10 +1798,17 @@ $("#btn-preset-import").addEventListener("click", async () => {
|
|||||||
if (result.applied !== undefined) {
|
if (result.applied !== undefined) {
|
||||||
toast(t("import.applied", { applied: result.applied, skipped: result.skipped }));
|
toast(t("import.applied", { applied: result.applied, skipped: result.skipped }));
|
||||||
}
|
}
|
||||||
|
if (result.switched) {
|
||||||
|
toast(t("import.switched", { profile: result.profile }));
|
||||||
|
} else if (result.profile !== profiles.active) {
|
||||||
|
// Вкладки показывают активный профиль: без этого импорт выглядит так,
|
||||||
|
// будто моды и настройки никуда не попали.
|
||||||
|
toast(t("import.notActive", { profile: result.profile }));
|
||||||
|
}
|
||||||
$("#preset-file").value = "";
|
$("#preset-file").value = "";
|
||||||
$("#preset-details").hidden = true;
|
$("#preset-details").hidden = true;
|
||||||
await loadProfiles();
|
await loadProfiles();
|
||||||
// Импортированный профиль мог оказаться активным — вкладки показывают
|
// Импортированный профиль мог стать активным — вкладки показывают
|
||||||
// именно его конфиг.
|
// именно его конфиг.
|
||||||
loadTab(currentTab);
|
loadTab(currentTab);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -159,6 +159,7 @@ const STRINGS = {
|
|||||||
"console.autoscroll": "Прокручивать за выводом",
|
"console.autoscroll": "Прокручивать за выводом",
|
||||||
"console.filter": "Фильтр по строке…",
|
"console.filter": "Фильтр по строке…",
|
||||||
"console.clear": "Очистить экран",
|
"console.clear": "Очистить экран",
|
||||||
|
"console.managerRestarted": "— менеджер перезапущен, консоль начата заново —",
|
||||||
"console.placeholder": "Команда сервера, например: players, save, quit",
|
"console.placeholder": "Команда сервера, например: players, save, quit",
|
||||||
"console.placeholderOffline": "Сервер остановлен — консоль принимает команды только на работающем",
|
"console.placeholderOffline": "Сервер остановлен — консоль принимает команды только на работающем",
|
||||||
"console.send": "Отправить",
|
"console.send": "Отправить",
|
||||||
@@ -303,6 +304,8 @@ const STRINGS = {
|
|||||||
"import.fileHint": "ZIP-пакет сборки или пресет песочницы .cfg. Из архива панель возьмёт серверный .ini, настройки песочницы и точки появления, остальное пропустит.",
|
"import.fileHint": "ZIP-пакет сборки или пресет песочницы .cfg. Из архива панель возьмёт серверный .ini, настройки песочницы и точки появления, остальное пропустит.",
|
||||||
"import.reading": "Читаю архив…",
|
"import.reading": "Читаю архив…",
|
||||||
"import.set": "Набор из архива",
|
"import.set": "Набор из архива",
|
||||||
|
"import.setServer": "конфиг сервера, модов: {mods}",
|
||||||
|
"import.setSandbox": "только пресет песочницы, без модов",
|
||||||
"import.server": "Сервер: {name}",
|
"import.server": "Сервер: {name}",
|
||||||
"import.mods": "Моды: {mods} · пакеты мастерской: {workshop}",
|
"import.mods": "Моды: {mods} · пакеты мастерской: {workshop}",
|
||||||
"import.maps": "Карты: {maps}",
|
"import.maps": "Карты: {maps}",
|
||||||
@@ -320,6 +323,11 @@ const STRINGS = {
|
|||||||
"import.keepPorts": "Порты и RCON",
|
"import.keepPorts": "Порты и RCON",
|
||||||
"import.keepAccess": "Пароль сервера и объявляемый IP",
|
"import.keepAccess": "Пароль сервера и объявляемый IP",
|
||||||
"import.keepIdentity": "Имя и описание сервера",
|
"import.keepIdentity": "Имя и описание сервера",
|
||||||
|
"import.activate": "Сделать этот профиль активным",
|
||||||
|
"import.confirmActivate": "Профиль {profile} станет активным — панель и запуск переключатся на него.",
|
||||||
|
"import.activateHint": "Вкладки «Моды» и «Настройки» показывают активный профиль. Без переключения импортированные моды там не появятся.",
|
||||||
|
"import.switched": "Активный профиль: {profile}",
|
||||||
|
"import.notActive": "Профиль {profile} не активен — импортированные моды и настройки видны только под ним. Переключиться можно на вкладке «Профили».",
|
||||||
"import.apply": "Импортировать",
|
"import.apply": "Импортировать",
|
||||||
"import.noFile": "Выберите ZIP-пакет сборки",
|
"import.noFile": "Выберите ZIP-пакет сборки",
|
||||||
"import.confirm": "Импортировать набор «{name}» в профиль {profile}?\n\nКонфиги профиля будут заменены, прежние останутся рядом с расширением .bak.",
|
"import.confirm": "Импортировать набор «{name}» в профиль {profile}?\n\nКонфиги профиля будут заменены, прежние останутся рядом с расширением .bak.",
|
||||||
@@ -494,6 +502,7 @@ const STRINGS = {
|
|||||||
"console.autoscroll": "Scroll with output",
|
"console.autoscroll": "Scroll with output",
|
||||||
"console.filter": "Filter by text…",
|
"console.filter": "Filter by text…",
|
||||||
"console.clear": "Clear screen",
|
"console.clear": "Clear screen",
|
||||||
|
"console.managerRestarted": "— the manager restarted, the console starts over —",
|
||||||
"console.placeholder": "Server command, for example: players, save, quit",
|
"console.placeholder": "Server command, for example: players, save, quit",
|
||||||
"console.placeholderOffline": "Server stopped — the console only accepts commands while it runs",
|
"console.placeholderOffline": "Server stopped — the console only accepts commands while it runs",
|
||||||
"console.send": "Send",
|
"console.send": "Send",
|
||||||
@@ -638,6 +647,8 @@ const STRINGS = {
|
|||||||
"import.fileHint": "A collection ZIP package or a .cfg sandbox preset. From the archive the panel takes the server .ini, the sandbox settings and the spawn regions, and skips the rest.",
|
"import.fileHint": "A collection ZIP package or a .cfg sandbox preset. From the archive the panel takes the server .ini, the sandbox settings and the spawn regions, and skips the rest.",
|
||||||
"import.reading": "Reading the archive…",
|
"import.reading": "Reading the archive…",
|
||||||
"import.set": "Preset from the archive",
|
"import.set": "Preset from the archive",
|
||||||
|
"import.setServer": "server config, mods: {mods}",
|
||||||
|
"import.setSandbox": "sandbox preset only, no mods",
|
||||||
"import.server": "Server: {name}",
|
"import.server": "Server: {name}",
|
||||||
"import.mods": "Mods: {mods} · Workshop items: {workshop}",
|
"import.mods": "Mods: {mods} · Workshop items: {workshop}",
|
||||||
"import.maps": "Maps: {maps}",
|
"import.maps": "Maps: {maps}",
|
||||||
@@ -655,6 +666,11 @@ const STRINGS = {
|
|||||||
"import.keepPorts": "Ports and RCON",
|
"import.keepPorts": "Ports and RCON",
|
||||||
"import.keepAccess": "Server password and announced IP",
|
"import.keepAccess": "Server password and announced IP",
|
||||||
"import.keepIdentity": "Server name and description",
|
"import.keepIdentity": "Server name and description",
|
||||||
|
"import.activate": "Make this profile active",
|
||||||
|
"import.confirmActivate": "The profile {profile} will become active — the panel and the server start will switch to it.",
|
||||||
|
"import.activateHint": "The Mods and Settings tabs show the active profile. Without switching, the imported mods will not appear there.",
|
||||||
|
"import.switched": "Active profile: {profile}",
|
||||||
|
"import.notActive": "The profile {profile} is not active — the imported mods and settings are only visible under it. You can switch on the Profiles tab.",
|
||||||
"import.apply": "Import",
|
"import.apply": "Import",
|
||||||
"import.noFile": "Choose a collection ZIP package",
|
"import.noFile": "Choose a collection ZIP package",
|
||||||
"import.confirm": "Import the preset \"{name}\" into the profile {profile}?\n\nThe profile configs will be replaced, the previous ones stay next to them with a .bak extension.",
|
"import.confirm": "Import the preset \"{name}\" into the profile {profile}?\n\nThe profile configs will be replaced, the previous ones stay next to them with a .bak extension.",
|
||||||
|
|||||||
@@ -306,6 +306,10 @@
|
|||||||
<span data-i18n="import.keepIdentity"></span></label>
|
<span data-i18n="import.keepIdentity"></span></label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<label class="checkbox"><input type="checkbox" id="preset-activate" checked>
|
||||||
|
<span data-i18n="import.activate"></span></label>
|
||||||
|
<div class="hint" data-i18n="import.activateHint"></div>
|
||||||
|
|
||||||
<button class="btn btn-primary" id="btn-preset-import" data-i18n="import.apply"></button>
|
<button class="btn btn-primary" id="btn-preset-import" data-i18n="import.apply"></button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user