1 | using backend.Data;
|
---|
2 | using Microsoft.EntityFrameworkCore;
|
---|
3 | using Quartz;
|
---|
4 | using SendGrid;
|
---|
5 | using SendGrid.Helpers.Mail;
|
---|
6 |
|
---|
7 | namespace backend.Jobs
|
---|
8 | {
|
---|
9 | public class QueueJob : IJob
|
---|
10 | {
|
---|
11 | private readonly DataContext _context = null;
|
---|
12 | public QueueJob(DataContext context)
|
---|
13 | {
|
---|
14 | _context = context;
|
---|
15 | }
|
---|
16 | public async Task Execute(IJobExecutionContext context)
|
---|
17 | {
|
---|
18 | var items = await _context.QueueItems.OrderBy(x => x.CreatedAt).Take(10).ToListAsync();
|
---|
19 | var client = new SendGridClient("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");
|
---|
20 | foreach(var item in items)
|
---|
21 | {
|
---|
22 | var msg = new SendGridMessage()
|
---|
23 | {
|
---|
24 | From = new EmailAddress("danilo.najkov@students.finki.ukim.mk",
|
---|
25 | "Danilo"),
|
---|
26 | Subject = item.Subject,
|
---|
27 | HtmlContent = item.Message
|
---|
28 | };
|
---|
29 | msg.AddTo(new EmailAddress(item.Reciptient));
|
---|
30 | msg.SetClickTracking(false, false);
|
---|
31 |
|
---|
32 | var response = await client.SendEmailAsync(msg);
|
---|
33 | if (response.IsSuccessStatusCode)
|
---|
34 | {
|
---|
35 | _context.QueueItems.Remove(item);
|
---|
36 | }
|
---|
37 | else if (item.Retries == 2)
|
---|
38 | {
|
---|
39 | _context.QueueItems.Add(new Entities.QueueItem()
|
---|
40 | {
|
---|
41 | CreatedAt=DateTime.UtcNow,
|
---|
42 | Subject="Неуспешно испратена порака",
|
---|
43 | Message="Порака: "+item.Subject+", до "+item.Reciptient+" беше неуспешно пратена.",
|
---|
44 | Retries=0
|
---|
45 | });
|
---|
46 | _context.QueueItems.Remove(item);
|
---|
47 | }
|
---|
48 | else
|
---|
49 | {
|
---|
50 | item.Retries++;
|
---|
51 | _context.QueueItems.Update(item);
|
---|
52 | }
|
---|
53 | }
|
---|
54 | await _context.SaveChangesAsync();
|
---|
55 | }
|
---|
56 | }
|
---|
57 | }
|
---|