-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainForm.cs
More file actions
1540 lines (1363 loc) · 56.1 KB
/
MainForm.cs
File metadata and controls
1540 lines (1363 loc) · 56.1 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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
namespace FFmpegInstaller
{
public enum FFmpegBuildType
{
Full,
Essentials,
Shared
}
public enum InstallationScope
{
User,
System
}
public class BuildInfo
{
public FFmpegBuildType Type { get; set; }
public string Name { get; set; }
public string DownloadUrl { get; set; }
public string HashUrl { get; set; }
public string Description { get; set; }
public string ApproximateSize { get; set; }
public string FileName { get; set; }
}
public partial class MainForm : Form
{
private const string VERSION_URL = "https://www.gyan.dev/ffmpeg/builds/release-version";
private const string PORTABLE_7Z_URL = "https://www.7-zip.org/a/7za920.zip";
private const string APP_UPDATE_URL = "https://api.github.com/repos/oop7/ffmpeg-install-guide/releases/latest";
private const string REPO_URL = "https://github.com/oop7/ffmpeg-install-guide";
private const string CURRENT_VERSION = "2.6.0";
private static readonly Dictionary<FFmpegBuildType, BuildInfo> BuildInfos = new Dictionary<FFmpegBuildType, BuildInfo>
{
{
FFmpegBuildType.Full, new BuildInfo
{
Type = FFmpegBuildType.Full,
Name = "Full",
DownloadUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z",
HashUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z.sha256",
Description = "Complete build with all libraries and codecs (recommended for most users)",
ApproximateSize = "~60 MB",
FileName = "ffmpeg-release-full.7z"
}
},
{
FFmpegBuildType.Essentials, new BuildInfo
{
Type = FFmpegBuildType.Essentials,
Name = "Essentials",
DownloadUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.7z",
HashUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.7z.sha256",
Description = "Minimal build with essential codecs only (recommended for YTSage users)",
ApproximateSize = "~30 MB",
FileName = "ffmpeg-release-essentials.7z"
}
},
{
FFmpegBuildType.Shared, new BuildInfo
{
Type = FFmpegBuildType.Shared,
Name = "Shared",
DownloadUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full-shared.7z",
HashUrl = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full-shared.7z.sha256",
Description = "Full build with shared libraries (for developers)",
ApproximateSize = "~50 MB",
FileName = "ffmpeg-release-full-shared.7z"
}
}
};
private readonly string extractDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ffmpeg");
private readonly string tempExtractDir = Path.Combine(Path.GetTempPath(), "ffmpeg-extract");
private readonly string portable7z = Path.Combine(Path.GetTempPath(), "7z-zip\\7za.exe");
private readonly HttpClient httpClient = new HttpClient();
private string latestVersion = "Unknown";
private string expectedHash = null;
private bool isInstalling = false;
private FFmpegBuildType selectedBuildType = FFmpegBuildType.Full;
private InstallationScope installationScope = InstallationScope.User;
private string tempFile;
// UI Controls
private Label titleLabel;
private Label versionLabel;
private Label hashLabel;
private Label statusLabel;
private Label speedLabel;
private ProgressBar progressBar;
private Button installButton;
private Button aboutButton;
private Button exitButton;
private TextBox logTextBox;
private Panel headerPanel;
private Panel buttonPanel;
public MainForm()
{
InitializeComponent();
// Check if restarted with --system flag (after UAC elevation)
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1 && args[1] == "--system")
{
// Skip dialog, directly set to system-wide
installationScope = InstallationScope.System;
LogMessage("Installation scope: system-wide (elevated)");
statusLabel.Text = "Ready to install (system-wide)";
}
else
{
// Show dialog for user to choose
if (!ShowInstallationScopeDialog())
{
// User cancelled - close immediately without showing form
this.Load += (s, e) => this.Close();
return;
}
}
CheckAdminPrivileges();
_ = LoadVersionInfoAsync();
_ = CheckForUpdatesAsync();
}
private void InitializeComponent()
{
this.Text = "FFmpeg Installer";
this.Size = new Size(600, 500);
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
// Load custom icon
try
{
// Try to load from embedded resource first (for single file exe)
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("FFmpegInstaller.Icons.app_icon.ico"))
{
if (stream != null)
{
// Try different sizes to find the best match
var originalIcon = new Icon(stream);
// Try 48x48 first (common for desktop icons), then 32x32, then original
try
{
this.Icon = new Icon(originalIcon, 48, 48);
}
catch
{
try
{
this.Icon = new Icon(originalIcon, 32, 32);
}
catch
{
this.Icon = originalIcon; // Use original if sizing fails
}
}
}
else
{
// Fallback to file system
string iconPath = Path.Combine(Application.StartupPath, "Icons", "app_icon.ico");
if (File.Exists(iconPath))
{
var iconFromFile = new Icon(iconPath);
try
{
this.Icon = new Icon(iconFromFile, 48, 48);
}
catch
{
this.Icon = new Icon(iconFromFile, 32, 32);
}
}
else
{
this.Icon = SystemIcons.Application;
}
}
}
}
catch (Exception ex)
{
this.Icon = SystemIcons.Application;
LogMessage($"Icon loading failed: {ex.Message}");
}
// Header Panel
headerPanel = new Panel
{
Dock = DockStyle.Top,
Height = 120,
BackColor = Color.FromArgb(45, 45, 48)
};
titleLabel = new Label
{
Text = "FFmpeg Installer",
Font = new Font("Segoe UI", 16, FontStyle.Bold),
ForeColor = Color.White,
Location = new Point(20, 20),
Size = new Size(300, 30)
};
versionLabel = new Label
{
Text = "Loading version information...",
Font = new Font("Segoe UI", 9),
ForeColor = Color.LightGray,
Location = new Point(20, 55),
Size = new Size(500, 20)
};
hashLabel = new Label
{
Text = "Select a build to see hash information",
Font = new Font("Segoe UI", 9),
ForeColor = Color.LightGray,
Location = new Point(20, 75),
Size = new Size(500, 20)
};
headerPanel.Controls.AddRange(new Control[] { titleLabel, versionLabel, hashLabel });
// Status and Progress
statusLabel = new Label
{
Text = "Ready to install",
Font = new Font("Segoe UI", 9),
Location = new Point(20, 140),
Size = new Size(400, 20)
};
speedLabel = new Label
{
Text = "",
Font = new Font("Segoe UI", 9),
ForeColor = Color.FromArgb(0, 120, 215),
Location = new Point(430, 140),
Size = new Size(130, 20),
TextAlign = ContentAlignment.MiddleRight
};
progressBar = new ProgressBar
{
Location = new Point(20, 170),
Size = new Size(540, 25),
Style = ProgressBarStyle.Continuous
};
// Log TextBox
logTextBox = new TextBox
{
Location = new Point(20, 210),
Size = new Size(540, 200),
Multiline = true,
ScrollBars = ScrollBars.Vertical,
ReadOnly = true,
Font = new Font("Consolas", 9),
BackColor = Color.Black,
ForeColor = Color.White
};
// Button Panel
buttonPanel = new Panel
{
Dock = DockStyle.Bottom,
Height = 60,
BackColor = Color.FromArgb(240, 240, 240)
};
installButton = new Button
{
Text = "Install FFmpeg",
Size = new Size(120, 35),
Location = new Point(280, 12),
BackColor = Color.FromArgb(0, 120, 215),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 9, FontStyle.Bold)
};
installButton.Click += InstallButton_Click;
aboutButton = new Button
{
Text = "About",
Size = new Size(80, 35),
Location = new Point(410, 12),
BackColor = Color.FromArgb(100, 100, 100),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 9)
};
aboutButton.Click += AboutButton_Click;
exitButton = new Button
{
Text = "Exit",
Size = new Size(80, 35),
Location = new Point(500, 12),
BackColor = Color.FromArgb(160, 160, 160),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 9)
};
exitButton.Click += (s, e) => this.Close();
buttonPanel.Controls.AddRange(new Control[] { installButton, aboutButton, exitButton });
// Add all controls to form
this.Controls.AddRange(new Control[] { headerPanel, statusLabel, speedLabel, progressBar, logTextBox, buttonPanel });
}
private bool ShowInstallationScopeDialog()
{
var scopeForm = new Form
{
Text = "Installation Scope",
Size = new Size(500, 330),
StartPosition = FormStartPosition.CenterParent,
FormBorderStyle = FormBorderStyle.FixedDialog,
MaximizeBox = false,
MinimizeBox = false,
BackColor = Color.White
};
var titleLabel = new Label
{
Text = "Choose Installation Scope",
Font = new Font("Segoe UI", 12, FontStyle.Bold),
Location = new Point(20, 20),
Size = new Size(440, 25)
};
var descLabel = new Label
{
Text = "How would you like to install FFmpeg?",
Font = new Font("Segoe UI", 9),
ForeColor = Color.Gray,
Location = new Point(20, 50),
Size = new Size(440, 20)
};
var userRadio = new RadioButton
{
Text = "User Installation (Recommended)",
Font = new Font("Segoe UI", 9, FontStyle.Bold),
Location = new Point(30, 85),
Size = new Size(250, 20),
Checked = true
};
var userDesc = new Label
{
Text = "• No administrator privileges required\n• Available only for your user account\n• Installed in your AppData folder",
Font = new Font("Segoe UI", 8.25f),
ForeColor = Color.DarkGray,
Location = new Point(50, 108),
Size = new Size(400, 50)
};
var systemRadio = new RadioButton
{
Text = "System-wide Installation",
Font = new Font("Segoe UI", 9, FontStyle.Bold),
Location = new Point(30, 160),
Size = new Size(250, 20)
};
var systemDesc = new Label
{
Text = "• Requires administrator privileges\n• Available for all users on this computer\n• Installed in Program Files or similar",
Font = new Font("Segoe UI", 8.25f),
ForeColor = Color.DarkGray,
Location = new Point(50, 183),
Size = new Size(400, 50)
};
var continueButton = new Button
{
Text = "Continue",
Location = new Point(280, 245),
Size = new Size(100, 35),
DialogResult = DialogResult.OK,
BackColor = Color.FromArgb(0, 120, 215),
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 9, FontStyle.Bold)
};
continueButton.FlatAppearance.BorderSize = 0;
scopeForm.AcceptButton = continueButton;
var cancelButton = new Button
{
Text = "Cancel",
Location = new Point(390, 245),
Size = new Size(90, 35),
DialogResult = DialogResult.Cancel,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 9)
};
scopeForm.Controls.AddRange(new Control[] {
titleLabel, descLabel,
userRadio, userDesc,
systemRadio, systemDesc,
continueButton, cancelButton
});
var result = scopeForm.ShowDialog(this);
if (result == DialogResult.OK)
{
installationScope = userRadio.Checked ? InstallationScope.User : InstallationScope.System;
var scopeText = installationScope == InstallationScope.User ? "user-level" : "system-wide";
LogMessage($"Installation scope selected: {scopeText}");
statusLabel.Text = $"Ready to install ({scopeText})";
return true;
}
else
{
LogMessage("Installation cancelled by user");
return false;
}
}
private void CheckAdminPrivileges()
{
// Only require admin if system-wide installation is selected
if (installationScope == InstallationScope.System)
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
{
// Restart the application with admin privileges
try
{
var startInfo = new ProcessStartInfo
{
FileName = Application.ExecutablePath,
UseShellExecute = true,
Verb = "runas", // Request elevation
Arguments = "--system" // Pass flag to indicate system-wide install
};
Process.Start(startInfo);
Environment.Exit(0); // Immediate exit to prevent duplicate windows
}
catch (Exception ex)
{
// User cancelled UAC prompt or other error
LogMessage($"Failed to elevate privileges: {ex.Message}");
MessageBox.Show("Administrator privileges are required for system-wide installation.\n\nPlease approve the UAC prompt or choose User Installation instead.",
"Administrator Required", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Environment.Exit(1);
}
}
else
{
LogMessage("System-wide installation with administrator privileges");
}
}
}
else
{
LogMessage("User installation selected - administrator privileges not required");
}
}
private async Task LoadVersionInfoAsync()
{
try
{
// Get version
latestVersion = (await httpClient.GetStringAsync(VERSION_URL)).Trim();
versionLabel.Text = $"Latest Version: {latestVersion}";
LogMessage($"Latest FFmpeg version: {latestVersion}");
}
catch (Exception ex)
{
versionLabel.Text = "Version: Could not fetch";
LogMessage($"Warning: Could not fetch version info: {ex.Message}");
}
}
private async Task LoadHashForBuildAsync(FFmpegBuildType buildType)
{
try
{
var buildInfo = BuildInfos[buildType];
var hashResponse = await httpClient.GetStringAsync(buildInfo.HashUrl);
expectedHash = hashResponse.Trim().Split()[0];
hashLabel.Text = $"SHA256: {expectedHash}";
LogMessage($"Expected hash for {buildInfo.Name} build: {expectedHash}");
}
catch (Exception ex)
{
hashLabel.Text = "Hash: Could not fetch";
LogMessage($"Warning: Could not fetch hash info: {ex.Message}");
}
}
private async void InstallButton_Click(object sender, EventArgs e)
{
if (isInstalling) return;
// Show build selection dialog
var selectedBuild = ShowBuildSelectionDialog();
if (selectedBuild == null)
{
LogMessage("Installation cancelled by user");
return;
}
selectedBuildType = selectedBuild.Value;
var buildInfo = BuildInfos[selectedBuildType];
tempFile = Path.Combine(Path.GetTempPath(), buildInfo.FileName);
// Load hash for selected build
await LoadHashForBuildAsync(selectedBuildType);
var result = MessageBox.Show(
$"This will install FFmpeg {latestVersion} ({buildInfo.Name} build) to:\n{extractDir}\n\nAnd add it to your system PATH.\n\nProceed?",
"Confirm Installation",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
await InstallFFmpegAsync();
}
}
private async Task InstallFFmpegAsync()
{
isInstalling = true;
installButton.Enabled = false;
progressBar.Value = 0;
try
{
// Step 1: Clean up previous installation
UpdateStatus("Cleaning up previous installation...");
CleanupPreviousInstallation();
progressBar.Value = 10;
var downloaded = false;
if (File.Exists(tempFile))
{
if (VerifyFileHash())
{
UpdateStatus("✓ There has downloaded file and hash verification successful");
downloaded = true;
progressBar.Value = 40;
}
else
{
File.Delete(tempFile);
}
}
if (!downloaded)
{
// Step 2: Download FFmpeg
var currentBuild = BuildInfos[selectedBuildType];
UpdateStatus($"Downloading FFmpeg ({currentBuild.Name} build)...");
await DownloadFFmpegAsync();
progressBar.Value = 40;
// Step 3: Verify hash
UpdateStatus("Verifying file integrity...");
if (!VerifyFileHash())
{
throw new Exception("File integrity verification failed");
}
}
progressBar.Value = 50;
// Step 4: Extract files
UpdateStatus("Extracting files...");
await ExtractFilesAsync();
progressBar.Value = 80;
// Step 5: Install and configure
UpdateStatus("Installing and configuring...");
InstallAndConfigure();
progressBar.Value = 95;
// Step 6: Test installation
UpdateStatus("Testing installation...");
TestInstallation();
progressBar.Value = 100;
var buildInfo = BuildInfos[selectedBuildType];
var scopeText = installationScope == InstallationScope.User ? "user-level" : "system-wide";
UpdateStatus($"Installation of {buildInfo.Name} build completed successfully!");
LogMessage($"✓ FFmpeg {buildInfo.Name} build ({scopeText}) installation completed successfully!");
var restartMessage = installationScope == InstallationScope.User
? "Please restart your command prompt or applications to use ffmpeg."
: "Please restart your command prompt to use ffmpeg.";
MessageBox.Show($"FFmpeg ({buildInfo.Name} build) has been installed successfully as a {scopeText} installation!\n\n{restartMessage}",
"Installation Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
UpdateStatus($"Installation failed: {ex.Message}");
LogMessage($"✗ Installation failed: {ex.Message}");
MessageBox.Show($"Installation failed:\n\n{ex.Message}", "Installation Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
//CleanupTempFiles();//don't clearnup,because the downloaded file can be use next time.
isInstalling = false;
installButton.Enabled = true;
}
}
private void CleanupPreviousInstallation()
{
try
{
if (Directory.Exists(extractDir))
{
Directory.Delete(extractDir, true);
LogMessage("Previous installation cleaned up");
}
}
catch (Exception ex)
{
LogMessage($"Warning: Could not clean up previous installation: {ex.Message}");
}
}
private async Task DownloadFFmpegAsync()
{
try
{
var buildInfo = BuildInfos[selectedBuildType];
LogMessage($"Starting download of {buildInfo.Name} build...");
using (var response = await httpClient.GetAsync(buildInfo.DownloadUrl, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength ?? 0;
var downloadedBytes = 0L;
var startTime = DateTime.Now;
var lastUpdateTime = startTime;
var lastDownloadedBytes = 0L;
using (var contentStream = await response.Content.ReadAsStreamAsync())
using (var fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
{
var buffer = new byte[8192];
int bytesRead;
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fileStream.WriteAsync(buffer, 0, bytesRead);
downloadedBytes += bytesRead;
var currentTime = DateTime.Now;
var timeElapsed = currentTime - lastUpdateTime;
// Update speed every 500ms
if (timeElapsed.TotalMilliseconds >= 500)
{
var bytesSinceLastUpdate = downloadedBytes - lastDownloadedBytes;
var speedBytesPerSecond = bytesSinceLastUpdate / timeElapsed.TotalSeconds;
var speedText = FormatSpeed(speedBytesPerSecond);
UpdateSpeedDisplay(speedText);
lastUpdateTime = currentTime;
lastDownloadedBytes = downloadedBytes;
}
if (totalBytes > 0)
{
var progress = (int)((downloadedBytes * 30) / totalBytes) + 10; // 10-40%
progressBar.Value = Math.Min(progress, 40);
}
}
}
}
// Clear speed display when download is complete
UpdateSpeedDisplay("");
var fileInfo = new FileInfo(tempFile);
LogMessage($"Download completed: {fileInfo.Length / 1024 / 1024:F2} MB");
}
catch (Exception ex)
{
UpdateSpeedDisplay("");
throw new Exception($"Download failed: {ex.Message}");
}
}
private bool VerifyFileHash()
{
if (string.IsNullOrEmpty(expectedHash))
{
LogMessage("Skipping hash verification (hash not available)");
return true;
}
try
{
using (var sha256 = SHA256.Create())
using (var fileStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read))
{
var hashBytes = sha256.ComputeHash(fileStream);
var actualHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
if (actualHash.Equals(expectedHash, StringComparison.OrdinalIgnoreCase))
{
LogMessage("✓ File hash verification successful");
return true;
}
else
{
LogMessage($"✗ Hash mismatch!");
LogMessage($"Expected: {expectedHash}");
LogMessage($"Actual: {actualHash}");
return false;
}
}
}
catch (Exception ex)
{
LogMessage($"Hash verification error: {ex.Message}");
return false;
}
}
private async Task ExtractFilesAsync()
{
// Clean up temp extract directory
if (Directory.Exists(tempExtractDir))
{
Directory.Delete(tempExtractDir, true);
}
Directory.CreateDirectory(tempExtractDir);
// Try multiple extraction methods
if (await TryExtractWithPortable7z())
{
LogMessage("✓ Extraction completed using portable 7z");
return;
}
if (await TryExtractWithComObject())
{
LogMessage("✓ Extraction completed using COM object");
return;
}
if (TryExtractAsZip())
{
LogMessage("✓ Extraction completed using ZIP method");
return;
}
throw new Exception("All extraction methods failed");
}
private async Task<bool> TryExtractWithPortable7z()
{
try
{
LogMessage("Attempting extraction with portable 7z...");
if (!File.Exists(portable7z))
{
LogMessage("Downloading portable 7z...");
await DownloadPortable7z();
}
var startInfo = new ProcessStartInfo
{
FileName = portable7z,
Arguments = $"x \"{tempFile}\" -o\"{tempExtractDir}\" -y",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = false,
RedirectStandardError = true
};
using (var process = Process.Start(startInfo))
{
var error = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
bool success = process.ExitCode == 0;
if (!success && !string.IsNullOrEmpty(error))
{
LogMessage($"Portable 7z extraction failed: {Environment.NewLine}{error}");
}
return success;
}
}
catch (Exception ex)
{
LogMessage($"Portable 7z extraction failed: {ex.Message}");
return false;
}
}
private async Task DownloadPortable7z()
{
var tempZipFile = Path.Combine(Path.GetTempPath(), "7za.zip");
using (var response = await httpClient.GetAsync(PORTABLE_7Z_URL))
{
response.EnsureSuccessStatusCode();
using (var fileStream = new FileStream(tempZipFile, FileMode.Create))
{
await response.Content.CopyToAsync(fileStream);
}
}
ZipFile.ExtractToDirectory(tempZipFile, Path.GetTempPath() + "7z-zip");
//File.Delete(tempZipFile);
}
private async Task<bool> TryExtractWithComObject()
{
try
{
LogMessage("Attempting extraction with COM object...");
dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
dynamic zip = shell.NameSpace(tempFile);
dynamic dest = shell.NameSpace(tempExtractDir);
if (zip == null) return false;
dest.CopyHere(zip.Items(), 4);
// Wait for extraction to complete
var timeout = DateTime.Now.AddSeconds(60);
while (DateTime.Now < timeout)
{
if (Directory.GetDirectories(tempExtractDir).Length > 0 ||
Directory.GetFiles(tempExtractDir).Length > 0)
{
return true;
}
await Task.Delay(1000);
}
return false;
}
catch (Exception ex)
{
LogMessage($"COM object extraction failed: {ex.Message}");
return false;
}
}
private bool TryExtractAsZip()
{
try
{
LogMessage("Attempting extraction as ZIP...");
var tempZipFile = Path.ChangeExtension(tempFile, ".zip");
File.Copy(tempFile, tempZipFile, true);
ZipFile.ExtractToDirectory(tempZipFile, tempExtractDir);
File.Delete(tempZipFile);
return true;
}
catch (Exception ex)
{
LogMessage($"ZIP extraction failed: {ex.Message}");
return false;
}
}
private void InstallAndConfigure()
{
// Find extracted FFmpeg folder
var ffmpegDir = FindFFmpegDirectory(tempExtractDir);
if (ffmpegDir == null)
{
throw new Exception("FFmpeg directory not found in extracted files");
}
LogMessage($"Found FFmpeg at: {ffmpegDir}");
// Copy to final destination
Directory.CreateDirectory(extractDir);
CopyDirectory(ffmpegDir, Path.Combine(extractDir, Path.GetFileName(ffmpegDir)));
// Find bin directory
var binDir = Path.Combine(extractDir, Path.GetFileName(ffmpegDir), "bin");
if (!Directory.Exists(binDir) || !File.Exists(Path.Combine(binDir, "ffmpeg.exe")))
{
throw new Exception("FFmpeg executable not found after installation");
}
// Add to PATH
AddToSystemPath(binDir);
LogMessage($"Added to system PATH: {binDir}");
}
private string FindFFmpegDirectory(string searchDir)
{
// Look for directory containing bin/ffmpeg.exe
foreach (var dir in Directory.GetDirectories(searchDir, "*", SearchOption.AllDirectories))
{
var binPath = Path.Combine(dir, "bin", "ffmpeg.exe");
if (File.Exists(binPath))
{
return dir;
}
}
return null;
}
private void CopyDirectory(string sourceDir, string destDir)
{
Directory.CreateDirectory(destDir);
foreach (var file in Directory.GetFiles(sourceDir))
{
var destFile = Path.Combine(destDir, Path.GetFileName(file));
File.Copy(file, destFile, true);
}
foreach (var dir in Directory.GetDirectories(sourceDir))
{
var destSubDir = Path.Combine(destDir, Path.GetFileName(dir));
CopyDirectory(dir, destSubDir);
}
}
private void AddToSystemPath(string path)
{
try
{
RegistryKey key;
string pathType;
if (installationScope == InstallationScope.User)
{
// User-level PATH (HKEY_CURRENT_USER)
key = Registry.CurrentUser.OpenSubKey("Environment", true);
pathType = "user PATH";
}
else
{
// System-level PATH (HKEY_LOCAL_MACHINE)
key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true);
pathType = "system PATH";
}
using (key)
{
var currentPath = key.GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames).ToString();
if (!currentPath.Contains(path))
{
var newPath = string.IsNullOrEmpty(currentPath) ? path : $"{currentPath};{path}";
key.SetValue("PATH", newPath, RegistryValueKind.ExpandString);
LogMessage($"Successfully added to {pathType}");