-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathPdfService.cs
More file actions
511 lines (450 loc) · 17.9 KB
/
Copy pathPdfService.cs
File metadata and controls
511 lines (450 loc) · 17.9 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
using System.Globalization;
using System.Text.Json;
using Altinn.App.Core.Configuration;
using Altinn.App.Core.Features;
using Altinn.App.Core.Features.Auth;
using Altinn.App.Core.Helpers.Extensions;
using Altinn.App.Core.Internal.App;
using Altinn.App.Core.Internal.Data;
using Altinn.App.Core.Internal.Expressions;
using Altinn.App.Core.Internal.Texts;
using Altinn.App.Core.Models;
using Altinn.App.Core.Models.Expressions;
using Altinn.Platform.Storage.Interface.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
namespace Altinn.App.Core.Internal.Pdf;
/// <summary>
/// Service for handling the creation and storage of receipt Pdf.
/// </summary>
public class PdfService : IPdfService
{
private static readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
private readonly IDataClient _dataClient;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IPdfGeneratorClient _pdfGeneratorClient;
private readonly PdfGeneratorSettings _pdfGeneratorSettings;
private readonly ILogger<PdfService> _logger;
private readonly IAuthenticationContext _authenticationContext;
private readonly ITranslationService _translationService;
private readonly GeneralSettings _generalSettings;
private readonly IAppResources _resources;
private readonly InstanceDataUnitOfWorkInitializer? _instanceDataUnitOfWorkInitializer;
private readonly Telemetry? _telemetry;
internal const string PdfElementType = "ref-data-as-pdf";
private const string PdfContentType = "application/pdf";
/// <summary>
/// Initializes a new instance of the <see cref="PdfService"/> class.
/// </summary>
public PdfService(
IDataClient dataClient,
IHttpContextAccessor httpContextAccessor,
IPdfGeneratorClient pdfGeneratorClient,
IOptions<PdfGeneratorSettings> pdfGeneratorSettings,
IOptions<GeneralSettings> generalSettings,
ILogger<PdfService> logger,
IAuthenticationContext authenticationContext,
ITranslationService translationService,
IAppResources resources,
IServiceProvider? serviceProvider = null,
Telemetry? telemetry = null
)
{
_dataClient = dataClient;
_httpContextAccessor = httpContextAccessor;
_pdfGeneratorClient = pdfGeneratorClient;
_pdfGeneratorSettings = pdfGeneratorSettings.Value;
_generalSettings = generalSettings.Value;
_logger = logger;
_authenticationContext = authenticationContext;
_translationService = translationService;
_resources = resources;
_instanceDataUnitOfWorkInitializer = serviceProvider?.GetService<InstanceDataUnitOfWorkInitializer>();
_telemetry = telemetry;
}
/// <inheritdoc/>
public async Task GenerateAndStorePdf(Instance instance, string taskId, CancellationToken ct)
{
using var activity = _telemetry?.StartGenerateAndStorePdfActivity(instance, taskId);
_ = await GenerateAndStorePdfInternal(instance, taskId, null, null, null, ct);
}
/// <inheritdoc/>
public async Task<DataElement> GenerateAndStorePdf(
Instance instance,
string taskId,
string? customFileNameTextResourceKey,
List<string>? autoGeneratePdfForTaskIds = null,
CancellationToken ct = default
)
{
using var activity = _telemetry?.StartGenerateAndStorePdfActivity(instance, taskId);
return await GenerateAndStorePdfInternal(
instance,
taskId,
customFileNameTextResourceKey,
null,
autoGeneratePdfForTaskIds,
ct
);
}
/// <inheritdoc/>
public async Task<DataElement> GenerateAndStoreSubformPdf(
Instance instance,
string taskId,
string? customFileNameTextResourceKey,
SubformPdfContext subformPdfContext,
CancellationToken ct
)
{
return await GenerateAndStorePdfInternal(
instance,
taskId,
customFileNameTextResourceKey,
subformPdfContext,
null,
ct
);
}
/// <inheritdoc/>
public async Task<Stream> GeneratePdf(Instance instance, string taskId, bool isPreview, CancellationToken ct)
{
using var activity = _telemetry?.StartGeneratePdfActivity(instance, taskId);
HttpContext? httpContext = _httpContextAccessor.HttpContext;
var queries = httpContext?.Request.Query;
var auth = _authenticationContext.Current;
var language = GetOverriddenLanguage(queries) ?? await auth.GetLanguage();
return await GeneratePdfContent(instance, taskId, language, isPreview, null, null, ct);
}
/// <inheritdoc/>
public async Task<Stream> GeneratePdf(Instance instance, string taskId, CancellationToken ct)
{
return await GeneratePdf(instance, taskId, false, ct);
}
private async Task<DataElement> GenerateAndStorePdfInternal(
Instance instance,
string taskId,
string? customFileNameTextResourceKey,
SubformPdfContext? subformPdfContext,
List<string>? autoGeneratePdfForTaskIds = null,
CancellationToken ct = default
)
{
HttpContext? httpContext = _httpContextAccessor.HttpContext;
var queries = httpContext?.Request.Query;
var auth = _authenticationContext.Current;
var language = GetOverriddenLanguage(queries) ?? await auth.GetLanguage();
await using Stream pdfContent = await GeneratePdfContent(
instance,
taskId,
language,
false,
subformPdfContext,
autoGeneratePdfForTaskIds,
ct
);
string fileName = await GetFileName(
instance,
taskId,
language,
customFileNameTextResourceKey,
subformPdfContext?.DataElementId
);
DataElement dataElement = await _dataClient.InsertBinaryData(
instance.Id,
PdfElementType,
PdfContentType,
fileName,
pdfContent,
taskId,
cancellationToken: ct
);
return dataElement;
}
private async Task<Stream> GeneratePdfContent(
Instance instance,
string taskId,
string language,
bool isPreview,
SubformPdfContext? subformPdfContext,
List<string>? autoGeneratePdfForTaskIds,
CancellationToken ct
)
{
var baseUrl = _generalSettings.FormattedExternalAppBaseUrl(new AppIdentifier(instance));
var pagePath = _pdfGeneratorSettings
.AppPdfPagePathTemplate.ToLowerInvariant()
.Replace("{instanceid}", instance.Id);
List<KeyValuePair<string, string>> autoPdfTaskIdsQueryParams = CreateAutoPdfTaskIdsQueryParams(
autoGeneratePdfForTaskIds
);
Uri uri = BuildUri(baseUrl, pagePath, taskId, language, subformPdfContext, autoPdfTaskIdsQueryParams);
bool displayFooter = _pdfGeneratorSettings.DisplayFooter;
string? footerContent = null;
if (isPreview)
{
footerContent = await GetPreviewFooter(language);
}
else if (displayFooter)
{
footerContent = await GetFooterContent(instance, taskId, language);
}
Stream pdfContent = await _pdfGeneratorClient.GeneratePdf(uri, footerContent, ct);
return pdfContent;
}
private static Uri BuildUri(
string baseUrl,
string pagePath,
string taskId,
string language,
SubformPdfContext? subformPdfContext,
List<KeyValuePair<string, string>>? additionalQueryParams = null
)
{
// Uses string manipulation instead of UriBuilder, since UriBuilder messes up
// query parameters in combination with hash fragments in the url.
string url = baseUrl + pagePath;
// Insert subform component and data element id in the url if provided
if (subformPdfContext is not null)
{
int pdfIndex = url.IndexOf("?pdf=1", StringComparison.OrdinalIgnoreCase);
if (pdfIndex > 0)
{
string beforePdf = $"{url[..pdfIndex]}/{taskId}/subform";
string afterPdf = url[pdfIndex..];
url = $"{beforePdf}/{subformPdfContext.ComponentId}/{subformPdfContext.DataElementId}/{afterPdf}";
}
else
{
url += $"/{taskId}/subform/{subformPdfContext.ComponentId}/{subformPdfContext.DataElementId}";
}
}
string lang = Uri.EscapeDataString(language);
if (url.Contains('?'))
{
url += $"&lang={lang}";
}
else
{
url += $"?lang={lang}";
}
if (additionalQueryParams != null)
{
foreach (KeyValuePair<string, string> param in additionalQueryParams)
{
url += $"&{param.Key}={param.Value}";
}
}
return new Uri(url);
}
internal static string? GetOverriddenLanguage(IQueryCollection? queries)
{
if (queries is null)
{
return null;
}
if (
queries.TryGetValue("language", out StringValues queryLanguage)
|| queries.TryGetValue("lang", out queryLanguage)
)
{
return queryLanguage.ToString();
}
return null;
}
private async Task<string> GetFileName(
Instance instance,
string taskId,
string? language,
string? customFileNameTextResourceKey,
string? subformDataElementId
)
{
string? fileName;
if (_instanceDataUnitOfWorkInitializer != null && customFileNameTextResourceKey != null)
{
InstanceDataUnitOfWork dataAccessor = await _instanceDataUnitOfWorkInitializer.Init(
instance,
taskId,
language
);
fileName = await GetVariableSubstitutedFileName(
dataAccessor,
customFileNameTextResourceKey,
subformDataElementId
);
}
else
{
// Fall back to simple translation without variable substitution
fileName = await _translationService.TranslateTextKey(
customFileNameTextResourceKey ?? "backend.pdf_default_file_name",
language
);
}
if (string.IsNullOrEmpty(fileName))
{
// translation for backend.pdf_default_file_name should always be present (it has a falback in the translation service),
// but just in case, we default to a hardcoded string.
fileName = "Altinn PDF.pdf";
}
string escapedFileName = Uri.EscapeDataString(fileName.AsFileName(false));
return escapedFileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)
? escapedFileName
: $"{escapedFileName}.pdf";
}
private async Task<string> GetPreviewFooter(string language)
{
var previewText = await _translationService.TranslateTextKey("pdfPreviewText", language);
return $@"<div style='font-family: Inter; font-size: 12px; width: 100%; display: flex; flex-direction: row; align-items: center; gap: 12px; padding: 0 70px 0 70px;'>
<div style='display: flex; flex-direction: row; width: 100%; align-items: center; font-style: italic; color: #e02e49;'>
<span>{previewText}</span>
</div>
</div>";
}
private async Task<string> GetFooterContent(Instance instance, string taskId, string? language)
{
TimeZoneInfo timeZone = TimeZoneInfo.Utc;
try
{
// attempt to set timezone to norwegian
timeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Oslo");
}
catch (TimeZoneNotFoundException e)
{
_logger.LogWarning($"Could not find timezone Europe/Oslo. Defaulting to UTC. {e.Message}");
}
DateTimeOffset now = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, timeZone);
bool hideAppName = await GetHideAppNameInPdf(instance, taskId, language);
string dateGenerated = now.ToString("dd.MM.yyyy HH:mm", new CultureInfo("nb-NO"));
string altinnReferenceId = instance.Id.Split("/")[1].Split("-")[4];
string title = hideAppName
? string.Empty
: $"<span>{await _translationService.TranslateTextKey("appName", language) ?? "Altinn"}</span>";
string footerTemplate =
$@"<div style='font-family: Inter; font-size: 12px; width: 100%; display: flex; flex-direction: row; align-items: center; gap: 12px; padding: 0 70px 0 70px;'>
<div style='display: flex; flex-direction: row; width: 100%; align-items: center'>
{title}
<div
id='header-template'
style='color: #F00; font-weight: 700; border: 1px solid #F00; padding: 6px 8px; margin-left: auto;'
>
<span>{dateGenerated} </span>
<span>ID:{altinnReferenceId}</span>
</div>
</div>
<div style='display: flex; flex-direction-row; align-items: center;'>
<span class='pageNumber'></span>
/
<span class='totalPages'></span>
</div>
</div>";
return footerTemplate;
}
private async Task<bool> GetHideAppNameInPdf(Instance instance, string taskId, string? language)
{
string? layoutSets = _resources.GetLayoutSets();
if (string.IsNullOrEmpty(layoutSets))
return false;
try
{
using var jsonDoc = JsonDocument.Parse(
layoutSets,
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }
);
var root = jsonDoc.RootElement;
if (
!root.TryGetProperty("uiSettings", out var uiSettings)
|| !uiSettings.TryGetProperty("hideAppNameInPdf", out var hideAppName)
)
return false;
if (hideAppName.ValueKind == JsonValueKind.True)
return true;
if (hideAppName.ValueKind == JsonValueKind.False)
return false;
if (_instanceDataUnitOfWorkInitializer is null)
{
_logger.LogWarning(
"Cannot evaluate hideAppNameInPdf expression: InstanceDataUnitOfWorkInitializer is not available"
);
return false;
}
var expression = hideAppName.Deserialize<Expression>(_jsonSerializerOptions);
var dataAccessor = await _instanceDataUnitOfWorkInitializer.Init(instance, taskId, language);
var state = dataAccessor.GetLayoutEvaluatorState();
var layoutSet = _resources.GetLayoutSetForTask(taskId);
DataElementIdentifier? dataElement = layoutSet?.DataType is { } dataType
? instance.Data?.Find(d => d.DataType == dataType)
: null;
var componentContext = new ComponentContext(
dataAccessor,
component: null,
rowIndices: null,
dataElementIdentifier: dataElement
);
var result = await ExpressionEvaluator.EvaluateExpression(state, expression, componentContext);
return result is true;
}
catch (JsonException e)
{
_logger.LogWarning(e, "Failed to evaluate hideAppNameInPdf, defaulting to showing app name");
return false;
}
catch (InvalidOperationException e)
{
_logger.LogWarning(e, "Failed to evaluate hideAppNameInPdf, defaulting to showing app name");
return false;
}
}
private static List<KeyValuePair<string, string>> CreateAutoPdfTaskIdsQueryParams(
List<string>? autoGeneratePdfForTaskIds
)
{
List<KeyValuePair<string, string>> additionalQueryParams = [];
// Create query param array for autoGeneratePdfForTaskIds if provided, task=1&task=2 etc.
if (autoGeneratePdfForTaskIds != null && autoGeneratePdfForTaskIds.Count != 0)
{
foreach (string taskId in autoGeneratePdfForTaskIds)
{
additionalQueryParams.Add(new KeyValuePair<string, string>("task", taskId));
}
}
return additionalQueryParams;
}
private async Task<string?> GetVariableSubstitutedFileName(
InstanceDataUnitOfWork dataAccessor,
string customFileNameTextResourceKey,
string? subformDataElementId
)
{
DataElementIdentifier? dataElementIdentifier =
subformDataElementId != null
? new DataElementIdentifier(subformDataElementId)
: (DataElementIdentifier?)null;
var componentContext = new ComponentContext(
dataAccessor,
component: null,
rowIndices: null,
dataElementIdentifier: dataElementIdentifier
);
return await _translationService.TranslateTextKey(
customFileNameTextResourceKey,
dataAccessor,
componentContext
);
}
}
/// <summary>
/// Contains subform-specific parameters required for generating a subform PDF.
/// </summary>
/// <param name="ComponentId">The ID of the subform component.</param>
/// <param name="DataElementId">The ID of the subform data element.</param>
public sealed record SubformPdfContext(string ComponentId, string DataElementId);