chr
2024-10-09 1f645778ae80a3a8801b8bb4d0fcf8feb244ad43
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
using AutoUpdater.Entity;
using AutoUpdater.Util;
using ICSharpCode.SharpZipLib.Zip;
using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using VersionControl;
using Path = System.IO.Path;
 
namespace AutoUpdater
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static ILog Logger = LogManager.GetLogger("AutoUpdater");
        #region 字段
        /// <summary>
        /// SolidWorks 主窗口进程PID
        /// </summary>
        private int SwMainProcessId { get; set; } = -1;
 
        /// <summary>
        /// exe文件路径
        /// </summary>
        private DirectoryInfo CurrentPath { get; set; }
 
        /// <summary>
        /// 更新时所用的临时文件夹
        /// </summary>
        private string TempDir { get; set; }
 
        /// <summary>
        /// 下载文件的临时路径
        /// </summary>
        private string DownloadDir { get; set; }
 
        /// <summary>
        /// 临时解压缩文件夹
        /// </summary>
        private string UnZipDir { get; set; }
 
        /// <summary>
        /// SolidWorks程序启动路径
        /// </summary>
        private string SwAppPath { get; set; }
 
        /// <summary>
        /// 要更新的AppId
        /// </summary>
        private string AppId { get; set; }
        /// <summary>
        /// 本地版本
        /// </summary>
        private string CurrentVersion { get; set; }
        #endregion
 
        public MainWindow()
        {
            InitializeComponent();
        }
 
        /// <summary>
        /// 窗口加载完成后执行,关掉SolidWorks主进程,进行更新操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Logger.Info("自动更新程序启动...");
            string[] args = Environment.GetCommandLineArgs();
            // 有参数,说明是从SolidWork插件启动的,需要kill solidwork进程
            SwMainProcessId = args.Length >= 2 ? int.Parse(args[1]) : -1;
            // 初始化程序路径
            CurrentPath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent;
            Init();
            if (SwMainProcessId > 0)
            {
                // 可能需要关进程,可能不需要
                Close_SwMainProcess();
            }
            else
            {
                // 从exe文件中获取本地插件版本
                GetCurrentVersion();
                // 检查插件的更新
                CheckPluginUpdate();
            }
        }
 
        public void KillProcessByFullPath(string exePath)
        {
            string exeName = Path.GetFileNameWithoutExtension(exePath);
            Process[] ps = Process.GetProcessesByName(exeName);
            if (ps.Length > 0)
            {
                foreach (Process p in ps)
                {
                    if (new Uri(p.MainModule.FileName) == new Uri(exePath))
                    {
                        p.Kill();
                    }
                }
            }
        }
 
        /// <summary>
        /// 终止两个Listener相关进程
        /// </summary>
        public void KillListenerProcess()
        {
            string dir = Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            string path1 = Path.Combine(dir, "Listener", "SolidWorksListener.exe");
            string path2 = Path.Combine(dir, "Alert.exe");
            KillProcessByFullPath(path1);
            // 暂停一秒不然AlertKill不掉
            Thread.Sleep(1000);
            KillProcessByFullPath(path2);
        }
 
        /// <summary>
        /// 启动Listener相关进程
        /// </summary>
        public void StartListenerProcess()
        {
            string dir = Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            string path1 = Path.Combine(dir, "Listener", "SolidWorksListener.exe");
            if (File.Exists(path1))
            {
                ProcessStartInfo info = new ProcessStartInfo
                {
                    FileName = path1,
                    WorkingDirectory = Path.GetDirectoryName(path1)
                };
 
                new Process
                {
                    StartInfo = info
                }.Start();
            }
        }
 
        public void Init()
        {
            label.Content = "准备更新程序...";
            bar.IsIndeterminate = true;
        }
 
        /// <summary>
        /// 初始化下载文件夹
        /// </summary>
        public void InitDownloadDir()
        {
            try
            {
                string tempDir = "temp";
                string downloadDir = "download";
                // 创建临时文件夹
                TempDir = $"{CurrentPath.FullName}{Path.DirectorySeparatorChar}{tempDir}";
                if (!Directory.Exists(TempDir))
                {
                    Directory.CreateDirectory(TempDir);
                }
                // 创建临时文件夹下的下载文件夹
                DownloadDir = $"{TempDir}{Path.DirectorySeparatorChar}{downloadDir}";
                if (!Directory.Exists(DownloadDir))
                {
                    Directory.CreateDirectory(DownloadDir);
                }
            }
            catch (Exception e)
            {
                Logger.Error("创建下载文件夹失败!异常:{0}", e);
                MessageBox.Show("创建下载文件夹失败!请重试", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(1);
            }
        }
 
        public void InitUnZipDir()
        {
            try
            {
                string tempDir = "temp";
                string unzipDir = "unzip";
                // 创建临时文件夹
                TempDir = $"{CurrentPath.FullName}{Path.DirectorySeparatorChar}{tempDir}";
                if (!Directory.Exists(TempDir))
                {
                    Directory.CreateDirectory(TempDir);
                }
                // 创建临时文件夹下的下载文件夹
                UnZipDir = $"{TempDir}{Path.DirectorySeparatorChar}{unzipDir}";
                if (!Directory.Exists(UnZipDir))
                {
                    Directory.CreateDirectory(UnZipDir);
                }
            }
            catch (Exception e)
            {
                Logger.Error("创建临时解压文件夹失败!异常:{0}", e);
                MessageBox.Show("创建临时解压文件夹失败!请重试", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(1);
            }
        }
 
        /// <summary>
        /// 先检查更新
        /// </summary>
        public void CheckPluginUpdate()
        {
            label.Content = "检查更新...";
            bar.IsIndeterminate = true;
            try
            {
                Dictionary<string, object> datas = new Dictionary<string, object>
                {
                    {
                        "params", new List<Dictionary<string, string>>
                        {
                           new Dictionary<string, string>
                           {
                               {"appId", AppId},
                               {"currentVersion", CurrentVersion},
                           }
                        }
                    }
                };
                Result<List<PluginInfo>> result =
                   HttpUtil.GetClient().PostSyncAction<List<PluginInfo>>(datas, "plugin/openApi/checkUpdate");
                List<PluginInfo> updates = result.HandleResult();
                if (updates == null || updates.Count <= 0)
                {
                    label.Content = "当前为最新版本!";
                    bar.IsIndeterminate = false;
                    return;
                }
                DownloadReleasePlugin(updates);
            }
            catch (Exception e)
            {
                Logger.Error("检查更新错误!异常:{0}", e);
                MessageBox.Show("检查更新错误!请重试", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                label.Content = "检查更新错误!请重试";
                bar.IsIndeterminate = false;
            }
        }
 
        /// <summary>
        /// 如果有需要更新的插件,就下载
        /// </summary>
        /// <param name="updates">需要更新的插件信息</param>
        private async void DownloadReleasePlugin(List<PluginInfo> updates)
        {
            InitDownloadDir();
            label.Content = "下载更新文件中,请勿关闭程序...";
            PluginInfo update = updates[0];
            try
            {
                string localFilePath = await HttpUtil.GetClient().GetDownload($"plugin/openApi/downloadReleasePlugin/{update.id}", DownloadDir, "Latest");
                UnZipAndUpdateFile(localFilePath);
            }
            catch (Exception e)
            {
                Logger.Error("下载更新文件错误!异常:{0}", e);
                MessageBox.Show("下载更新文件错误!请重试", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                label.Content = "下载更新文件错误!请重试";
                bar.IsIndeterminate = false;
            }
        }
 
        /// <summary>
        /// 下载压缩包后,解压缩并替换插件文件
        /// </summary>
        /// <param name="localFilePath">下载的zip路径</param>
        private async void UnZipAndUpdateFile(string localFilePath)
        {
            if (Path.GetExtension(localFilePath).ToLower() != ".zip")
            {
                return;
            }
            label.Content = "下载完成,解压中,请勿关闭程序...";
            // 临时解压目录,防止解压出错
            InitUnZipDir();
            // kill掉监听程序,避免文件占用
            KillListenerProcess();
            // 等待一秒释放exe占用
            Thread.Sleep(1000);
 
            // 插件文件夹 默认在 AutoUpdater.exe 的上级目录中
            string pluginDir = new DirectoryInfo(TempDir).Parent.Parent.FullName;
            using (ZipInputStream zipIn = new ZipInputStream(File.Open(localFilePath, FileMode.Open)))
            {
                ZipEntry zipEntry;
                while ((zipEntry = zipIn.GetNextEntry()) != null)
                {
                    string zipFileName = zipEntry.Name,
                        targetFileName;
                    zipFileName = zipFileName.Replace("AutoUpdater/", "WaitingUpdate/");
                    targetFileName = Path.Combine(pluginDir, zipFileName);
                    if (zipEntry.IsDirectory)
                    {
                        if (!Directory.Exists(targetFileName))
                        {
                            Directory.CreateDirectory(targetFileName);
                        }
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(targetFileName, FileMode.Create))
                        {
                            byte[] buffer = new byte[1024];
                            int readLength = 0;
                            int length;
                            while ((length = await zipIn.ReadAsync(buffer, 0, buffer.Length)) != 0)
                            {
                                readLength += length;
                                fs.Write(buffer, 0, length);
                            }
                        }
                    }
                }
            }
            DoFinished();
        }
 
        private void DoFinished()
        {
            // 启动监听进程
            StartListenerProcess();
            label.Content = "更新完成";
            bar.IsIndeterminate = false;
            if (SwAppPath != null)
            {
                MessageBoxResult mr = MessageBox.Show("更新完成,是否启动SolidWorks?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                if (mr == MessageBoxResult.OK)
                {
                    Process swProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = SwAppPath
                        }
                    };
                    swProcess.Start();
 
                }
            }
            Environment.Exit(0);
        }
 
        private void GetCurrentVersion()
        {
            Thread.Sleep(1000);
            try
            {
                var data = VersionUtil.GetRegPluginVersion();
                this.AppId = data[VersionUtil.APPID_KEY];
                this.CurrentVersion = data[VersionUtil.VERSION_KEY];
            }
            catch (NoSoftwareKeyException e)
            {
                Logger.Error("Get plugin version failed,SwPlugin software reg not found.", e);
                MessageBox.Show("获取插件当前版本失败!请打开插件重试");
                Environment.Exit(1);
            }
            catch (Exception e)
            {
                Logger.Error("Get plugin version failed.", e);
                MessageBox.Show("获取插件当前版本失败!请重试");
                Environment.Exit(1);
            }
        }
 
        private void Close_SwMainProcess()
        {
            try
            {
                Process swMainProcess = Process.GetProcessById(SwMainProcessId);
                if (swMainProcess != null)
                {
                    // 获取 SW 路径
                    SwAppPath = swMainProcess.MainModule.FileName;
                    swMainProcess.EnableRaisingEvents = true;
                    swMainProcess.Exited += new EventHandler(SwMainProcessExited);
                    if (!swMainProcess.CloseMainWindow())
                    {
                        MessageBoxResult mr = MessageBox.Show("不能关闭SolidWorks主窗口!请手动退出SolidWorks后点击确认按钮,或点击取消退出更新程序",
                     "错误", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                        if (mr == MessageBoxResult.OK)
                        {
                            Thread.Sleep(1000);
                            Close_SwMainProcess();
                        }
                        Environment.Exit(1);
                    }
                }
            }
            catch (Exception ex)
            {
                //Dispatcher.Invoke(new Action(delegate
                //{
                //    SwMainProcessId = -1;
                //    // 从exe文件中获取本地插件版本
                //    GetCurrentVersion();
                //    // 检查插件的更新
                //    CheckPluginUpdate();
                //}));
                Logger.Error("不能关闭 SolidWorks主窗口!异常:{0}", ex);
                MessageBoxResult mr = MessageBox.Show("不能关闭SolidWorks主窗口!请手动退出SolidWorks后点击确认按钮,或点击取消退出更新程序",
                    "错误", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                if (mr == MessageBoxResult.OK)
                {
                    Thread.Sleep(1000);
                    Close_SwMainProcess();
                }
                Environment.Exit(1);
            }
        }
 
        void SwMainProcessExited(object sender, object e)
        {
            Dispatcher.Invoke(new Action(delegate
            {
                SwMainProcessId = -1;
                // 从exe文件中获取本地插件版本
                GetCurrentVersion();
                // 检查插件的更新
                CheckPluginUpdate();
            }));
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            CheckPluginUpdate();
        }
    }
}