-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdminBlockTemplateController.cs
More file actions
275 lines (256 loc) · 9.36 KB
/
AdminBlockTemplateController.cs
File metadata and controls
275 lines (256 loc) · 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.Json;
using MyWebApp.Data;
using MyWebApp.Filters;
using MyWebApp.Models;
using MyWebApp.Services;
namespace MyWebApp.Controllers;
[RoleAuthorize("Admin")]
public class AdminBlockTemplateController : Controller
{
private readonly ApplicationDbContext _db;
private readonly HtmlSanitizerService _sanitizer;
public AdminBlockTemplateController(ApplicationDbContext db, HtmlSanitizerService sanitizer)
{
_db = db;
_sanitizer = sanitizer;
}
private async Task LoadPagesAsync()
{
ViewBag.Pages = await _db.Pages.AsNoTracking().OrderBy(p => p.Slug).ToListAsync();
ViewBag.Roles = await _db.Roles.AsNoTracking().OrderBy(r => r.Name).ToListAsync();
ViewBag.Zones = await _db.PageSections.AsNoTracking()
.Select(s => s.Zone)
.Distinct()
.OrderBy(z => z)
.ToListAsync();
}
public async Task<IActionResult> Index()
{
var items = await _db.BlockTemplates.AsNoTracking().OrderBy(t => t.Name).ToListAsync();
return View(items);
}
public async Task<IActionResult> Create()
{
await LoadPagesAsync();
return View(new BlockTemplate());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(BlockTemplate model, List<int>? pageIds, string? zone, string? role)
{
if (!ModelState.IsValid)
{
await LoadPagesAsync();
ViewBag.SelectedPageIds = pageIds ?? new List<int>();
ViewBag.SelectedZone = zone;
ViewBag.SelectedRole = role;
return View(model);
}
model.Html = _sanitizer.Sanitize(model.Html);
_db.BlockTemplates.Add(model);
_db.BlockTemplateVersions.Add(new BlockTemplateVersion { Template = model, Html = model.Html });
await _db.SaveChangesAsync();
await AddSectionsAsync(model, pageIds, zone, role);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Edit(int id)
{
var item = await _db.BlockTemplates.FindAsync(id);
if (item == null) return NotFound();
await LoadPagesAsync();
return View(item);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(BlockTemplate model, List<int>? pageIds, string? zone, string? role)
{
if (!ModelState.IsValid)
{
await LoadPagesAsync();
ViewBag.SelectedPageIds = pageIds ?? new List<int>();
ViewBag.SelectedZone = zone;
ViewBag.SelectedRole = role;
return View(model);
}
model.Html = _sanitizer.Sanitize(model.Html);
_db.Update(model);
_db.BlockTemplateVersions.Add(new BlockTemplateVersion { BlockTemplateId = model.Id, Html = model.Html });
await _db.SaveChangesAsync();
await AddSectionsAsync(model, pageIds, zone, role);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Delete(int id)
{
var item = await _db.BlockTemplates.FindAsync(id);
if (item == null) return NotFound();
return View(item);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var item = await _db.BlockTemplates.FindAsync(id);
if (item != null)
{
_db.BlockTemplates.Remove(item);
await _db.SaveChangesAsync();
}
return RedirectToAction(nameof(Index));
}
[HttpGet]
public async Task<IActionResult> Html(int id)
{
var item = await _db.BlockTemplates.AsNoTracking().FirstOrDefaultAsync(t => t.Id == id);
if (item == null) return NotFound();
return Content(item.Html, "text/html");
}
public async Task<IActionResult> Export()
{
var list = await _db.BlockTemplates.AsNoTracking().ToListAsync();
var json = JsonSerializer.Serialize(list);
return File(System.Text.Encoding.UTF8.GetBytes(json), "application/json", "blocks.json");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Import(IFormFile? file)
{
if (file == null || file.Length == 0) return RedirectToAction(nameof(Index));
using var reader = new StreamReader(file.OpenReadStream());
var json = await reader.ReadToEndAsync();
var list = JsonSerializer.Deserialize<List<BlockTemplate>>(json) ?? new();
foreach (var t in list)
{
t.Id = 0;
t.Html = _sanitizer.Sanitize(t.Html);
_db.BlockTemplates.Add(t);
_db.BlockTemplateVersions.Add(new BlockTemplateVersion { Template = t, Html = t.Html });
}
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
[HttpGet]
public async Task<IActionResult> GetBlocks()
{
var items = await _db.BlockTemplates.AsNoTracking()
.OrderBy(t => t.Name)
.Select(t => new { t.Id, t.Name, Preview = t.Html.Length > 200 ? t.Html.Substring(0, 200) + "..." : t.Html })
.ToListAsync();
return Json(items);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateFromSection(string name, string html)
{
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(html))
return BadRequest();
html = _sanitizer.Sanitize(html);
var t = new BlockTemplate { Name = name, Html = html };
_db.BlockTemplates.Add(t);
_db.BlockTemplateVersions.Add(new BlockTemplateVersion { Template = t, Html = html });
await _db.SaveChangesAsync();
return Json(new { t.Id });
}
public async Task<IActionResult> AddToPage(int id)
{
var item = await _db.BlockTemplates.FindAsync(id);
if (item == null) return NotFound();
await LoadPagesAsync();
ViewBag.BlockId = id;
ViewBag.SelectedPageIds = new List<int>();
ViewBag.SelectedZone = string.Empty;
ViewBag.SelectedRole = string.Empty;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToPage(int id, List<int> pageIds, string zone, string role)
{
var template = await _db.BlockTemplates.FindAsync(id);
if (template == null) return NotFound();
if (pageIds == null || pageIds.Count == 0)
{
await LoadPagesAsync();
ViewBag.BlockId = id;
ViewBag.SelectedPageIds = pageIds ?? new List<int>();
ViewBag.SelectedZone = zone;
ViewBag.SelectedRole = role;
ModelState.AddModelError("pageIds", "Page selection required");
return View();
}
var roleEntity = await _db.Roles.FirstOrDefaultAsync(r => r.Name == role);
int? roleId = roleEntity?.Id;
zone = zone?.Trim() ?? string.Empty;
if (string.IsNullOrEmpty(zone))
{
await LoadPagesAsync();
ViewBag.BlockId = id;
ViewBag.SelectedPageIds = pageIds;
ViewBag.SelectedZone = zone;
ViewBag.SelectedRole = role;
ModelState.AddModelError("zone", "Zone required");
return View();
}
if (pageIds.Contains(0))
{
pageIds = await _db.Pages.Select(p => p.Id).ToListAsync();
}
foreach (var pageId in pageIds)
{
var maxSort = await _db.PageSections
.Where(s => s.PageId == pageId && s.Zone == zone)
.Select(s => (int?)s.SortOrder)
.MaxAsync();
var sort = (maxSort ?? -1) + 1;
var section = new PageSection
{
PageId = pageId,
Zone = zone,
SortOrder = sort,
Html = template.Html,
Type = PageSectionType.Html,
RoleId = roleId
};
_db.PageSections.Add(section);
}
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private async Task AddSectionsAsync(BlockTemplate template, List<int>? pageIds, string? zone, string? role)
{
if (pageIds == null || pageIds.Count == 0 || string.IsNullOrWhiteSpace(zone))
return;
var roleEntity = await _db.Roles.FirstOrDefaultAsync(r => r.Name == role);
int? roleId = roleEntity?.Id;
zone = zone!.Trim();
if (pageIds.Contains(0))
{
pageIds = await _db.Pages.Select(p => p.Id).ToListAsync();
}
foreach (var pageId in pageIds)
{
var maxSort = await _db.PageSections
.Where(s => s.PageId == pageId && s.Zone == zone)
.Select(s => (int?)s.SortOrder)
.MaxAsync();
var sort = (maxSort ?? -1) + 1;
var section = new PageSection
{
PageId = pageId,
Zone = zone,
SortOrder = sort,
Html = template.Html,
Type = PageSectionType.Html,
RoleId = roleId
};
_db.PageSections.Add(section);
}
}
}