Initial commit

This commit is contained in:
Popov_Grigorii 2026-07-15 17:17:03 +03:00
commit cc078a2c8d
94 changed files with 76773 additions and 0 deletions

37
.gitignore vendored Normal file
View File

@ -0,0 +1,37 @@
# Build results
[Dd]ebug/
[Rr]elease/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio cache/options
.vs/
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# Папка с опубликованным приложением (её лучше собирать на целевом ПК, а не хранить в Git)
publish/
# Файлы конфигурации с реальными паролями (если есть)
# appsettings.Production.json
# appsettings.Development.json (раскомментируй, если там есть реальные пароли от почты)
# Docker volumes (если вдруг создались локально)
listmonk_data/

25
ListmonkIntegration.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.37411.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ListmonkIntegration", "ListmonkIntegration\ListmonkIntegration.csproj", "{7953334B-632D-4422-9EEB-51B078AC90F1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7953334B-632D-4422-9EEB-51B078AC90F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7953334B-632D-4422-9EEB-51B078AC90F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7953334B-632D-4422-9EEB-51B078AC90F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7953334B-632D-4422-9EEB-51B078AC90F1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {709BB448-6204-486B-A72E-675092D0C77E}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.105.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,9 @@
namespace ListmonkIntegration.Models
{
public class ListInfo
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int SubscriberCount { get; set; }
}
}

View File

@ -0,0 +1,10 @@
namespace ListmonkIntegration.Models
{
public class ListmonkSettings
{
public string BaseUrl { get; set; } = "http://localhost:9000";
public string Username { get; set; } = "listmonk";
public string Password { get; set; } = "listmonk";
public string? ApiToken { get; set; }
}
}

View File

@ -0,0 +1,11 @@
namespace ListmonkIntegration.Models
{
public class Subscriber
{
public string Email { get; set; } = string.Empty;
public string FullName { get; set; } = string.Empty;
public string Login { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public Dictionary<string, string> Attributes { get; set; } = new();
}
}

View File

@ -0,0 +1,9 @@
namespace ListmonkIntegration.Models
{
public class TemplateInfo
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,44 @@
@page
@model ListmonkIntegration.Pages.Campaigns.IndexModel
@{
ViewData["Title"] = "Управление рассылками";
}
<h1> Управление рассылками</h1>
<hr />
<div class="row">
<div class="col-md-12">
<div class="mb-4">
<a asp-page="/Templates/Create" class="btn btn-primary btn-lg">
Создать шаблон письма
</a>
<a asp-page="/Campaigns/Send" class="btn btn-warning btn-lg">
Отправить письмо
</a>
<a asp-page="/Subscribers/Upload" class="btn btn-success btn-lg">
Загрузить подписчиков
</a>
</div>
<div class="alert alert-info">
<h5>Функционал:</h5>
<ul>
<li>Загрузка Excel файлов с подписчиками</li>
<li>Создание шаблонов писем</li>
<li>Просмотр существующих кампаний</li>
<li>Запуск рассылок</li>
<li>Просмотр статистики</li>
</ul>
</div>
<a asp-page="/Index" class="btn btn-secondary">← На главную</a>
</div>
</div>
@if (TempData["SuccessMessage"] != null)
{
<div class="alert alert-success mt-3">
@TempData["SuccessMessage"]
</div>
}

View File

@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace ListmonkIntegration.Pages.Campaigns
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@ -0,0 +1,96 @@
@page
@model ListmonkIntegration.Pages.Campaigns.SendModel
@{
ViewData["Title"] = "Отправка письма";
}
<h1>Отправка письма</h1>
<hr />
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">@Model.ErrorMessage</div>
}
@if (!string.IsNullOrEmpty(Model.SuccessMessage))
{
<div class="alert alert-success">@Model.SuccessMessage</div>
}
<div class="row">
<div class="col-md-8">
<form method="post">
<div class="mb-3">
<label class="form-label">Название кампании</label>
<input type="text" asp-for="CampaignName" class="form-control" required placeholder="Например: Рассылка 08.07.2026" />
</div>
<div class="mb-3">
<label class="form-label">Выберите шаблон письма</label>
<select asp-for="SelectedTemplateId" class="form-select" asp-items="Model.Templates" id="templateSelect" required>
<option value="">-- Выберите шаблон --</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Список получателей</label>
<select asp-for="SelectedListId" class="form-select" asp-items="Model.Lists" required>
<option value="">-- Выберите список --</option>
</select>
<div class="form-text">
<span id="selectedListInfo"></span>
</div>
</div>
<div class="mb-3">
<label class="form-label">Предпросмотр шаблона</label>
<div id="templatePreview" class="border p-3 bg-light" style="min-height: 200px;">
<p class="text-muted">Выберите шаблон для предпросмотра</p>
</div>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary btn-lg">Отправить</button>
<a asp-page="/Campaigns/Index" class="btn btn-secondary">Отмена</a>
</div>
</form>
</div>
</div>
@section Scripts {
<script>
document.getElementById('templateSelect').addEventListener('change', async function() {
const templateId = this.value;
const previewDiv = document.getElementById('templatePreview');
if (templateId) {
previewDiv.innerHTML = '<p class="text-muted">Загрузка...</p>';
try {
const response = await fetch(`/api/templates/${templateId}/preview`);
if (response.ok) {
const data = await response.json();
previewDiv.innerHTML = data.body || '<p class="text-muted">Шаблон пуст</p>';
} else {
previewDiv.innerHTML = '<p class="text-danger">Ошибка загрузки шаблона</p>';
}
} catch (error) {
console.error('Error:', error);
previewDiv.innerHTML = '<p class="text-danger">Ошибка загрузки шаблона</p>';
}
} else {
previewDiv.innerHTML = '<p class="text-muted">Выберите шаблон для предпросмотра</p>';
}
});
document.querySelector('select[asp-for="SelectedListId"]').addEventListener('change', function() {
const select = this;
const infoSpan = document.getElementById('selectedListInfo');
const selectedOption = select.options[select.selectedIndex];
if (selectedOption.value) {
infoSpan.textContent = `Выбран список: ${selectedOption.text}`;
} else {
infoSpan.textContent = '';
}
});
</script>
}

View File

@ -0,0 +1,108 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using ListmonkIntegration.Services;
namespace ListmonkIntegration.Pages.Campaigns
{
public class SendModel : PageModel
{
private readonly IListmonkService _listmonkService;
private readonly ILogger<SendModel> _logger;
[BindProperty]
public string CampaignName { get; set; } = string.Empty;
[BindProperty]
public int? SelectedTemplateId { get; set; }
[BindProperty]
public int? SelectedListId { get; set; }
public SelectList Templates { get; set; } = new SelectList(Enumerable.Empty<SelectListItem>());
public SelectList Lists { get; set; } = new SelectList(Enumerable.Empty<SelectListItem>());
public string? ErrorMessage { get; set; }
public string? SuccessMessage { get; set; }
public SendModel(IListmonkService listmonkService, ILogger<SendModel> logger)
{
_listmonkService = listmonkService;
_logger = logger;
}
public async Task OnGetAsync()
{
await LoadDataAsync();
}
public async Task<IActionResult> OnPostAsync()
{
if (!SelectedTemplateId.HasValue || !SelectedListId.HasValue || string.IsNullOrWhiteSpace(CampaignName))
{
ErrorMessage = "Çàïîëíèòå âñå ïîëÿ";
await LoadDataAsync();
return Page();
}
try
{
var templates = await _listmonkService.GetTemplatesAsync();
var template = templates.FirstOrDefault(t => t.Id == SelectedTemplateId.Value);
if (template == null)
{
ErrorMessage = "Øàáëîí íå íàéäåí";
await LoadDataAsync();
return Page();
}
var campaignId = await _listmonkService.CreateCampaignAsync(
CampaignName,
SelectedListId.Value,
SelectedTemplateId.Value,
template.Subject
);
var started = await _listmonkService.StartCampaignAsync(campaignId);
if (started)
{
SuccessMessage = $"Êàìïàíèÿ \"{CampaignName}\" óñïåøíî ñîçäàíà è çàïóùåíà!";
_logger.LogInformation($"Campaign {campaignId} started successfully");
}
else
{
ErrorMessage = $"Êàìïàíèÿ ñîçäàíà (ID: {campaignId}), íî íå óäàëîñü çàïóñòèòü";
}
await LoadDataAsync();
return Page();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending campaign");
ErrorMessage = $"Îøèáêà: {ex.Message}";
await LoadDataAsync();
return Page();
}
}
private async Task LoadDataAsync()
{
try
{
var templates = await _listmonkService.GetTemplatesAsync();
Templates = new SelectList(templates, "Id", "Name");
var lists = await _listmonkService.GetListsAsync();
Lists = new SelectList(lists, "Id", "Name");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error loading data");
ErrorMessage = $"Îøèáêà çàãðóçêè äàííûõ: {ex.Message}";
}
}
}
}

View File

@ -0,0 +1,26 @@
@page
@model ErrorModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@ -0,0 +1,28 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace ListmonkIntegration.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}

