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
|
using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.AdvancedInstaller;
using Tango.Core;
using Tango.Core.Helpers;
using Tango.PMR.FirmwareUpgrade;
using Tango.PPC.Common.Web;
using Tango.SQLExaminer;
using Tango.Transport.Web;
using Tango.Web;
namespace Tango.PPC.Common.Publish
{
public class PPCPublisher : ExtendedObject
{
private PPCWebClient _client;
/// <summary>
/// Occurs on publish progress.
/// </summary>
public event EventHandler<PublishProgressEventArgs> PublishProgress;
private PublishOptions _options;
/// <summary>
/// Gets or sets the publish options.
/// </summary>
public PublishOptions Options
{
get { return _options; }
set { _options = value; RaisePropertyChangedAuto(); }
}
/// <summary>
/// Initializes a new instance of the <see cref="PPCPublisher"/> class.
/// </summary>
public PPCPublisher()
{
_client = new PPCWebClient();
Options = new PublishOptions();
}
/// <summary>
/// Initializes a new instance of the <see cref="PPCPublisher"/> class.
/// </summary>
/// <param name="publishOptions">The publish options.</param>
public PPCPublisher(PublishOptions publishOptions) : this()
{
Options = publishOptions;
}
/// <summary>
/// Gets the latest version.
/// </summary>
/// <returns></returns>
public async Task<String> GetRemoteVersion(String machineVersionGuid)
{
_client.Environment = Options.Environment;
var response = await _client.GetLatestVersion(new LatestVersionRequest()
{
MachineVersionGuid = machineVersionGuid,
});
return response.Version;
}
/// <summary>
/// Gets the latest version.
/// </summary>
/// <returns></returns>
public async Task<String> GetRemoteVersion(DeploymentSlot environment)
{
_client.Environment = environment;
var response = await _client.GetLatestVersion(new LatestVersionRequest());
return response.Version;
}
/// <summary>
/// Gets the latest version.
/// </summary>
/// <returns></returns>
public String GetLocalVersion()
{
if (File.Exists(GetPPCExecutablePath()))
{
return FileVersionInfo.GetVersionInfo(GetPPCExecutablePath()).ProductVersion;
}
else
{
return "0.0.0.0";
}
}
/// <summary>
/// Gets the PPC executable path.
/// </summary>
/// <returns></returns>
public String GetPPCExecutablePath()
{
String appPath = Path.Combine(Options.GetApplicationPath(), "Tango.PPC.UI.exe");
return appPath;
}
/// <summary>
/// Login to machine service and returns an access token.
/// </summary>
/// <returns></returns>
private Task Login()
{
return Task.Factory.StartNew(() =>
{
return _client.Login(new LoginRequest()
{
Mode = LoginMode.User,
Email = Options.Email,
Password = Options.Password,
}).Result;
});
}
/// <summary>
/// Publish a PPC version using the specified <see cref="Options"/>.
/// </summary>
/// <returns></returns>
public Task Publish()
{
_client.Environment = Options.Environment;
String appPath = GetPPCExecutablePath();
String folder = Options.GetApplicationPath();
if (!File.Exists(appPath))
{
throw new FileNotFoundException($"Could not locate the PPC executable at {appPath}.");
}
if (!String.IsNullOrWhiteSpace(Options.InstallerProject))
{
if (!File.Exists(Options.InstallerProject))
{
throw new FileNotFoundException($"Installer project not found at '{Options.InstallerProject}'.");
}
if (!Directory.Exists(Options.InstallerOutputFolder))
{
throw new DirectoryNotFoundException($"Installer output folder does not exists '{Options.InstallerOutputFolder}'.");
}
}
return Task.Factory.StartNew(() =>
{
String tempFile = TemporaryManager.CreateFile(".zip");
try
{
OnPublishProgress(0, 100, $"Logging in to machine service at {Options.Environment.ToAddress()}...");
Login().Wait();
OnPublishProgress(0, 100, $"Fetching remote version from {Options.Environment.ToAddress()}...");
String remote_version = GetRemoteVersion(Options.MachineVersionGuid).Result;
String local_version = GetLocalVersion();
OnPublishProgress(0, 100, $"Remote version: {remote_version}");
OnPublishProgress(0, 100, $"Local version: {local_version}");
if (Version.Parse(local_version) <= Version.Parse(remote_version))
{
throw new InvalidOperationException($"The local version '{local_version}' is not greater than the remote version '{remote_version}'.");
}
OnPublishProgress(0, 100, $"Requesting version upload...");
var response = _client.UploadVersion(new UploadVersionRequest()
{
Comments = Options.Comments,
Version = local_version,
MachineVersionGuid = Options.MachineVersionGuid,
WithInstaller = !String.IsNullOrWhiteSpace(Options.InstallerProject),
FirmwareVersion = GetVersionInfoFromTFP(Options.TfpPath).FileDescriptors.SingleOrDefault(x => x.Destination == VersionFileDestination.Mcu).Version,
}).Result;
if (!String.IsNullOrWhiteSpace(Options.InstallerProject))
{
String output_folder = Options.InstallerOutputFolder;
OnPublishProgress(0, 100, $"Building installer project...");
InstallerBuilder installerBuilder = new InstallerBuilder(Options.InstallerProject);
String installer_name = $"PPC Installer_v{Version.Parse(local_version).ToString(3)}.exe";
String output_file = Path.Combine(output_folder, installer_name);
installerBuilder.Build(local_version, output_file).Wait();
Thread.Sleep(5000);
OnPublishProgress(0, 100, $"Uploading installer '{installer_name}'...");
using (StorageBlobUploader uploader = new StorageBlobUploader(response.InstallerBlobAddress, output_file))
{
uploader.Progress += (x, e) =>
{
OnPublishProgress(e.Current, e.Total, $"Uploading installer {(((double)e.Current / (double)e.Total) * 100d).ToString("0.0")}%...", true);
};
uploader.Upload().Wait();
}
}
CreateTupPackage(tempFile).Wait();
OnPublishProgress(0, 100, $"Starting version upload...");
using (StorageBlobUploader uploader = new StorageBlobUploader(response.BlobAddress, tempFile))
{
uploader.Progress += (x, e) =>
{
InvokeUINow(() =>
{
OnPublishProgress(e.Current, e.Total, $"Uploading version {(((double)e.Current / (double)e.Total) * 100d).ToString("0.0")}%...", true);
});
};
uploader.Upload().Wait();
}
OnPublishProgress(100, 100, $"Finalizing version upload...");
_client.NotifyVersionUploadCompleted(new UploadCompletedRequest()
{
Token = response.Token,
}).Wait();
remote_version = GetRemoteVersion(Options.MachineVersionGuid).Result;
local_version = GetLocalVersion();
OnPublishProgress(0, 0, $"Remote version: {remote_version}");
OnPublishProgress(0, 0, $"Local version: {local_version}");
if (remote_version != local_version)
{
throw new InvalidOperationException("The remote version does not seems to have been updated.");
}
OnPublishProgress(0, 0, "Version published successfully.");
}
catch (Exception ex)
{
OnPublishProgress(0, 100, $"Failed: {ex.Message}");
throw ex;
}
finally
{
PathHelper.TryDeleteFile(tempFile);
}
});
}
/// <summary>
/// Creates a Tango Update Package (.tup) file.
/// </summary>
/// <param name="filePath">The file path.</param>
/// <returns></returns>
public Task CreateTupPackage(String filePath)
{
return Task.Factory.StartNew(() =>
{
try
{
OnPublishProgress(0, 100, "Generating .tup file...");
String appPath = GetPPCExecutablePath();
String folder = Options.GetApplicationPath();
if (!File.Exists(appPath))
{
throw new FileNotFoundException($"Could not locate the PPC executable at {appPath}.");
}
if (!File.Exists(Options.TfpPath))
{
throw new FileNotFoundException($"Could not locate TFP file at {Options.TfpPath}.");
}
var tempFile = filePath;
using (ZipFile zip = new ZipFile())
{
zip.AddFile(Options.TfpPath, "/").FileName = "firmware_package.tfp";
PublishInfo versionInfo = new PublishInfo();
versionInfo.ApplicationVersion = GetLocalVersion();
versionInfo.Comments = Options.Comments;
versionInfo.Firmware = GetVersionInfoFromTFP(Options.TfpPath);
var versionInfoFile = TemporaryManager.CreateImaginaryFile();
File.WriteAllText(versionInfoFile, versionInfo.ToJson());
zip.AddFile(versionInfoFile, "/").FileName = "version.json";
String provision_dir = "Provision Scripts";
zip.AddDirectoryByName(provision_dir);
ExaminerSequenceConfiguration provision_config = new ExaminerSequenceConfiguration();
OnPublishProgress(0, 100, "Processing provisioning scripts...");
foreach (var item in Options.Synchronization.ProvisionSequenceItems)
{
OnPublishProgress(0, 100, $"Processing provisioning script '{item.Name}'...");
provision_config.Items.Add(new ExaminerSequenceItem()
{
Direction = item.Direction,
FileName = item.FileName,
Index = item.Index,
Name = item.Name,
Type = item.Type,
RequiresSerialNumber = item.RequiresSerialNumber
});
zip.AddFile(item.FilePath, provision_dir);
}
String provision_config_file = TemporaryManager.CreateFile(".zip");
provision_config.ToFile(provision_config_file);
var cf = zip.AddFile(provision_config_file, provision_dir);
cf.FileName = provision_dir + "\\config.xml";
String update_dir = "Update Scripts";
zip.AddDirectoryByName(update_dir);
ExaminerSequenceConfiguration update_config = new ExaminerSequenceConfiguration();
OnPublishProgress(0, 100, "Processing update scripts...");
foreach (var item in Options.Synchronization.UpdateSequenceItems)
{
OnPublishProgress(0, 100, $"Processing update script '{item.Name}'...");
update_config.Items.Add(new ExaminerSequenceItem()
{
Direction = item.Direction,
FileName = item.FileName,
Index = item.Index,
Name = item.Name,
Type = item.Type,
RequiresSerialNumber = item.RequiresSerialNumber
});
zip.AddFile(item.FilePath, update_dir);
}
String update_config_file = TemporaryManager.CreateFile(".zip");
update_config.ToFile(update_config_file);
var cuf = zip.AddFile(update_config_file, update_dir);
cuf.FileName = update_dir + "\\config.xml";
foreach (var file in Directory.GetFiles(folder, "*.*", SearchOption.TopDirectoryOnly))
{
zip.AddFile(file, "/");
}
zip.SaveProgress += (x, e) =>
{
if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
{
OnPublishProgress(e.EntriesSaved + 1, e.EntriesTotal, $"Compressing files {(((double)(e.EntriesSaved + 1) / (double)e.EntriesTotal) * 100d).ToString("0.0")}%...", true);
}
};
zip.ParallelDeflateThreshold = -1;
zip.Save(tempFile);
OnPublishProgress(100, 100, "TUP file generated successfully.");
}
}
catch (Exception ex)
{
OnPublishProgress(0, 100, $"Failed: {ex.Message}");
throw ex;
}
});
}
/// <summary>
/// Gets the version information from a TFP file.
/// </summary>
/// <param name="tfpFile">The TFP file.</param>
/// <returns></returns>
private VersionPackageDescriptor GetVersionInfoFromTFP(String tfpFile)
{
using (ZipFile zip = ZipFile.Read(tfpFile))
{
var reader = zip.Entries.SingleOrDefault(x => x.FileName == "package.cfg").OpenReader();
return VersionPackageDescriptor.Parser.ParseFrom(reader);
}
}
/// <summary>
/// Raises the publish progress event.
/// </summary>
/// <param name="progress">The progress.</param>
/// <param name="total">The total.</param>
/// <param name="message">The message.</param>
protected virtual void OnPublishProgress(double progress, double total, String message, bool singleLine = false)
{
PublishProgress?.Invoke(this, new PublishProgressEventArgs()
{
Progress = progress,
Total = total,
Message = message,
SingleLineRecommended = singleLine,
});
}
}
}
|