forked from nuttylmao/NOOBS-CMDR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
1361 lines (1185 loc) · 57.8 KB
/
MainWindow.xaml.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
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 GongSolutions.Wpf.DragDrop;
using Microsoft.Win32;
using NOOBS_CMDR.Extensions;
using NOOBS_CMDR.Commands;
using OBSWebsocketDotNet;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Security.Principal;
namespace NOOBS_CMDR
{
public partial class NOOBS_CMDR_Homepage : Window, IDropTarget, INotifyPropertyChanged
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion INotifyPropertyChanged
#region Properties
public string WindowTitle
{
get
{
Version version = Assembly.GetExecutingAssembly().GetName().Version;
return "NOOBS CMDR v" + version;
}
}
#endregion Properties
#region Variables
private OBSWebsocket _obs;
public OBSWebsocket obs
{
get { return _obs; }
set
{
if (value != _obs)
{
_obs = value;
OnPropertyChanged();
}
}
}
private ObservableCollection<CommandType> CommandTypes = new ObservableCollection<CommandType>();
private ObservableCollection<Command> Commands = new ObservableCollection<Command>();
private ObservableCollection<Command> CommandsCopyStack = new ObservableCollection<Command>();
#endregion Variables
#region Constructors
public NOOBS_CMDR_Homepage()
{
InitializeComponent();
this.DataContext = this;
// Check that all OBSCommand files exist and that environment PATH variable is set up
if (!OBSCommandExists())
{
// OBSCommand not found, so need to install it but this needs to be done in admin mode
if (!IsAdministrator())
{
MessageBox.Show(@"Please restart in admin mode to install OBSCommand.", "OBSCommand Not Installed", MessageBoxButton.OK, MessageBoxImage.Warning);
System.Environment.Exit(1);
}
else
{
// Ask user to select directory
const string message ="Before using NOOBS CMDR, you must install OBSCommand. Choose a directory to install OBSCommand.";
const string caption = "NOOBS CMDR Install";
var result = MessageBox.Show(message, caption,
MessageBoxButton.OKCancel,
MessageBoxImage.Question);
if (result == MessageBoxResult.OK)
{
// Check that all OBSCommand files exist in NOOBS CMDR folder
string sourcePath = $"{System.AppDomain.CurrentDomain.BaseDirectory}OBSCommand";
// If they don't exist, we can't install OBSCommand
if (!File.Exists($"{sourcePath}\\OBSCommand.exe") || !File.Exists($"{sourcePath}\\Newtonsoft.Json.dll") || !File.Exists($"{sourcePath}\\obs-websocket-dotnet.dll") || !File.Exists($"{sourcePath}\\websocket-sharp.dll"))
{
MessageBox.Show(@"Could not find OBSCommand Files. Please re-download NOOBS CMDR.", "OBSCommand Files Missing", MessageBoxButton.OK, MessageBoxImage.Warning);
System.Environment.Exit(1);
}
// Ask user to select directory
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
// Default to the Program Files directory
dlg.SelectedPath = Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable("ProgramFiles(x86)") : Environment.GetEnvironmentVariable("ProgramFiles");
// User selects OK
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedPath = $"{dlg.SelectedPath}\\OBSCommand";
// Create OBSCommand folder automatically + copy all OBSCommand files
Directory.CreateDirectory($"{dlg.SelectedPath}\\OBSCommand");
File.Copy($"{sourcePath}\\OBSCommand.exe", $"{selectedPath}\\OBSCommand.exe", true);
File.Copy($"{sourcePath}\\Newtonsoft.Json.dll", $"{selectedPath}\\Newtonsoft.Json.dll", true);
File.Copy($"{sourcePath}\\obs-websocket-dotnet.dll", $"{selectedPath}\\obs-websocket-dotnet.dll", true);
File.Copy($"{sourcePath}\\websocket-sharp.dll", $"{selectedPath}\\websocket-sharp.dll", true);
// Check the environment PATH variable
string enviromentPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
// If the selected directory does not exist in the PATH variable, we need to add it
if (!enviromentPath.Contains(selectedPath))
{
Environment.SetEnvironmentVariable("PATH", $"{enviromentPath};{selectedPath}", EnvironmentVariableTarget.Machine);
}
MessageBox.Show(@"NOOBS CMDR is now ready to use.", "OBSCommand Successfully Installed", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
System.Environment.Exit(1);
}
}
else
{
System.Environment.Exit(1);
}
}
}
ServerText.Text = ConfigurationManager.AppSettings.Get("Server");
PortText.Text = ConfigurationManager.AppSettings.Get("Port");
PasswordText.Password = ConfigurationManager.AppSettings.Get("Password");
obs = new OBSWebsocket();
obs.Connected += Obs_Connected;
obs.Disconnected += Obs_Disconnected;
Connect();
CommandTypeList.ItemsSource = CommandTypes;
CommandListBox.ItemsSource = Commands;
CollectionView view = CollectionViewSource.GetDefaultView(CommandTypeList.ItemsSource) as CollectionView;
view.Filter = CommandTypeListFilter;
CreateActionTypes();
}
#region Filters
private void Searchbar_SearchTextChanged(object sender, EventArgs e)
{
if (CommandTypeList.ItemsSource != null)
{
CollectionViewSource.GetDefaultView(CommandTypeList.ItemsSource).Refresh();
}
}
public bool CommandTypeListFilter(object commandType)
{
if (string.IsNullOrEmpty(CommandTypeListSearch.Text))
{
return true;
}
else
{
return (
(commandType as CommandType).commandTypeDesc.ToString().IndexOf(CommandTypeListSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0);
}
}
#endregion Filters
#endregion Constructors
#region Functions
public static bool IsAdministrator()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public bool OBSCommandExists()
{
var enviromentPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
var paths = enviromentPath.Split(';');
var exePath = paths.Select(x => Path.Combine(x, "OBSCommand.exe"))
.Where(x => File.Exists(x))
.FirstOrDefault();
if (string.IsNullOrWhiteSpace(exePath))
{
return false;
}
string path = exePath.Replace(@"\OBSCommand.exe", "");
return
File.Exists($"{path}\\OBSCommand.exe")
&& File.Exists($"{path}\\Newtonsoft.Json.dll")
&& File.Exists($"{path}\\obs-websocket-dotnet.dll")
&& File.Exists($"{path}\\websocket-sharp.dll");
}
private void CreateActionTypes()
{
CommandTypes.Add(new CommandType("Stream", CommandType.Type.Stream));
CommandTypes.Add(new CommandType("Record", CommandType.Type.Record));
CommandTypes.Add(new CommandType("Profile", CommandType.Type.Profile));
CommandTypes.Add(new CommandType("Scene", CommandType.Type.Scene));
CommandTypes.Add(new CommandType("Source", CommandType.Type.Source));
CommandTypes.Add(new CommandType("Filter", CommandType.Type.Filter));
CommandTypes.Add(new CommandType("Audio", CommandType.Type.Audio));
CommandTypes.Add(new CommandType("Media Control", CommandType.Type.Media));
CommandTypes.Add(new CommandType("Transition", CommandType.Type.Transition));
CommandTypes.Add(new CommandType("Studio Mode", CommandType.Type.StudioMode));
CommandTypes.Add(new CommandType("Screenshot", CommandType.Type.Screenshot));
CommandTypes.Add(new CommandType("Replay Buffer", CommandType.Type.ReplayBuffer));
CommandTypes.Add(new CommandType("Projector", CommandType.Type.Projector));
CommandTypes.Add(new CommandType("Delay", CommandType.Type.Delay));
CommandTypes.Add(new CommandType("Custom", CommandType.Type.Custom));
}
#endregion Functions
#region Page Actions
private void CommandList_MouseDown(object sender, MouseButtonEventArgs e)
{
// Deselect when click outside of items
HitTestResult r = VisualTreeHelper.HitTest(this, e.GetPosition(this));
if (r.VisualHit.GetType() != typeof(ListBoxItem))
CommandListBox.UnselectAll();
}
private void CommandTypeList_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var item = ItemsControl.ContainerFromElement(sender as ListBox, e.OriginalSource as DependencyObject) as ListBoxItem;
if (item == null)
return;
if (item.Content.GetType() != typeof(CommandType))
return;
CommandType commandType = (CommandType)item.Content;
switch (commandType.commandTypeID)
{
case CommandType.Type.Stream:
Commands.Add(new StreamCommand(obs));
break;
case CommandType.Type.Record:
Commands.Add(new RecordingCommand(obs));
break;
case CommandType.Type.Profile:
Commands.Add(new ProfileCommand(obs));
break;
case CommandType.Type.Scene:
Commands.Add(new SceneCommand(obs));
break;
case CommandType.Type.Source:
Commands.Add(new SourceCommand(obs));
break;
case CommandType.Type.Filter:
Commands.Add(new FilterCommand(obs));
break;
case CommandType.Type.Audio:
Commands.Add(new AudioCommand(obs));
break;
case CommandType.Type.Media:
Commands.Add(new MediaCommand(obs));
break;
case CommandType.Type.Transition:
Commands.Add(new TransitionCommand(obs));
break;
case CommandType.Type.StudioMode:
Commands.Add(new StudioModeCommand(obs));
break;
case CommandType.Type.Screenshot:
Commands.Add(new ScreenshotCommand(obs));
break;
case CommandType.Type.ReplayBuffer:
Commands.Add(new ReplayBufferCommand(obs));
break;
case CommandType.Type.Projector:
Commands.Add(new ProjectorCommand(obs));
break;
case CommandType.Type.Delay:
Commands.Add(new DelayCommand(obs));
break;
default:
Commands.Add(new CustomCommand(obs));
break;
}
// Scroll to end of list
CommandListBox.ScrollIntoView(CommandListBox.Items[CommandListBox.Items.Count - 1]);
}
private void CommandListBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
DeleteCommands(CommandListBox.SelectedItems.OfType<Command>().ToList());
}
}
#endregion Page Actions
#region Connect
private void Connect()
{
if (!obs.IsConnected)
{
string server = ServerText.Text;
string port = PortText.Text;
string password = PasswordText.Password;
try
{
obs.Connect(@"ws://" + server + ":" + port, password);
}
catch (AuthFailureException)
{
MessageBox.Show("Authentication failed.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
obs.Disconnect();
return;
}
catch (ErrorResponseException ex)
{
MessageBox.Show("Connect failed : " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
catch (Exception ex)
{
MessageBox.Show("Connect failed : " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
}
else
{
obs.Disconnect();
}
}
private void Obs_Connected(object sender, EventArgs e)
{
OnPropertyChanged("obs");
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings["Server"].Value = ServerText.Text;
configuration.AppSettings.Settings["Port"].Value = PortText.Text;
configuration.AppSettings.Settings["Password"].Value = PasswordText.Password;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
private void Obs_Disconnected(object sender, EventArgs e)
{
OnPropertyChanged("obs");
}
private void ConnectBtn_Click(object sender, RoutedEventArgs e)
{
Connect();
}
#endregion
#region Test Command
private void TestCommands(List<Command> commandList)
{
if (!OBSCommandExists())
{
MessageBox.Show(@"Please restart in admin mode to install OBSCommand.", "OBSCommand Not Installed", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
string strCmdText;
strCmdText = string.Format(@"/server={0}:{1} /password=""{2}""", ServerText.Text, PortText.Text, PasswordText.Password);
foreach (Command command in commandList)
{
Console.WriteLine(command.ToString());
strCmdText += " " + command.ToString().ReplaceTimestamp();
}
Console.WriteLine(strCmdText);
var enviromentPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
var paths = enviromentPath.Split(';');
var exePath = paths.Select(x => Path.Combine(x, "OBSCommand.exe"))
.Where(x => File.Exists(x))
.FirstOrDefault();
Process process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
FileName = exePath,
Arguments = strCmdText
}
};
try
{
process.Start();
}
catch (Exception ex)
{
MessageBox.Show("Test failed : " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
}
private void TestCommandBtn_Click(object sender, RoutedEventArgs e)
{
TestCommands(Commands.ToList());
}
private void Test_MenuItem_Click(object sender, RoutedEventArgs e)
{
TestCommands(CommandListBox.SelectedItems.OfType<Command>().ToList());
}
#endregion Test Command
#region Copy Commands
private void CopyCommands(List<Command> commandList)
{
CommandsCopyStack.Clear();
List<Command> reverseList = commandList;
reverseList.Reverse();
foreach (var command in reverseList)
CommandsCopyStack.Add(command.Clone());
}
private void Copy_MenuItem_Click(object sender, RoutedEventArgs e)
{
CopyCommands(CommandListBox.SelectedItems.OfType<Command>().ToList());
}
#endregion Copy Commands
#region Paste Commands
private void PasteCommands(int row)
{
foreach (var command in CommandsCopyStack)
Commands.Insert(row, command.Clone());
}
private void Paste_MenuItem_Click(object sender, RoutedEventArgs e)
{
int row = 0;
if (CommandListBox.SelectedItems.Count <= 0)
{
row = CommandListBox.Items.Count;
}
else if (CommandListBox.SelectedItems.Count == 1)
{
row = CommandListBox.SelectedIndex + 1;
}
else if (CommandListBox.SelectedItems.Count > 1)
{
foreach (var item in CommandListBox.SelectedItems)
{
row = CommandListBox.Items.IndexOf(item) > row ? CommandListBox.Items.IndexOf(item) : row;
}
row = row + 1;
}
PasteCommands(row);
}
#endregion Paste Commands
#region Delete Commands
private void DeleteCommands(List<Command> commandList)
{
foreach (var command in commandList)
Commands.Remove(command);
}
private void Delete_MenuItem_Click(object sender, RoutedEventArgs e)
{
DeleteCommands(CommandListBox.SelectedItems.OfType<Command>().ToList());
}
#endregion Delete Commands
#region Duplicate Commands
private void DuplicateCommands(List<Command> commandList)
{
int row = 0;
if (CommandListBox.SelectedItems.Count <= 0)
{
row = CommandListBox.Items.Count;
}
else if (CommandListBox.SelectedItems.Count == 1)
{
row = CommandListBox.SelectedIndex + 1;
}
else if (CommandListBox.SelectedItems.Count > 1)
{
foreach (var item in CommandListBox.SelectedItems)
{
row = CommandListBox.Items.IndexOf(item) > row ? CommandListBox.Items.IndexOf(item) : row;
}
row = row + 1;
}
List<Command> reverseList = commandList;
reverseList.Reverse();
foreach (var command in reverseList)
Commands.Insert(row, command.Clone());
}
private void Duplicate_MenuItem_Click(object sender, RoutedEventArgs e)
{
DuplicateCommands(CommandListBox.SelectedItems.OfType<Command>().ToList());
}
#endregion Duplicate Commands
#region Export to Script
private void ExportBtn_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Batch Script (*.bat)|*.bat|VBS Script (*.vbs)|*.vbs";
if (dlg.ShowDialog() == true)
{
string path = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf("\\") + 1);
string filename = Path.GetFileNameWithoutExtension(dlg.FileName);
File.WriteAllText(string.Format(@"{0}\\{1}.bat", path, filename), CommandsToBatch(Commands.ToList()));
File.WriteAllText(string.Format(@"{0}\\{1}.vbs", path, filename), CommandsToVBS(Commands.ToList()), System.Text.Encoding.Unicode);
}
}
private string CommandsToBatch(List<Command> commandList)
{
string strCmdText = string.Format(@"::::: GENERATED WITH NOOBS CMDR v{0} :::::", typeof(NOOBS_CMDR_Homepage).Assembly.GetName().Version);
strCmdText += Environment.NewLine;
strCmdText += @"chcp 65001";
strCmdText += Environment.NewLine;
strCmdText += Environment.NewLine;
// Need to set up date variable for screenshots
if (commandList.OfType<ScreenshotCommand>().Where(x => x.createNewFile).ToList().Count > 0)
{
strCmdText += @"FOR /f ""tokens=2 delims=="" %%G in ('wmic os get localdatetime /value') do set datetime=%%G";
strCmdText += Environment.NewLine;
strCmdText += @"SET hh=%time:~0,2%";
strCmdText += Environment.NewLine;
strCmdText += @"SET hh=%hh: =0%";
strCmdText += Environment.NewLine;
strCmdText += @"SET datetime=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2% %hh%-%time:~3,2%-%time:~6,2%";
strCmdText += Environment.NewLine;
strCmdText += Environment.NewLine;
}
strCmdText += string.Format(@"OBSCommand.exe /server={0}:{1} /password=""{2}""", ServerText.Text, PortText.Text, PasswordText.Password);
foreach (Command command in commandList)
{
strCmdText += " " + command.ToString().ReplaceTimestamp(StringExtensions.TimestampType.Batch);
}
return strCmdText;
}
private string CommandsToVBS(List<Command> commandList)
{
string strCmdText = string.Format(@"''''' GENERATED WITH NOOBS CMDR v{0} '''''", typeof(NOOBS_CMDR_Homepage).Assembly.GetName().Version);
strCmdText += Environment.NewLine;
strCmdText += Environment.NewLine;
// Need to set up date variable for screenshots
if (commandList.OfType<ScreenshotCommand>().Where(x => x.createNewFile).ToList().Count > 0)
{
strCmdText += @"Dim g_oSB : Set g_oSB = CreateObject(""System.Text.StringBuilder"")";
strCmdText += Environment.NewLine;
strCmdText += @"Function sprintf(sFmt, aData)";
strCmdText += Environment.NewLine;
strCmdText += @" g_oSB.AppendFormat_4 sFmt, (aData)";
strCmdText += Environment.NewLine;
strCmdText += @" sprintf = g_oSB.ToString()";
strCmdText += Environment.NewLine;
strCmdText += @" g_oSB.Length = 0";
strCmdText += Environment.NewLine;
strCmdText += @"End Function";
strCmdText += Environment.NewLine;
strCmdText += @"Dim datetime : datetime = now()";
strCmdText += Environment.NewLine;
strCmdText += Environment.NewLine;
}
strCmdText += @"Set WshShell = CreateObject(""WScript.Shell"")";
strCmdText += Environment.NewLine;
strCmdText += string.Format(@"WshShell.Run ""OBSCommand.exe /server={0}:{1} /password=""""{2}""""", ServerText.Text, PortText.Text, PasswordText.Password);
foreach (Command command in commandList)
{
strCmdText += " " + command.ToString().Replace(@"""", @"""""").ReplaceTimestamp(StringExtensions.TimestampType.VBS);
}
strCmdText += @""", 0";
return strCmdText;
}
#endregion Export to Script
#region Import Script
private void ImportBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Batch Script (*.bat)|*.bat|VBS Script (*.vbs)|*.vbs";
if (dlg.ShowDialog() == true)
{
if (dlg.FileName.ToLower().EndsWith(".bat") || dlg.FileName.ToLower().EndsWith(".vbs"))
{
string contents;
//Read the contents of the file into a stream
var fileStream = dlg.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
contents = reader.ReadToEnd();
}
if (dlg.FileName.ToLower().EndsWith(".bat"))
{
ImportFromBatch(contents);
}
else if (dlg.FileName.ToLower().EndsWith(".vbs"))
{
ImportFromVBS(contents);
}
}
else
{
// Do nothing
}
}
}
private void ImportFromBatch(string contents)
{
Commands.Clear();
string[] lines = contents.Split(
new[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
);
foreach (string line in lines)
{
if (line.StartsWith("OBSCommand.exe"))
{
string[] contentArray = Regex.Split(line, "[ ](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
foreach (string cmdText in contentArray)
{
if (cmdText.StartsWith("OBSCommand.exe"))
{
// Do nothing
}
else if (cmdText.StartsWith("/server"))
{
// Do nothing
}
else if (cmdText.StartsWith("/password"))
{
// Do nothing
}
else if (cmdText == "/startstream")
{
Commands.Add(new StreamCommand(obs)
{
streamingStatus = StreamCommand.Status.Start
});
}
else if (cmdText == "/stopstream")
{
Commands.Add(new StreamCommand(obs)
{
streamingStatus = StreamCommand.Status.Stop
});
}
else if (cmdText == "/command=StartStopStreaming")
{
Commands.Add(new StreamCommand(obs)
{
streamingStatus = StreamCommand.Status.Toggle
});
}
else if (cmdText == "/startrecording")
{
Commands.Add(new RecordingCommand(obs)
{
recordingStatus = RecordingCommand.Status.Start
});
}
else if (cmdText == "/stoprecording")
{
Commands.Add(new RecordingCommand(obs)
{
recordingStatus = RecordingCommand.Status.Stop
});
}
else if (cmdText == "/command=StartStopRecording")
{
Commands.Add(new RecordingCommand(obs)
{
recordingStatus = RecordingCommand.Status.Toggle
});
}
else if (cmdText == "/command=PauseRecording")
{
Commands.Add(new RecordingCommand(obs)
{
recordingStatus = RecordingCommand.Status.Pause
});
}
else if (cmdText == "/command=ResumeRecording")
{
Commands.Add(new RecordingCommand(obs)
{
recordingStatus = RecordingCommand.Status.Resume
});
}
else if (cmdText.StartsWith("/profile="))
{
Commands.Add(new ProfileCommand(obs)
{
profileName = cmdText.RemoveBeforeChar('=').RemoveQuotes()
});
}
else if (cmdText.StartsWith("/scene="))
{
Commands.Add(new SceneCommand(obs)
{
sceneName = cmdText.RemoveBeforeChar('=').RemoveQuotes()
});
}
else if (cmdText.StartsWith("/showsource=") || cmdText.StartsWith("/hidesource=") || cmdText.StartsWith("/togglesource="))
{
string[] sourceArray = Regex.Split(cmdText.RemoveBeforeChar('='), "[/](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
SourceCommand.State sourceState;
if (cmdText.StartsWith("/showsource="))
{
sourceState = SourceCommand.State.Show;
}
else if (cmdText.StartsWith("/hidesource="))
{
sourceState = SourceCommand.State.Hide;
}
else
{
sourceState = SourceCommand.State.Toggle;
}
if (sourceArray.Count() == 1)
{
Commands.Add(new SourceCommand(obs)
{
sourceState = sourceState,
sourceName = sourceArray[0].RemoveQuotes()
});
}
else if (sourceArray.Count() == 2)
{
Commands.Add(new SourceCommand(obs)
{
sourceState = sourceState,
sceneName = sourceArray[0].RemoveQuotes(),
sourceName = sourceArray[1].RemoveQuotes()
});
}
}
else if (cmdText.StartsWith("/command=SetSourceFilterVisibility,"))
{
string parString = cmdText.RemoveBeforeChar(',');
string[] pars = Regex.Split(parString, "[,](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
string sourceName = "";
string filterName = "";
FilterCommand.State filterState = FilterCommand.State.Hide;
foreach (string par in pars)
{
if (par.StartsWith("sourceName"))
{
sourceName = par.RemoveBeforeChar('=').RemoveQuotes();
}
else if (par.StartsWith("filterName"))
{
filterName = par.RemoveBeforeChar('=').RemoveQuotes();
}
else if (par.StartsWith("filterEnabled"))
{
filterState = par.RemoveBeforeChar('=').RemoveQuotes() == "True" ? FilterCommand.State.Show : FilterCommand.State.Hide;
}
}
Commands.Add(new FilterCommand(obs)
{
sourceName = sourceName,
filterName = filterName,
filterState = filterState
});
}
else if (cmdText.StartsWith("/mute="))
{
Commands.Add(new AudioCommand(obs)
{
audioState = AudioCommand.State.mute,
sourceName = cmdText.RemoveBeforeChar('=').RemoveQuotes()
});
}
else if (cmdText.StartsWith("/unmute="))
{
Commands.Add(new AudioCommand(obs)
{
audioState = AudioCommand.State.unmute,
sourceName = cmdText.RemoveBeforeChar('=').RemoveQuotes()
});
}
else if (cmdText.StartsWith("/toggleaudio="))
{
Commands.Add(new AudioCommand(obs)
{
audioState = AudioCommand.State.toggle,
sourceName = cmdText.RemoveBeforeChar('=').RemoveQuotes()
});
}
else if (cmdText.StartsWith("/setvolume="))
{
string parString = cmdText.RemoveBeforeChar('=');
string[] pars = Regex.Split(parString, "[,](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
string sourceName = pars[0].RemoveQuotes();
int volume = int.Parse(pars[1]);
int delay = int.Parse(pars[2]);
Commands.Add(new AudioCommand(obs)
{
audioState = AudioCommand.State.setVolume,
sourceName = sourceName,
volume = volume,
delay = delay
});
}
else if (cmdText.StartsWith("/command=SetAudioMonitorType,"))
{
string parString = cmdText.RemoveBeforeChar(',');
string[] pars = Regex.Split(parString, "[,](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
string sourceName = "";
AudioCommand.MonitoringType monitorType = AudioCommand.MonitoringType.none;
foreach (string par in pars)
{
if (par.StartsWith("sourceName"))
{
sourceName = par.RemoveBeforeChar('=').RemoveQuotes();
}
else if (par.StartsWith("monitorType"))
{
if (par.RemoveBeforeChar('=') == "none")
{
monitorType = AudioCommand.MonitoringType.none;
}
else if (par.RemoveBeforeChar('=') == "monitorOnly")
{
monitorType = AudioCommand.MonitoringType.monitorOnly;
}
else if (par.RemoveBeforeChar('=') == "monitorAndOutput")
{
monitorType = AudioCommand.MonitoringType.monitorAndOutput;
}
}
}
Commands.Add(new AudioCommand(obs)
{
audioState = AudioCommand.State.setMonitoringType,
sourceName = sourceName,
monitoringType = monitorType
});
}
else if (cmdText.StartsWith("/command=PlayPauseMedia,"))
{
string parString = cmdText.RemoveBeforeChar(',');
string[] pars = Regex.Split(parString, "[,](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
string sourceName = "";
MediaCommand.ControlType controlType = MediaCommand.ControlType.play;
foreach (string par in pars)
{
if (par.StartsWith("sourceName"))
{
sourceName = par.RemoveBeforeChar('=').RemoveQuotes();
}
else if (par.StartsWith("playPause"))
{
if (par.RemoveBeforeChar('=') == "False")
{
controlType = MediaCommand.ControlType.play;
}
else if (par.RemoveBeforeChar('=') == "True")
{
controlType = MediaCommand.ControlType.pause;
}
}
}
Commands.Add(new MediaCommand(obs)
{
sourceName = sourceName,
controlType = controlType
});
}
else if (cmdText.StartsWith("/command=RestartMedia,"))
{
string parString = cmdText.RemoveBeforeChar(',');
string[] pars = Regex.Split(parString, "[,](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
string sourceName = "";
MediaCommand.ControlType state = MediaCommand.ControlType.restart;
foreach (string par in pars)
{
if (par.StartsWith("sourceName"))
{
sourceName = par.RemoveBeforeChar('=').RemoveQuotes();
}
}
Commands.Add(new MediaCommand(obs)
{
sourceName = sourceName,
controlType = state
});
}
else if (cmdText.StartsWith("/command=StopMedia,"))
{