View File

@ -0,0 +1,49 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Главная";
}
<div class="text-center">
<h1 class="display-4">Система управления рассылками</h1>
<p>Интеграция с Listmonk для автоматизации email-рассылок</p>
</div>
<div class="row mt-5">
<div class="col-md-4">
<div class="card">
<div class="card-body text-center">
<h5 class="card-title">Статус подключения</h5>
@if (Model.IsConnected)
{
<p class="text-success"><strong>Подключено к Listmonk</strong></p>
}
else
{
<p class="text-danger"><strong>Нет подключения</strong></p>
}
<p class="card-text">Адрес: @Model.ListmonkUrl</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-body text-center">
<h5 class="card-title">Загрузка данных</h5>
<p class="card-text">Загрузите Excel файл со списком получателей</p>
<a asp-page="/Subscribers/Upload" class="btn btn-primary">Загрузить файл</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-body text-center">
<h5 class="card-title">Рассылки</h5>
<p class="card-text">Создание шаблонов писем. </p>
<a asp-page="/Campaigns/Index" class="btn btn-success">Управление</a>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using ListmonkIntegration.Services;
using ListmonkIntegration.Models;
using Microsoft.Extensions.Options;
namespace ListmonkIntegration.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly IListmonkService _listmonkService;
private readonly ListmonkSettings _settings;
public bool IsConnected { get; private set; }
public string ListmonkUrl { get; private set; } = string.Empty;
public IndexModel(
ILogger<IndexModel> logger,
IListmonkService listmonkService,
IOptions<ListmonkSettings> settings)
{
_logger = logger;
_listmonkService = listmonkService;
_settings = settings.Value;
}
public async Task OnGetAsync()
{
ListmonkUrl = _settings.BaseUrl;
IsConnected = await _listmonkService.TestConnectionAsync();
}
}
}

View File

@ -0,0 +1,8 @@
@page
@model PrivacyModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace ListmonkIntegration.Pages
{
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;
public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}

