-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
233 lines (200 loc) · 7.67 KB
/
Program.cs
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
using DocuSign.eSign.Model;
using System.Diagnostics;
using System.Text.Json;
namespace DSBatchDownloader
{
internal class Program
{
static void Main()
{
ReportDetails report = new ReportDetails();
report.RunDate = DateTime.Now;
//SETUP FROM CONFIG
Config? config = null;
string downloadDir = string.Empty;
try
{
var jsonConfig = File.ReadAllText($@".\config.json");
config = JsonSerializer.Deserialize<Config>(jsonConfig);
if (config == null)
throw new Exception("Config file is invalid.");
downloadDir = $@"{config.TopLevelDirectory}\DownloadedFiles";
if (Directory.Exists(downloadDir))
{
if (config.ClearPreviousDownloads)
{
Directory.Delete(downloadDir, true);
Directory.CreateDirectory(downloadDir);
}
else if (Directory.GetFiles(downloadDir, "*", SearchOption.AllDirectories).Any())
{
throw new Exception("Files exist in DownloadedFiles directory but ClearPreviousDownloads setting is false. Cannot proceed.");
}
}
else
Directory.CreateDirectory(downloadDir);
}
catch(Exception ex)
{
FailForOverallException(report, config, ex);
}
//AUTHENTICATION
AuthInfo authInfo = new AuthInfo();
try
{
authInfo = Authentication.Authenticate(config!, report);
}
catch(Exception ex)
{
FailForOverallException(report, config, ex);
}
var dsController = new DSController(authInfo);
//GET ENVELOPES
EnvelopesInformation? envelopeInformation = null;
IEnumerable<Envelope>? filteredEnvelopes = null;
try
{
envelopeInformation = dsController.GetEnvelopes(config!.EnvelopeOptions);
if (envelopeInformation == null || envelopeInformation.ResultSetSize == "0")
throw new Exception("No envelopes were found.");
report.TotalEnvelopes = envelopeInformation!.ResultSetSize;
filteredEnvelopes =
envelopeInformation.Envelopes
.Where(e => string.IsNullOrEmpty(e.PurgeState) || e.PurgeState == "unpurged");
report.UnpurgedEnvelopes = filteredEnvelopes.Count();
if (filteredEnvelopes == null || filteredEnvelopes.Count() == 0)
throw new Exception("No unpurged envelopes found");
ColorConsole.WriteMarkedUpString($"Total # Envelopes Found : <green>{envelopeInformation.ResultSetSize}</green>");
ColorConsole.WriteMarkedUpString($"Unpurged # Envelopes Found: <green>{filteredEnvelopes.Count()}</green>");
Console.WriteLine();
}
catch(Exception ex)
{
FailForOverallException(report, config, ex);
}
//DOWNLOAD FILES
var fileNameDict = new Dictionary<string, int>();
foreach(var envelope in filteredEnvelopes!)
{
var reportResult = new ReportEnvelopeResult();
reportResult.EnvelopeId = envelope.EnvelopeId;
reportResult.OriginalName = envelope.EmailSubject;
Stream responseStream;
try
{
responseStream = dsController.GetDocuments(envelope.EnvelopeId, config!.DownloadMode);
}
catch(Exception ex)
{
reportResult.Exception = ex;
reportResult.ResponseSize = 0;
reportResult.FileName = string.Empty;
reportResult.FileSize = 0;
report.Results.Add(reportResult);
ColorConsole.WriteMarkedUpString($"<red>Error getting file from envelope id {envelope.EnvelopeId}</red>");
Console.WriteLine(ex.Message);
if (config!.FailOnFirstError)
FailForOverallException(report, config, null);
continue;
}
reportResult.ResponseSize = responseStream.Length;
var fileName = $"{string.Join("", envelope.EmailSubject.Split(Path.GetInvalidFileNameChars()))}";
var extension = config.DownloadMode == "combined" ? ".pdf" : ".zip";
if (fileName.EndsWith(".pdf") || fileName.EndsWith(".zip"))
{
fileName = fileName.Substring(0, fileName.Length - 4);
}
if (!fileNameDict.ContainsKey(fileName))
{
fileNameDict.Add(fileName, 0);
fileName = $"{fileName}{extension}";
}
else
{
var fnNum = ++fileNameDict[fileName];
fileName = $"{fileName}({fnNum}){extension}";
}
using var fileStream = File.Create($@"{downloadDir}\{fileName}");
responseStream.Seek(0, SeekOrigin.Begin);
responseStream.CopyTo(fileStream);
responseStream.Flush();
responseStream.Close();
fileStream.Flush();
fileStream.Close();
ColorConsole.WriteMarkedUpString($"Saved file: <darkcyan>{fileName}</darkcyan>");
//Verify for report
reportResult.FileName = fileName;
try
{
var fileBytes = File.ReadAllBytes($@"{downloadDir}\{fileName}");
reportResult.FileSize = fileBytes.Length;
reportResult.Verify(config.VerificationAllowance);
if (!reportResult.Verified)
throw new Exception("File cannot be verified.");
}
catch(Exception ex)
{
reportResult.Exception = ex;
if (config.FailOnFirstError)
{
report.Results.Add(reportResult);
FailForOverallException(report, config, null);
}
}
report.Results.Add(reportResult);
if(config.DownloadIntervalMilliseconds > 0)
Thread.Sleep(config.DownloadIntervalMilliseconds);
}
Console.WriteLine();
Console.WriteLine($"Done. Opening report...");
if (report.Results.Where(r => !r.Verified).Any())
report.Succeeded = false;
else
report.Succeeded = true;
PrintAndOpenReport(report, config);
}
private static void PrintAndOpenReport(ReportDetails report, Config? config)
{
var reportHtml = ReportBuilder.BuildReport(report, config);
var reportFileName = $@"{Path.GetFullPath(config?.TopLevelDirectory ?? ".")}\report{report.RunDate.ToString("MM.dd.yyyy-HH.mm.ss")}.html";
File.WriteAllText(reportFileName, reportHtml);
var browserProcess = new Process();
browserProcess.StartInfo.UseShellExecute = true;
if (config == null)
{
//Don't know which browser is desired, so just use OS default for HTML files (and hope it's a browser).
browserProcess.StartInfo.FileName = reportFileName;
browserProcess.Start();
}
else
{
switch (config!.Browser)
{
case "edge":
browserProcess.StartInfo.FileName = "msedge";
browserProcess.StartInfo.Arguments = $@"{(config.UsePrivate ? "-inprivate" : string.Empty)} --new-window ""{reportFileName}""";
break;
case "chrome":
browserProcess.StartInfo.FileName = "chrome";
browserProcess.StartInfo.Arguments = $@"{(config.UsePrivate ? "--incognito" : string.Empty)} --new-window ""{reportFileName}""";
break;
case "firefox":
browserProcess.StartInfo.FileName = "firefox";
browserProcess.StartInfo.Arguments = $@"{(config.UsePrivate ? "-private-window" : "--new-window")} ""{reportFileName}""";
break;
default:
browserProcess.StartInfo.FileName = reportFileName;
break;
}
browserProcess.Start();
}
}
private static void FailForOverallException(ReportDetails report, Config? config, Exception? ex)
{
report.Succeeded = false;
report.OverallException = ex;
PrintAndOpenReport(report, config);
Environment.Exit(1);
}
}
}