View File

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - ListmonkIntegration</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/ListmonkIntegration.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">ListmonkIntegration</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2026 - ListmonkIntegration - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,48 @@
/* Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@ -0,0 +1,73 @@
@page
@model ListmonkIntegration.Pages.Subscribers.UploadModel
@{
ViewData["Title"] = "Загрузка подписчиков";
}
<h1>Загрузка списка подписчиков</h1>
<hr />
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="alert @(Model.IsSuccess ? "alert-success" : "alert-danger")">
@Model.Message
</div>
}
<div class="row">
<div class="col-md-6">
<form method="post" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label">Выберите Excel файл (.xlsx)</label>
<input type="file" name="excelFile" class="form-control" accept=".xlsx" required />
<div class="form-text">
Файл должен содержать столбцы: Email, FullName и другие атрибуты
</div>
</div>
<div class="mb-3">
<label class="form-label">Название списка в Listmonk</label>
<input type="text" name="listName" class="form-control" value="Рассылка @DateTime.Now.ToString("dd.MM.yyyy")" required />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary">Загрузить и обработать</button>
<a asp-page="/Index" class="btn btn-secondary">Отмена</a>
</div>
</form>
</div>
</div>
@if (Model.Subscribers != null && Model.Subscribers.Any())
{
<h3 class="mt-4">Загружено подписчиков: @Model.Subscribers.Count</h3>
@if (Model.ColumnHeaders != null && Model.ColumnHeaders.Any())
{
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead class="table-dark">
<tr>
@foreach (var header in Model.ColumnHeaders)
{
<th>@header</th>
}
</tr>
</thead>
<tbody>
@foreach (var sub in Model.Subscribers)
{
<tr>
<td>@sub.Email</td>
<td>@sub.FullName</td>
@foreach (var attr in sub.Attributes)
{
<td>@attr.Value</td>
}
</tr>
}
</tbody>
</table>
</div>
}
}

View File

@ -0,0 +1,215 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ListmonkIntegration.Services;
using ListmonkIntegration.Models;
using ClosedXML.Excel;
namespace ListmonkIntegration.Pages.Subscribers
{
public class UploadModel : PageModel
{
private readonly IListmonkService _listmonkService;
private readonly ILogger<UploadModel> _logger;
[BindProperty]
public IFormFile? excelFile { get; set; }
public List<Subscriber> Subscribers { get; set; } = new List<Subscriber>();
public List<string> ColumnHeaders { get; set; } = new List<string>();
public string Message { get; set; } = string.Empty;
public bool IsSuccess { get; set; }
public UploadModel(IListmonkService listmonkService, ILogger<UploadModel> logger)
{
_listmonkService = listmonkService;
_logger = logger;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync(string listName)
{
try
{
_logger.LogInformation("=== Upload started ===");
if (excelFile == null || excelFile.Length == 0)
{
Message = "Ôàéë íå âûáðàí";
IsSuccess = false;
return Page();
}
_logger.LogInformation($"File received: {excelFile.FileName}, Size: {excelFile.Length} bytes");
// Îãðàíè÷åíèå ðàçìåðà ôàéëà (10 MB)
if (excelFile.Length > 10 * 1024 * 1024)
{
Message = "Ôàéë ñëèøêîì áîëüøîé (ìàêñèìóì 10 MB)";
IsSuccess = false;
return Page();
}
// ×òåíèå Excel ôàéëà
_logger.LogInformation("Reading Excel file...");
Subscribers = ReadExcelFile(excelFile);
_logger.LogInformation($"Read {Subscribers.Count} subscribers");
if (!Subscribers.Any())
{
Message = "Íå íàéäåíî ïîäïèñ÷èêîâ â ôàéëå";
IsSuccess = false;
return Page();
}
// Ïðîâåðÿåì ïîäêëþ÷åíèå
_logger.LogInformation("Testing Listmonk connection...");
if (!await _listmonkService.TestConnectionAsync())
{
Message = "Íåò ïîäêëþ÷åíèÿ ê Listmonk";
IsSuccess = false;
return Page();
}
// Ñîçäàåì ñïèñîê
_logger.LogInformation($"Creating list: {listName}");
int listId = await _listmonkService.CreateListAsync(listName);
// Èìïîðòèðóåì
_logger.LogInformation($"Importing to list {listId}...");
await _listmonkService.ImportSubscribersAsync(new List<int> { listId }, Subscribers);
Message = $"Óñïåøíî çàãðóæåíî {Subscribers.Count} ïîäïèñ÷èêîâ â ñïèñîê \"{listName}\"";
IsSuccess = true;
_logger.LogInformation("=== Upload completed successfully ===");
}
catch (Exception ex)
{
Message = $"Îøèáêà: {ex.Message}";
IsSuccess = false;
_logger.LogError(ex, "=== Upload failed ===");
}
return Page();
}
private List<Subscriber> ReadExcelFile(IFormFile file)
{
var subscribers = new List<Subscriber>();
try
{
// Ñîçäà¸ì âðåìåííûé ôàéë ñ ïðàâèëüíûì ðàñøèðåíèåì .xlsx
var tempFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.xlsx");
_logger.LogInformation($"Temp file: {tempFilePath}");
try
{
// Ñîõðàíÿåì çàãðóæåííûé ôàéë âî âðåìåííûé ôàéë
using (var stream = new FileStream(tempFilePath, FileMode.Create))
{
file.CopyTo(stream);
}
_logger.LogInformation("Opening workbook...");
using (var workbook = new XLWorkbook(tempFilePath))
{
var worksheet = workbook.Worksheet(1);
var firstRow = worksheet.FirstRowUsed();
if (firstRow == null)
{
_logger.LogWarning("Empty file");
return subscribers;
}
// Çàãîëîâêè
var headers = new List<string>();
foreach (var cell in firstRow.Cells())
{
var header = cell.Value.ToString().Trim();
headers.Add(header);
_logger.LogInformation($"Header: {header}");
}
ColumnHeaders = headers;
_logger.LogInformation($"Total headers: {headers.Count}");
if (headers.Count < 2)
{
_logger.LogError("Need at least 2 columns");
return subscribers;
}
// Äàííûå
var lastRow = worksheet.LastRowUsed();
_logger.LogInformation($"Last row: {lastRow?.RowNumber() ?? 0}");
for (int row = 2; row <= lastRow.RowNumber(); row++)
{
try
{
var email = worksheet.Cell(row, 1).GetValue<string>().Trim();
if (string.IsNullOrWhiteSpace(email))
{
_logger.LogWarning($"Row {row}: empty email, skipping");
continue;
}
var name = worksheet.Cell(row, 2).GetValue<string>().Trim();
var attributes = new Dictionary<string, string>();
for (int col = 3; col <= headers.Count; col++)
{
var value = worksheet.Cell(row, col).GetValue<string>().Trim();
if (!string.IsNullOrWhiteSpace(value))
{
attributes[headers[col - 1]] = value;
}
}
subscribers.Add(new Subscriber
{
Email = email,
FullName = name,
Attributes = attributes
});
_logger.LogInformation($"Row {row}: Added {email}");
}
catch (Exception rowEx)
{
_logger.LogWarning(rowEx, $"Skipping row {row}");
}
}
}
}
finally
{
// Óäàëÿåì âðåìåííûé ôàéë
if (System.IO.File.Exists(tempFilePath))
{
try
{
System.IO.File.Delete(tempFilePath);
_logger.LogInformation($"Deleted temp file: {tempFilePath}");
}
catch (Exception ex)
{
_logger.LogWarning(ex, $"Failed to delete temp file: {tempFilePath}");
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error reading Excel");
throw;
}
return subscribers;
}
}
}

View File

@ -0,0 +1,235 @@
@page
@model ListmonkIntegration.Pages.Templates.CreateModel
@{
ViewData["Title"] = "Создание шаблона письма";
}
<h1>Создание шаблона письма</h1>
<hr />
@if (TempData["SuccessMessage"] != null)
{
<div class="alert alert-success">
@TempData["SuccessMessage"]
</div>
}
@if (TempData["ErrorMessage"] != null)
{
<div class="alert alert-danger">
@TempData["ErrorMessage"]
</div>
}
<div class="row">
<div class="col-md-8">
<form method="post">
<div class="mb-3">
<label class="form-label">Название шаблона</label>
<input type="text" asp-for="TemplateName" class="form-control" required placeholder="Например: Приветственное письмо" />
</div>
<div class="mb-3">
<label class="form-label">Тема письма</label>
<input type="text" asp-for="Subject" class="form-control" required placeholder="Например: Добро пожаловать, {{ .Subscriber.Name }}!" />
<div class="form-text">Можно использовать переменные: {{ .Subscriber.Name }}, {{ .Subscriber.Email }}, {{ .Subscriber.Attribs.ИмяАтрибута }}</div>
</div>
<div class="mb-3">
<label class="form-label">Выберите список рассылки (для просмотра атрибутов)</label>
<select asp-for="SelectedListId" class="form-select" asp-items="Model.Lists" id="listSelect">
<option value="">-- Выберите список --</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Текст письма</label>
<textarea asp-for="Body" id="editor" class="form-control" rows="15" placeholder="Введите текст письма здесь..."></textarea>
<div class="form-text">
Используйте редактор для форматирования текста. HTML код генерируется автоматически.
</div>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary">Создать шаблон</button>
<a asp-page="/Campaigns/Index" class="btn btn-secondary">Отмена</a>
</div>
</form>
</div>
<div class="col-md-4">
<!-- Кнопки для вставки переменных -->
<div class="card mb-3">
<div class="card-header">
<h5>Быстрая вставка переменных</h5>
</div>
<div class="card-body">
<div class="mb-2">
<label class="form-label small text-muted">Стандартные поля:</label>
<div class="btn-group-vertical w-100">
<button type="button" class="btn btn-sm btn-outline-primary mb-1" onclick="insertVariable('{{ .Subscriber.Name }}')">
Имя (Name)
</button>
<button type="button" class="btn btn-sm btn-outline-primary mb-1" onclick="insertVariable('{{ .Subscriber.Email }}')">
Email
</button>
</div>
</div>
<hr />
<div id="attributesButtons">
<label class="form-label small text-muted">Атрибуты из списка:</label>
<p class="text-muted small">Выберите список для загрузки атрибутов</p>
</div>
</div>
</div>
<!-- Примеры использования -->
<div class="card">
<div class="card-header">
<h5>Пример использования</h5>
</div>
<div class="card-body">
<small class="text-muted">
Переменные подставляются автоматически при отправке письма каждому получателю.
</small>
</div>
</div>
</div>
</div>
@section Scripts {
<script src="https://cdn.tiny.cloud/1/k6rorn68v4xqaesxvaroqlkyhfmncfoq8bxgxv3nd39szqrc/tinymce/8/tinymce.min.js" referrerpolicy="origin" crossorigin="anonymous"></script>
<script>
console.log('Script started');
// Глобальная переменная для хранения ссылки на редактор
window.tinymceEditor = null;
// Инициализация TinyMCE
tinymce.init({
selector: '#editor', // ИСПРАВЛЕНО: конкретный ID вместо всех textarea
api_key: 'k6rorn68v4xqaesxvaroqlkyhfmncfoq8bxgxv3nd39szqrc',
height: 400,
plugins: 'lists link table code bold italic underline',
toolbar: 'bold italic underline | h1 h2 h3 | bullist numlist | link unlink | code',
menubar: false,
statusbar: true,
branding: false,
content_style: 'body { font-family: Arial, sans-serif; font-size: 14px; }',
// ИСПРАВЛЕНО: добавлена setup функция для сохранения редактора
setup: function(editor) {
window.tinymceEditor = editor;
console.log('TinyMCE editor saved to window.tinymceEditor');
editor.on('change', function() {
tinymce.triggerSave();
});
},
init_instance_callback: function(editor) {
console.log('TinyMCE initialized successfully');
}
});
// Глобальная функция для вставки переменной
window.insertVariable = function(variable) {
console.log('insertVariable called with:', variable);
try {
// Проверяем, существует ли редактор
if (window.tinymceEditor && !window.tinymceEditor.destroyed) {
// Вставляем в TinyMCE
window.tinymceEditor.insertContent(variable);
window.tinymceEditor.focus();
console.log('✓ Inserted into TinyMCE editor');
} else if (window.tinymce && window.tinymce.editors.length > 0) {
// Альтернативный способ - берём первый редактор
var editor = window.tinymce.editors[0];
editor.insertContent(variable);
editor.focus();
console.log('✓ Inserted via tinymce.editors');
} else {
// Если TinyMCE не инициализирован, вставляем в textarea
var textarea = document.querySelector('textarea[name="Body"]');
if (textarea) {
var start = textarea.selectionStart || 0;
var end = textarea.selectionEnd || 0;
var text = textarea.value;
textarea.value = text.substring(0, start) + variable + text.substring(end);
textarea.focus();
console.log('✓ Inserted into textarea (TinyMCE not ready)');
} else {
console.error('✗ Textarea not found');
}
}
} catch (error) {
console.error('✗ Error inserting variable:', error);
}
};
console.log('Script loaded, waiting for DOM...');
// Загрузка атрибутов при выборе списка
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM loaded');
const listSelect = document.getElementById('listSelect');
if (listSelect) {
listSelect.addEventListener('change', async function() {
const listId = this.value;
const attributesDiv = document.getElementById('attributesButtons');
console.log('List selected, ID:', listId);
if (listId) {
attributesDiv.innerHTML = '<label class="form-label small text-muted">Атрибуты из списка:</label><div class="text-center"><div class="spinner-border spinner-border-sm" role="status"><span class="visually-hidden">Загрузка...</span></div></div>';
try {
const response = await fetch(`/api/lists/${listId}/attributes`);
console.log('API response status:', response.status);
if (response.ok) {
const attributes = await response.json();
console.log('Attributes loaded:', attributes);
displayAttributeButtons(attributes);
} else {
attributesDiv.innerHTML = '<label class="form-label small text-muted">Атрибуты из списка:</label><p class="text-danger small">Ошибка загрузки атрибутов.</p>';
}
} catch (error) {
console.error('Error loading attributes:', error);
attributesDiv.innerHTML = '<label class="form-label small text-muted">Атрибуты из списка:</label><p class="text-danger small">Ошибка загрузки атрибутов.</p>';
}
} else {
attributesDiv.innerHTML = '<label class="form-label small text-muted">Атрибуты из списка:</label><p class="text-muted small">Выберите список для загрузки атрибутов</p>';
}
});
}
});
// Отображение кнопок для атрибутов
window.displayAttributeButtons = function(attributes) {
console.log('displayAttributeButtons called with:', attributes);
const attributesDiv = document.getElementById('attributesButtons');
if (attributes && attributes.length > 0) {
let html = '<label class="form-label small text-muted">Атрибуты из списка:</label><div class="d-flex flex-wrap gap-1">';
attributes.forEach(attr => {
const variable = `{{ .Subscriber.Attribs.${attr} }}`;
console.log('Creating button for attr:', attr, 'variable:', variable);
// Экранируем специальные символы для onclick
const escapedVar = variable.replace(/'/g, "\\'").replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
html += `<button type="button" class="btn btn-sm btn-outline-secondary m-1" onclick="insertVariable('${escapedVar}')">
${attr}
</button>`;
});
html += '</div>';
attributesDiv.innerHTML = html;
console.log('Buttons created');
} else {
attributesDiv.innerHTML = '<label class="form-label small text-muted">Атрибуты из списка:</label><p class="text-muted small">У выбранного списка нет пользовательских атрибутов.</p>';
}
};
console.log('All scripts initialized');
</script>
}

View File

@ -0,0 +1,99 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using ListmonkIntegration.Services;
using ListmonkIntegration.Models;
namespace ListmonkIntegration.Pages.Templates
{
public class CreateModel : PageModel
{
private readonly IListmonkService _listmonkService;
private readonly ILogger<CreateModel> _logger;
[BindProperty]
public string TemplateName { get; set; } = string.Empty;
[BindProperty]
public string Subject { get; set; } = string.Empty;
[BindProperty]
public string Body { get; set; } = string.Empty;
[BindProperty]
public int? SelectedListId { get; set; }
public SelectList Lists { get; set; } = new SelectList(Enumerable.Empty<SelectListItem>());
public string? DebugInfo { get; set; }
public CreateModel(IListmonkService listmonkService, ILogger<CreateModel> logger)
{
_listmonkService = listmonkService;
_logger = logger;
}
public async Task OnGetAsync()
{
_logger.LogInformation("OnGetAsync called, loading lists...");
await LoadListsAsync();
}
public async Task<IActionResult> OnPostAsync()
{
if (string.IsNullOrWhiteSpace(TemplateName) || string.IsNullOrWhiteSpace(Subject) || string.IsNullOrWhiteSpace(Body))
{
TempData["ErrorMessage"] = "Çàïîëíèòå âñå îáÿçàòåëüíûå ïîëÿ";
await LoadListsAsync();
return Page();
}
try
{
_logger.LogInformation($"Creating template: {TemplateName}");
var templateId = await _listmonkService.CreateTemplateAsync(
TemplateName,
Subject,
Body
);
_logger.LogInformation($"Template created successfully with ID: {templateId}");
TempData["SuccessMessage"] = $"Øàáëîí \"{TemplateName}\" óñïåøíî ñîçäàí!";
return RedirectToPage("/Campaigns/Index");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating template");
TempData["ErrorMessage"] = $"Îøèáêà ïðè ñîçäàíèè øàáëîíà: {ex.Message}";
await LoadListsAsync();
return Page();
}
}
private async Task LoadListsAsync()
{
try
{
_logger.LogInformation("Calling GetListsAsync...");
var lists = await _listmonkService.GetListsAsync();
_logger.LogInformation($"Got {lists.Count} lists from Listmonk");
foreach (var list in lists)
{
_logger.LogInformation($" List: ID={list.Id}, Name={list.Name}, Subscribers={list.SubscriberCount}");
}
Lists = new SelectList(lists, "Id", "Name");
DebugInfo = $"Çàãðóæåíî ñïèñêîâ: {lists.Count}";
}
catch (Exception ex)
{
_logger.LogError(ex, "Error loading lists");
DebugInfo = $"Îøèáêà çàãðóçêè ñïèñêîâ: {ex.Message}";
Lists = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
}
}

View File

@ -0,0 +1,3 @@
@using ListmonkIntegration
@namespace ListmonkIntegration.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@ -0,0 +1,4 @@
@page
@model ListmonkIntegration.Pages.api.ListsModel
@{
}

View File

@ -0,0 +1,35 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc;
using ListmonkIntegration.Services;
namespace ListmonkIntegration.Pages.api
{
[IgnoreAntiforgeryToken]
public class ListsModel : PageModel
{
private readonly IListmonkService _listmonkService;
private readonly ILogger<ListsModel> _logger;
public ListsModel(IListmonkService listmonkService, ILogger<ListsModel> logger)
{
_listmonkService = listmonkService;
_logger = logger;
}
public async Task<IActionResult> OnGetAttributesAsync(int id)
{
try
{
_logger.LogInformation($"API: Getting attributes for list {id}");
var attributes = await _listmonkService.GetListAttributesAsync(id);
_logger.LogInformation($"API: Found {attributes.Count} attributes");
return new JsonResult(attributes);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting attributes");
return new JsonResult(new List<string>()) { StatusCode = 500 };
}
}
}
}

View File

@ -0,0 +1,79 @@
using ListmonkIntegration.Models;
using ListmonkIntegration.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// Ãëîáàëüíûé îáðàáîò÷èê íåîáðàáîòàííûõ èñêëþ÷åíèé
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
var exception = args.ExceptionObject as Exception;
Console.WriteLine($"[CRITICAL] Unhandled exception: {exception?.Message}");
Console.WriteLine($"[CRITICAL] Stack trace: {exception?.StackTrace}");
if (exception?.InnerException != null)
{
Console.WriteLine($"[CRITICAL] Inner exception: {exception.InnerException.Message}");
}
};
// Äîáàâëÿåì ñåðâèñû Razor Pages
builder.Services.AddRazorPages();
// Íàñòðîéêà HttpClient
builder.Services.AddHttpClient();
// ×òåíèå íàñòðîåê èç appsettings.json
builder.Services.Configure<ListmonkSettings>(
builder.Configuration.GetSection("Listmonk"));
// Ðåãèñòðàöèÿ ñåðâèñà Listmonk
builder.Services.AddSingleton<IListmonkService>(sp =>
{
var httpClientFactory = sp.GetRequiredService<IHttpClientFactory>();
var settings = sp.GetRequiredService<IOptions<ListmonkSettings>>().Value;
var logger = sp.GetRequiredService<ILogger<ListmonkService>>();
var httpClient = httpClientFactory.CreateClient();
return new ListmonkService(httpClient, settings, logger);
});
var app = builder.Build();
// Íàñòðîéêà êîíâåéåðà HTTP-çàïðîñîâ
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapGet("/api/templates/{id}/preview", async (int id, IListmonkService service, ILogger<Program> logger) =>
{
logger.LogInformation($"API: Getting template {id} preview");
var body = await service.GetTemplateBodyAsync(id);
return Results.Json(new { body });
});
// Êàñòîìíûé ìàðøðóò äëÿ API àòðèáóòîâ
// API endpoint äëÿ ïîëó÷åíèÿ àòðèáóòîâ ñïèñêà
app.MapGet("/api/lists/{id}/attributes", async (int id, IListmonkService service, ILogger<Program> logger) =>
{
logger.LogInformation($"API: Getting attributes for list {id}");
try
{
var attributes = await service.GetListAttributesAsync(id);
logger.LogInformation($"API: Found {attributes.Count} attributes");
return Results.Json(attributes);
}
catch (Exception ex)
{
logger.LogError(ex, "Error getting attributes");
return Results.Json(new List<string>(), statusCode: 500);
}
});
app.MapRazorPages();
app.Run();

View File

@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:32816",
"sslPort": 44391
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5033",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7001;http://localhost:5033",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,22 @@
using ListmonkIntegration.Models;
using TemplateInfo = ListmonkIntegration.Models.TemplateInfo;
namespace ListmonkIntegration.Services
{
public interface IListmonkService
{
Task<bool> TestConnectionAsync();
Task<int> CreateListAsync(string listName);
Task<int> CreateTemplateAsync(string name, string subject, string body);
Task<int> CreateCampaignAsync(string name, int listId, int templateId, string subject);
Task<bool> StartCampaignAsync(int campaignId);
Task<List<ListInfo>> GetListsAsync();
Task<List<string>> GetListAttributesAsync(int listId);
Task<List<TemplateInfo>> GetTemplatesAsync();
Task<string> GetTemplateBodyAsync(int templateId);
Task<Subscriber?> GetSubscriberByEmailAsync(string email);
Task<bool> UpdateSubscriberAsync(int subscriberId, string email, string name, Dictionary<string, string> attributes, List<int> listIds);
Task<bool> ImportSubscribersAsync(List<int> listIds, List<Subscriber> subscribers);
}
}

View File

@ -0,0 +1,811 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using ListmonkIntegration.Models;
using TemplateInfo = ListmonkIntegration.Models.TemplateInfo;
namespace ListmonkIntegration.Services
{
public class ListmonkService : IListmonkService
{
private readonly HttpClient _httpClient;
private readonly ListmonkSettings _settings;
private readonly ILogger<ListmonkService> _logger;
public ListmonkService(
HttpClient httpClient,
ListmonkSettings settings,
ILogger<ListmonkService> logger)
{
_httpClient = httpClient;
_settings = settings;
_logger = logger;
// Настройка базового адреса
_httpClient.BaseAddress = new Uri(_settings.BaseUrl);
// Listmonk использует Basic Auth с API credentials
// Username: логин пользователя (например, "admin")
// Password: API токен (d1qPRY5jl1LsD1LskI4zWu4ukYWTyNLxjot05CjgRin4nQy3)
var username = _settings.Username;
var password = !string.IsNullOrEmpty(_settings.ApiToken)
? _settings.ApiToken
: _settings.Password;
var authToken = Convert.ToBase64String(
Encoding.ASCII.GetBytes($"{username}:{password}"));
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", authToken);
_logger.LogInformation($"Using Basic Auth with username: {username}");
}
public async Task<bool> TestConnectionAsync()
{
try
{
_logger.LogInformation($"Testing connection to Listmonk...");
_logger.LogInformation($"Base URL: {_settings.BaseUrl}");
_logger.LogInformation($"Username: {_settings.Username}");
var response = await _httpClient.GetAsync("/api/config");
_logger.LogInformation($"Response status: {response.StatusCode}");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Success! Connected to Listmonk");
return true;
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogWarning($"Failed! Status: {response.StatusCode}, Content: {errorContent}");
return false;
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"Exception during connection test: {ex.Message}");
return false;
}
}
public async Task<int> CreateListAsync(string listName)
{
_logger.LogInformation($"Creating list: {listName}");
// Сначала проверим, нет ли уже списка с таким именем
var existingListId = await FindListIdByNameAsync(listName);
if (existingListId.HasValue)
{
_logger.LogInformation($"List '{listName}' already exists with ID {existingListId.Value}");
return existingListId.Value;
}
var content = new StringContent(
JsonSerializer.Serialize(new
{
name = listName,
type = "private",
optin = "single"
}),
Encoding.UTF8,
"application/json");
var response = await _httpClient.PostAsync("/api/lists", content);
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Create list response: {responseBody}");
response.EnsureSuccessStatusCode();
var json = JsonDocument.Parse(responseBody);
// Listmonk возвращает {"data": {"id": 1, ...}}
var listId = json.RootElement
.GetProperty("data")
.GetProperty("id")
.GetInt32();
_logger.LogInformation($"List created with ID: {listId}");
return listId;
}
private async Task<int?> FindListIdByNameAsync(string listName)
{
try
{
var response = await _httpClient.GetAsync("/api/lists");
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Lists response: {responseBody.Substring(0, Math.Min(200, responseBody.Length))}...");
var json = JsonDocument.Parse(responseBody);
// Структура: {"data": {"results": [...]}}
if (json.RootElement.TryGetProperty("data", out var data))
{
JsonElement results;
if (data.ValueKind == JsonValueKind.Object &&
data.TryGetProperty("results", out results))
{
if (results.ValueKind == JsonValueKind.Array)
{
foreach (var list in results.EnumerateArray())
{
var name = list.GetProperty("name").GetString();
if (name == listName)
{
var id = list.GetProperty("id").GetInt32();
_logger.LogInformation($"Found existing list '{listName}' with ID {id}");
return id;
}
}
}
}
else if (data.ValueKind == JsonValueKind.Array)
{
foreach (var list in data.EnumerateArray())
{
var name = list.GetProperty("name").GetString();
if (name == listName)
{
var id = list.GetProperty("id").GetInt32();
return id;
}
}
}
}
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, $"Error searching for list '{listName}'");
}
return null;
}
public async Task<bool> ImportSubscribersAsync(List<int> listIds, List<Subscriber> subscribers)
{
_logger.LogInformation($"Importing {subscribers.Count} subscribers to lists: {string.Join(", ", listIds)}");
int successCount = 0;
int failCount = 0;
int updatedCount = 0;
int createdCount = 0;
foreach (var sub in subscribers)
{
try
{
// Проверяем, существует ли подписчик
var existingSubscriber = await GetSubscriberByEmailAsync(sub.Email);
if (existingSubscriber != null)
{
// Подписчик существует - обновляем его
_logger.LogInformation($"Subscriber {sub.Email} exists, updating...");
// Получаем ID существующего подписчика
var subscriberId = await GetSubscriberIdByEmailAsync(sub.Email);
if (subscriberId.HasValue)
{
// Получаем текущие списки подписчика
var currentListIds = await GetSubscriberListIdsAsync(subscriberId.Value);
// Добавляем новые списки к существующим
var allListIds = new List<int>(currentListIds);
foreach (var listId in listIds)
{
if (!allListIds.Contains(listId))
{
allListIds.Add(listId);
}
}
// Объединяем атрибуты
var mergedAttributes = new Dictionary<string, string>(existingSubscriber.Attributes);
foreach (var attr in sub.Attributes)
{
mergedAttributes[attr.Key] = attr.Value;
}
// Обновляем подписчика
var updated = await UpdateSubscriberAsync(
subscriberId.Value,
sub.Email,
sub.FullName,
mergedAttributes,
allListIds
);
if (updated)
{
updatedCount++;
successCount++;
}
else
{
failCount++;
}
}
else
{
failCount++;
}
}
else
{
// Создаём нового подписчика
await AddSubscriberToList(listIds, sub);
createdCount++;
successCount++;
}
}
catch (Exception ex)
{
failCount++;
_logger.LogWarning(ex, $"Failed to process subscriber {sub.Email}");
}
}
_logger.LogInformation($"Import completed: {successCount} success ({createdCount} created, {updatedCount} updated), {failCount} failed");
return true;
}
private async Task<List<int>> GetSubscriberListIdsAsync(int subscriberId)
{
try
{
var response = await _httpClient.GetAsync($"/api/subscribers/{subscriberId}");
if (!response.IsSuccessStatusCode)
return new List<int>();
var responseBody = await response.Content.ReadAsStringAsync();
var json = JsonDocument.Parse(responseBody);
var listIds = new List<int>();
if (json.RootElement.TryGetProperty("data", out var data))
{
if (data.TryGetProperty("lists", out var lists))
{
foreach (var list in lists.EnumerateArray())
{
if (list.TryGetProperty("id", out var id))
{
listIds.Add(id.GetInt32());
}
}
}
}
return listIds;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error getting list IDs for subscriber {subscriberId}");
return new List<int>();
}
}
private async Task AddSubscriberToList(List<int> listIds, Subscriber subscriber)
{
var subscriberData = new
{
email = subscriber.Email,
name = subscriber.FullName,
lists = listIds, // Массив ID списков
attribs = subscriber.Attributes,
status = "enabled",
mode = "subscribe"
};
var jsonContent = JsonSerializer.Serialize(subscriberData);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/api/subscribers", content);
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogWarning($"Failed to add subscriber {subscriber.Email}: {response.StatusCode} - {errorContent}");
throw new Exception($"Failed to add subscriber: {errorContent}");
}
}
public async Task<bool> CreateCampaignAsync(string name, int listId, int templateId)
{
var content = new StringContent(
JsonSerializer.Serialize(new
{
name = name,
subject = "Тема письма",
lists = new[] { listId },
template_id = templateId,
type = "regular",
content_type = "html"
}),
Encoding.UTF8,
"application/json");
var response = await _httpClient.PostAsync("/api/campaigns", content);
return response.IsSuccessStatusCode;
}
public async Task<List<ListInfo>> GetListsAsync()
{
_logger.LogInformation("Fetching lists from Listmonk");
var response = await _httpClient.GetAsync("/api/lists");
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync();
_logger.LogError($"Failed to fetch lists: {response.StatusCode} - {errorContent}");
throw new Exception($"Failed to fetch lists: {response.StatusCode}");
}
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Raw response: {responseBody.Substring(0, Math.Min(500, responseBody.Length))}");
var json = JsonDocument.Parse(responseBody);
var lists = new List<ListInfo>();
// Структура: {"data": {"results": [...]}}
if (json.RootElement.TryGetProperty("data", out var data))
{
if (data.ValueKind == JsonValueKind.Object &&
data.TryGetProperty("results", out var results))
{
if (results.ValueKind == JsonValueKind.Array)
{
foreach (var list in results.EnumerateArray())
{
var listInfo = new ListInfo
{
Id = list.GetProperty("id").GetInt32(),
Name = list.GetProperty("name").GetString() ?? string.Empty,
SubscriberCount = list.TryGetProperty("subscriber_count", out var countProp)
? countProp.GetInt32()
: 0
};
lists.Add(listInfo);
_logger.LogInformation($"Parsed list: ID={listInfo.Id}, Name={listInfo.Name}, Subscribers={listInfo.SubscriberCount}");
}
}
}
else if (data.ValueKind == JsonValueKind.Array)
{
// На случай, если Listmonk вернёт массив напрямую
foreach (var list in data.EnumerateArray())
{
var listInfo = new ListInfo
{
Id = list.GetProperty("id").GetInt32(),
Name = list.GetProperty("name").GetString() ?? string.Empty,
SubscriberCount = list.TryGetProperty("subscriber_count", out var countProp)
? countProp.GetInt32()
: 0
};
lists.Add(listInfo);
}
}
}
_logger.LogInformation($"Total lists found: {lists.Count}");
return lists;
}
public async Task<List<string>> GetListAttributesAsync(int listId)
{
_logger.LogInformation($"Fetching attributes for list {listId}");
// Получаем ТОЛЬКО подписчиков из конкретного списка
var response = await _httpClient.GetAsync($"/api/subscribers?list_id={listId}&per_page=1000");
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning($"Failed to fetch subscribers for list {listId}: {response.StatusCode}");
return new List<string>();
}
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Subscribers response for list {listId}: {responseBody.Substring(0, Math.Min(500, responseBody.Length))}");
var json = JsonDocument.Parse(responseBody);
var attributes = new HashSet<string>();
// Структура: {"data": {"results": [...]}}
if (json.RootElement.TryGetProperty("data", out var data))
{
JsonElement results;
if (data.ValueKind == JsonValueKind.Object && data.TryGetProperty("results", out results))
{
if (results.ValueKind == JsonValueKind.Array)
{
foreach (var subscriber in results.EnumerateArray())
{
if (subscriber.TryGetProperty("attribs", out var attribs))
{
foreach (var prop in attribs.EnumerateObject())
{
attributes.Add(prop.Name);
_logger.LogDebug($"Found attribute '{prop.Name}' for list {listId}");
}
}
}
}
}
else if (data.ValueKind == JsonValueKind.Array)
{
foreach (var subscriber in data.EnumerateArray())
{
if (subscriber.TryGetProperty("attribs", out var attribs))
{
foreach (var prop in attribs.EnumerateObject())
{
attributes.Add(prop.Name);
}
}
}
}
}
var result = attributes.ToList();
_logger.LogInformation($"Found {result.Count} unique attributes for list {listId}: {string.Join(", ", result)}");
return result;
}
public async Task<int> CreateTemplateAsync(string name, string subject, string body)
{
_logger.LogInformation($"Creating template: {name}");
// Listmonk требует плейсхолдер {{ template "content" . }} в теле шаблона
// Если его нет — добавляем автоматически
if (!body.Contains("{{ template \"content\" . }}"))
{
body = body.TrimEnd() + "\n\n{{ template \"content\" . }}";
_logger.LogInformation("Added required placeholder to template body");
}
var templateData = new
{
name = name,
subject = subject,
body = body,
type = "campaign"
};
var jsonContent = JsonSerializer.Serialize(templateData);
_logger.LogInformation($"Request body: {jsonContent}");
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/api/templates", content);
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Response status: {response.StatusCode}");
_logger.LogInformation($"Response body: {responseBody}");
if (!response.IsSuccessStatusCode)
{
_logger.LogError($"Failed to create template: {response.StatusCode} - {responseBody}");
throw new Exception($"Failed to create template: {responseBody}");
}
var json = JsonDocument.Parse(responseBody);
int templateId;
if (json.RootElement.TryGetProperty("data", out var data))
{
templateId = data.GetProperty("id").GetInt32();
}
else
{
templateId = json.RootElement.GetProperty("id").GetInt32();
}
_logger.LogInformation($"Template created with ID: {templateId}");
return templateId;
}
public async Task<List<TemplateInfo>> GetTemplatesAsync()
{
_logger.LogInformation("Fetching templates from Listmonk");
var response = await _httpClient.GetAsync("/api/templates");
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
_logger.LogError($"Failed to fetch templates: {response.StatusCode} - {error}");
return new List<TemplateInfo>();
}
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Templates response: {responseBody.Substring(0, Math.Min(500, responseBody.Length))}");
var json = JsonDocument.Parse(responseBody);
var templates = new List<TemplateInfo>();
if (json.RootElement.TryGetProperty("data", out var data))
{
JsonElement results;
if (data.ValueKind == JsonValueKind.Object && data.TryGetProperty("results", out results))
{
if (results.ValueKind == JsonValueKind.Array)
{
foreach (var template in results.EnumerateArray())
{
templates.Add(new TemplateInfo
{
Id = template.GetProperty("id").GetInt32(),
Name = template.GetProperty("name").GetString() ?? string.Empty,
Subject = template.TryGetProperty("subject", out var subj)
? subj.GetString() ?? string.Empty
: string.Empty
});
}
}
}
else if (data.ValueKind == JsonValueKind.Array)
{
foreach (var template in data.EnumerateArray())
{
templates.Add(new TemplateInfo
{
Id = template.GetProperty("id").GetInt32(),
Name = template.GetProperty("name").GetString() ?? string.Empty,
Subject = template.TryGetProperty("subject", out var subj)
? subj.GetString() ?? string.Empty
: string.Empty
});
}
}
}
_logger.LogInformation($"Found {templates.Count} templates");
return templates;
}
public async Task<string> GetTemplateBodyAsync(int templateId)
{
_logger.LogInformation($"Fetching template {templateId}");
var response = await _httpClient.GetAsync($"/api/templates/{templateId}");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var json = JsonDocument.Parse(responseBody);
if (json.RootElement.TryGetProperty("data", out var data))
{
if (data.TryGetProperty("body", out var body))
{
return body.GetString() ?? string.Empty;
}
}
return string.Empty;
}
public async Task<int> CreateCampaignAsync(string name, int listId, int templateId, string subject)
{
_logger.LogInformation($"Creating campaign: {name}");
_logger.LogInformation($"List ID: {listId}, Template ID: {templateId}, Subject: {subject}");
// Убираем send_at - кампания создастся как черновик, потом запустим отдельно
var campaignData = new
{
name = name,
subject = subject,
lists = new[] { listId },
template_id = templateId,
type = "regular",
content_type = "html",
messenger = "email"
};
var jsonContent = JsonSerializer.Serialize(campaignData);
_logger.LogInformation($"Request body: {jsonContent}");
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/api/campaigns", content);
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Response status: {response.StatusCode}");
_logger.LogInformation($"Response body: {responseBody}");
if (!response.IsSuccessStatusCode)
{
_logger.LogError($"Failed to create campaign: {response.StatusCode} - {responseBody}");
throw new Exception($"Failed to create campaign: {responseBody}");
}
var json = JsonDocument.Parse(responseBody);
int campaignId;
if (json.RootElement.TryGetProperty("data", out var data))
{
campaignId = data.GetProperty("id").GetInt32();
}
else
{
campaignId = json.RootElement.GetProperty("id").GetInt32();
}
_logger.LogInformation($"Campaign created with ID: {campaignId}");
return campaignId;
}
public async Task<bool> StartCampaignAsync(int campaignId)
{
_logger.LogInformation($"Starting campaign {campaignId}");
var statusData = new
{
status = "running"
};
var jsonContent = JsonSerializer.Serialize(statusData);
_logger.LogInformation($"Request body: {jsonContent}");
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// ВАЖНО: PUT, не POST!
var request = new HttpRequestMessage(HttpMethod.Put, $"/api/campaigns/{campaignId}/status")
{
Content = content
};
var response = await _httpClient.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Response status: {response.StatusCode}");
_logger.LogInformation($"Response body: {responseBody}");
if (!response.IsSuccessStatusCode)
{
_logger.LogError($"Failed to start campaign: {response.StatusCode} - {responseBody}");
return false;
}
_logger.LogInformation($"Campaign {campaignId} started successfully");
return true;
}
public async Task<Subscriber?> GetSubscriberByEmailAsync(string email)
{
_logger.LogInformation($"Searching for subscriber by email: {email}");
try
{
// Ищем подписчика по email
var response = await _httpClient.GetAsync($"/api/subscribers?query=LOWER(email)=LOWER('{email}')&per_page=1");
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning($"Failed to search subscriber: {response.StatusCode}");
return null;
}
var responseBody = await response.Content.ReadAsStringAsync();
var json = JsonDocument.Parse(responseBody);
if (json.RootElement.TryGetProperty("data", out var data))
{
JsonElement results;
if (data.ValueKind == JsonValueKind.Object && data.TryGetProperty("results", out results))
{
if (results.ValueKind == JsonValueKind.Array && results.GetArrayLength() > 0)
{
var subscriberData = results[0];
// Парсим атрибуты
var attributes = new Dictionary<string, string>();
if (subscriberData.TryGetProperty("attribs", out var attribs))
{
foreach (var prop in attribs.EnumerateObject())
{
attributes[prop.Name] = prop.Value.GetString() ?? string.Empty;
}
}
// Получаем списки
var listIds = new List<int>();
if (subscriberData.TryGetProperty("lists", out var lists))
{
foreach (var list in lists.EnumerateArray())
{
if (list.TryGetProperty("id", out var id))
{
listIds.Add(id.GetInt32());
}
}
}
return new Subscriber
{
Email = subscriberData.GetProperty("email").GetString() ?? string.Empty,
FullName = subscriberData.GetProperty("name").GetString() ?? string.Empty,
Attributes = attributes
};
}
}
}
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error searching subscriber {email}");
return null;
}
}
public async Task<bool> UpdateSubscriberAsync(int subscriberId, string email, string name, Dictionary<string, string> attributes, List<int> listIds)
{
_logger.LogInformation($"Updating subscriber {subscriberId} ({email})");
var updateData = new
{
email = email,
name = name,
attribs = attributes,
lists = listIds,
status = "enabled"
};
var jsonContent = JsonSerializer.Serialize(updateData);
_logger.LogInformation($"Update data: {jsonContent}");
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync($"/api/subscribers/{subscriberId}", content);
var responseBody = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Update response: {response.StatusCode} - {responseBody}");
return response.IsSuccessStatusCode;
}
private async Task<int?> GetSubscriberIdByEmailAsync(string email)
{
try
{
var response = await _httpClient.GetAsync($"/api/subscribers?query=LOWER(email)=LOWER('{email}')&per_page=1");
if (!response.IsSuccessStatusCode)
return null;
var responseBody = await response.Content.ReadAsStringAsync();
var json = JsonDocument.Parse(responseBody);
if (json.RootElement.TryGetProperty("data", out var data))
{
JsonElement results;
if (data.ValueKind == JsonValueKind.Object && data.TryGetProperty("results", out results))
{
if (results.ValueKind == JsonValueKind.Array && results.GetArrayLength() > 0)
{
return results[0].GetProperty("id").GetInt32();
}
}
}
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error getting subscriber ID for {email}");
return null;
}
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"ListmonkIntegration": "Debug"
}
}
}

View File

@ -0,0 +1,15 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Listmonk": {
"BaseUrl": "http://localhost:9000",
"Username": "admin",
"Password": "W6N-jXV-Sna-Vxv",
"ApiToken": "mOSPkAQ2tCK3icXCIimjoK4KicDf3Y7A8AXSuenRnSWW6cT4"
}
}

View File

@ -0,0 +1,22 @@
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus {
box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb;
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -0,0 +1,4 @@
// Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2011-2021 Twitter, Inc.
Copyright (c) 2011-2021 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,427 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-left: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr /* rtl:ignore */;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: left;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: left;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: left;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
/* rtl:raw:
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.css.map */

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,8 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;background-color:currentColor;border:0;opacity:.25}hr:not([size]){height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[data-bs-original-title],abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-left:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.2em;background-color:#fcf8e3}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#0d6efd;text-decoration:underline}a:hover{color:#0a58ca}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em;direction:ltr;unicode-bidi:bidi-override}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:#d63384;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:.875em;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:1em;font-weight:700}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:#6c757d;text-align:left}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]::-webkit-calendar-picker-indicator{display:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:left;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:left}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important}
/*# sourceMappingURL=bootstrap-reboot.min.css.map */

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,424 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-right: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-right: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr ;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: right;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: right;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: right;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.rtl.css.map */

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,8 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;background-color:currentColor;border:0;opacity:.25}hr:not([size]){height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[data-bs-original-title],abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-right:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-right:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.2em;background-color:#fcf8e3}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#0d6efd;text-decoration:underline}a:hover{color:#0a58ca}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em;direction:ltr;unicode-bidi:bidi-override}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:#d63384;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:.875em;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:1em;font-weight:700}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:#6c757d;text-align:right}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]::-webkit-calendar-picker-indicator{display:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:right;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:right}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}[type=email],[type=number],[type=tel],[type=url]{direction:ltr}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important}
/*# sourceMappingURL=bootstrap-reboot.rtl.min.css.map */

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,23 @@
The MIT License (MIT)
Copyright (c) .NET Foundation and Contributors
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,435 @@
/**
* @license
* Unobtrusive validation support library for jQuery and jQuery Validate
* Copyright (c) .NET Foundation. All rights reserved.
* Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
* @version v4.0.0
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define("jquery.validate.unobtrusive", ['jquery-validation'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports
module.exports = factory(require('jquery-validation'));
} else {
// Browser global
jQuery.validator.unobtrusive = factory(jQuery);
}
}(function ($) {
var $jQval = $.validator,
adapters,
data_validation = "unobtrusiveValidation";
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
function splitAndTrim(value) {
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
}
function escapeAttributeValue(value) {
// As mentioned on http://api.jquery.com/category/selectors/
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
}
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}
function onErrors(event, validator) { // 'this' is the form element
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
function onSuccess(error) { // 'this' is the form element
var container = error.data("unobtrusiveContainer");
if (container) {
var replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
container.addClass("field-validation-valid").removeClass("field-validation-error");
error.removeData("unobtrusiveContainer");
if (replace) {
container.empty();
}
}
}
function onReset(event) { // 'this' is the form element
var $form = $(this),
key = '__jquery_unobtrusive_validation_form_reset';
if ($form.data(key)) {
return;
}
// Set a flag that indicates we're currently resetting the form.
$form.data(key, true);
try {
$form.data("validator").resetForm();
} finally {
$form.removeData(key);
}
$form.find(".validation-summary-errors")
.addClass("validation-summary-valid")
.removeClass("validation-summary-errors");
$form.find(".field-validation-error")
.addClass("field-validation-valid")
.removeClass("field-validation-error")
.removeData("unobtrusiveContainer")
.find(">*") // If we were using valmsg-replace, get the underlying error
.removeData("unobtrusiveContainer");
}
function validationInfo(form) {
var $form = $(form),
result = $form.data(data_validation),
onResetProxy = $.proxy(onReset, form),
defaultOptions = $jQval.unobtrusive.options || {},
execInContext = function (name, args) {
var func = defaultOptions[name];
func && $.isFunction(func) && func.apply(form, args);
};
if (!result) {
result = {
options: { // options structure passed to jQuery Validate's validate() method
errorClass: defaultOptions.errorClass || "input-validation-error",
errorElement: defaultOptions.errorElement || "span",
errorPlacement: function () {
onError.apply(form, arguments);
execInContext("errorPlacement", arguments);
},
invalidHandler: function () {
onErrors.apply(form, arguments);
execInContext("invalidHandler", arguments);
},
messages: {},
rules: {},
success: function () {
onSuccess.apply(form, arguments);
execInContext("success", arguments);
}
},
attachValidation: function () {
$form
.off("reset." + data_validation, onResetProxy)
.on("reset." + data_validation, onResetProxy)
.validate(this.options);
},
validate: function () { // a validation function that is called by unobtrusive Ajax
$form.validate();
return $form.valid();
}
};
$form.data(data_validation, result);
}
return result;
}
$jQval.unobtrusive = {
adapters: [],
parseElement: function (element, skipAttach) {
/// <summary>
/// Parses a single HTML element for unobtrusive validation attributes.
/// </summary>
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
/// validation to the form. If parsing just this single element, you should specify true.
/// If parsing several elements, you should specify false, and manually attach the validation
/// to the form when you are finished. The default is false.</param>
var $element = $(element),
form = $element.parents("form")[0],
valInfo, rules, messages;
if (!form) { // Cannot do client-side validation without a form
return;
}
valInfo = validationInfo(form);
valInfo.options.rules[element.name] = rules = {};
valInfo.options.messages[element.name] = messages = {};
$.each(this.adapters, function () {
var prefix = "data-val-" + this.name,
message = $element.attr(prefix),
paramValues = {};
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
prefix += "-";
$.each(this.params, function () {
paramValues[this] = $element.attr(prefix + this);
});
this.adapt({
element: element,
form: form,
message: message,
params: paramValues,
rules: rules,
messages: messages
});
}
});
$.extend(rules, { "__dummy__": true });
if (!skipAttach) {
valInfo.attachValidation();
}
},
parse: function (selector) {
/// <summary>
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
/// attribute values.
/// </summary>
/// <param name="selector" type="String">Any valid jQuery selector.</param>
// $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
// element with data-val=true
var $selector = $(selector),
$forms = $selector.parents()
.addBack()
.filter("form")
.add($selector.find("form"))
.has("[data-val=true]");
$selector.find("[data-val=true]").each(function () {
$jQval.unobtrusive.parseElement(this, true);
});
$forms.each(function () {
var info = validationInfo(this);
if (info) {
info.attachValidation();
}
});
}
};
adapters = $jQval.unobtrusive.adapters;
adapters.add = function (adapterName, params, fn) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
/// mmmm is the parameter name).</param>
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
/// attributes into jQuery Validate rules and/or messages.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
if (!fn) { // Called with no params, just a function
fn = params;
params = [];
}
this.push({ name: adapterName, params: params, adapt: fn });
return this;
};
adapters.addBool = function (adapterName, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has no parameter values.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, function (options) {
setValidationValues(options, ruleName || adapterName, true);
});
};
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a minimum value.</param>
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a maximum value.</param>
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
/// have both a minimum and maximum value.</param>
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the minimum value. The default is "min".</param>
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the maximum value. The default is "max".</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
var min = options.params.min,
max = options.params.max;
if (min && max) {
setValidationValues(options, minMaxRuleName, [min, max]);
}
else if (min) {
setValidationValues(options, minRuleName, min);
}
else if (max) {
setValidationValues(options, maxRuleName, max);
}
});
};
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has a single value.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
/// The default is "val".</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [attribute || "val"], function (options) {
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
});
};
$jQval.addMethod("__dummy__", function (value, element, params) {
return true;
});
$jQval.addMethod("regex", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
match = new RegExp(params).exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
var match;
if (nonalphamin) {
match = value.match(/\W/g);
match = match && match.length >= nonalphamin;
}
return match;
});
if ($jQval.methods.extension) {
adapters.addSingleVal("accept", "mimtype");
adapters.addSingleVal("extension", "extension");
} else {
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
// validating the extension, and ignore mime-type validations as they are not supported.
adapters.addSingleVal("extension", "extension", "accept");
}
adapters.addSingleVal("regex", "pattern");
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
adapters.add("equalto", ["other"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
setValidationValues(options, "equalTo", element);
});
adapters.add("required", function (options) {
// jQuery Validate equates "required" with "mandatory" for checkbox elements
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
setValidationValues(options, "required", true);
}
});
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
// For checkboxes and radio buttons, only pick up values from checked fields.
if (field.is(":checkbox")) {
return field.filter(":checked").val() || field.filter(":hidden").val() || '';
}
else if (field.is(":radio")) {
return field.filter(":checked").val() || '';
}
return field.val();
};
});
setValidationValues(options, "remote", value);
});
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
if (options.params.min) {
setValidationValues(options, "minlength", options.params.min);
}
if (options.params.nonalphamin) {
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
}
if (options.params.regex) {
setValidationValues(options, "regex", options.params.regex);
}
});
adapters.add("fileextensions", ["extensions"], function (options) {
setValidationValues(options, "extension", options.params.extensions);
});
$(function () {
$jQval.unobtrusive.parse(document);
});
return $jQval.unobtrusive;
}));

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
=====================
Copyright Jörn Zaefferer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,21 @@
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long