/
Util.cs
4713 lines (4224 loc) · 151 KB
/
Util.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
#region Copyright (C) 2005-2011 Team MediaPortal
// Copyright (C) 2005-2011 Team MediaPortal
// http://www.team-mediaportal.com
//
// MediaPortal is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// MediaPortal is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MediaPortal. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Linq;
using System.Threading;
using System.Globalization;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;
using System.Management;
using System.Diagnostics;
using System.Text;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Windows.Forms;
using System.Xml;
using MediaPortal.ExtensionMethods;
using MediaPortal.Player;
using MediaPortal.Profile;
using Microsoft.Win32;
using MediaPortal.GUI.Library;
using MediaPortal.Ripper;
using MediaPortal.Configuration;
using MediaPortal.Services;
namespace MediaPortal.Util
{
public struct LanguageInfo
{
public string EnglishName;
public string TwoLetterISO;
} ;
/// <summary>
/// Common functions for general usage
/// </summary>
public class Utils
{
[DllImport("User32")]
public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount);
[DllImport("User32")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("User32")]
public static extern int EnumWindows(IECallBack x, int y);
[DllImport("kernel32.dll")]
private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out UInt64 lpFreeBytesAvailable,
out UInt64 lpTotalNumberOfBytes, out UInt64 lpTotalNumberOfFreeBytes);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool GetVolumeInformation(
string RootPathName,
StringBuilder VolumeNameBuffer,
int VolumeNameSize,
out uint VolumeSerialNumber,
out uint MaximumComponentLength,
out uint FileSystemFlags,
StringBuilder FileSystemNameBuffer,
int nFileSystemNameSize);
[DllImport("kernel32.dll")]
public static extern long GetDriveType(string driveLetter);
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi)]
protected static extern int mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength,
IntPtr hwndCallback);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode,
IntPtr lpInBuffer, uint nInBufferSize,
IntPtr lpOutBuffer, uint nOutBufferSize,
out uint lpBytesReturned, IntPtr lpOverlapped);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFile(
string filename,
[MarshalAs(UnmanagedType.U4)] FileAccess fileaccess,
[MarshalAs(UnmanagedType.U4)] FileShare fileshare,
int securityattributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationdisposition,
int flags, IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2A(ref NetResource pstNetRes, string psPassword, string psUsername,
int piFlags);
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOW = 5;
private const int SW_RESTORE = 9;
private const int CONNECT_UPDATE_PROFILE = 0x00000001;
private const int RESOURCETYPE_DISK = 0x1;
private const int FileLookUpCacheThreadScanningIntervalMSecs = 5000;
private static CRCTool crc = null;
[StructLayout(LayoutKind.Sequential)]
private struct NetResource
{
public int Scope;
public int Type;
public int DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
public delegate bool IECallBack(int hwnd, int lParam);
public delegate void UtilEventHandler(Process proc, bool waitForExit);
public static event UtilEventHandler OnStartExternal = null; // Event: Start external process / waeberd & mPod
public static event UtilEventHandler OnStopExternal = null; // Event: Stop external process / waeberd & mPod
private static HashSet<string> m_AudioExtensions = new HashSet<string>();
private static HashSet<string> m_VideoExtensions = new HashSet<string>();
private static HashSet<string> m_PictureExtensions = new HashSet<string>();
private static HashSet<string> m_ImageExtensions = new HashSet<string>();
private static string[] _artistNamePrefixes;
private static bool m_bHideExtensions = false;
private static bool enableGuiSounds;
private static char[] crypt = new char[10] {'G', 'D', 'J', 'S', 'I', 'B', 'T', 'P', 'W', 'Q'};
// singleton. Dont allow any instance of this class
private Utils() {}
public static string AudioExtensionsDefault =
".mp3,.wma,.ogg,.flac,.wav,.cda,.m3u,.pls,.b4s,.m4a,.m4p,.mp4,.wpl,.wv,.ape,.mpc";
public static string VideoExtensionsDefault =
".avi,.bdmv,.mpg,.mpeg,.mp4,.divx,.ogm,.mkv,.wmv,.qt,.rm,.mov,.mts,.m2ts,.sbe,.dvr-ms,.ts,.dat,.ifo";
public static string PictureExtensionsDefault = ".jpg,.jpeg,.gif,.bmp,.png";
public static string ImageExtensionsDefault = ".cue,.bin,.iso,.ccd,.bwt,.mds,.cdi,.nrg,.pdi,.b5t,.img";
static Utils()
{
using (Profile.Settings xmlreader = new Profile.MPSettings())
{
m_bHideExtensions = xmlreader.GetValueAsBool("gui", "hideextensions", true);
string artistNamePrefixes = xmlreader.GetValueAsString("musicfiles", "artistprefixes", "The, Les, Die");
_artistNamePrefixes = artistNamePrefixes.Split(',');
string strTmp = xmlreader.GetValueAsString("music", "extensions", AudioExtensionsDefault);
Tokens tok = new Tokens(strTmp, new[] {','});
foreach (string extension in tok)
{
m_AudioExtensions.Add(extension.ToLower().Trim());
}
strTmp = xmlreader.GetValueAsString("movies", "extensions", VideoExtensionsDefault);
tok = new Tokens(strTmp, new[] {','});
foreach (string extension in tok)
{
m_VideoExtensions.Add(extension.ToLower().Trim());
}
strTmp = xmlreader.GetValueAsString("pictures", "extensions", PictureExtensionsDefault);
tok = new Tokens(strTmp, new[] {','});
foreach (string extension in tok)
{
m_PictureExtensions.Add(extension.ToLower().Trim());
}
if (xmlreader.GetValueAsBool("daemon", "enabled", false))
{
strTmp = xmlreader.GetValueAsString("daemon", "extensions", ImageExtensionsDefault);
tok = new Tokens(strTmp, new[] {','});
foreach (string extension in tok)
{
m_ImageExtensions.Add(extension.ToLower().Trim());
}
}
enableGuiSounds = xmlreader.GetValueAsBool("gui", "enableguisounds", true);
}
}
public static ArrayList VideoExtensions
{
get
{
ArrayList t = new ArrayList();
t.AddRange(m_VideoExtensions.ToArray());
//
// Added images extensions in order to trigger autoplay as video
// no more need to add them manually to Videos extensions (mantis #2749)
//
if (m_ImageExtensions.Count != 0)
{
t.AddRange(m_ImageExtensions.ToArray());
}
return t;
}
}
public static ArrayList AudioExtensions
{
get { return new ArrayList(m_AudioExtensions.ToArray()); }
}
public static ArrayList PictureExtensions
{
get { return new ArrayList(m_PictureExtensions.ToArray()); }
}
public static ArrayList ImageExtensions
{
get { return new ArrayList(m_ImageExtensions.ToArray()); }
}
public static string GetDriveSerial(string drive)
{
if (drive == null) return string.Empty;
//receives volume name of drive
StringBuilder volname = new StringBuilder(256);
//receives serial number of drive,not in case of network drive(win95/98)
uint sn;
uint maxcomplen; //receives maximum component length
uint sysflags; //receives file system flags
StringBuilder sysname = new StringBuilder(256); //receives the file system name
bool retval; //return value
retval = GetVolumeInformation(drive.Substring(0, 2), volname, 256, out sn, out maxcomplen, out sysflags, sysname,
256);
if (retval)
{
return String.Format("{0:X}", sn);
}
else return "";
}
public static string GetDriveName(string drive)
{
if (drive == null) return string.Empty;
//receives volume name of drive
StringBuilder volname = new StringBuilder(256);
//receives serial number of drive,not in case of network drive(win95/98)
uint sn;
uint maxcomplen; //receives maximum component length
uint sysflags; //receives file system flags
StringBuilder sysname = new StringBuilder(256); //receives the file system name
bool retval; //return value
retval = GetVolumeInformation(drive, volname, 256, out sn, out maxcomplen, out sysflags, sysname, 256);
if (retval)
{
return volname.ToString();
}
else return "";
}
public static int getDriveType(string drive)
{
if (drive == null) return 2;
if ((GetDriveType(drive) & 5) == 5) return 5; //cd
if ((GetDriveType(drive) & 3) == 3) return 3; //fixed
if ((GetDriveType(drive) & 2) == 2) return 2; //removable
if ((GetDriveType(drive) & 4) == 4) return 4; //remote disk
if ((GetDriveType(drive) & 6) == 6) return 6; //ram disk
return 0;
}
public static string GetUNCPath(string sFilePath)
{
if (sFilePath.StartsWith("\\\\"))
return sFilePath;
try
{
ManagementObject mo = new ManagementObject();
mo.Path = new ManagementPath(string.Format("Win32_LogicalDisk='{0}'", sFilePath));
//DriveType 4 = Network Drive
if (Convert.ToUInt32(mo["DriveType"]) == 4)
return Convert.ToString(mo["ProviderName"]);
}
catch (Exception) {}
return sFilePath;
}
public static long GetDiskSize(string drive)
{
long diskSize = 0;
try
{
string cmd = String.Format("win32_logicaldisk.deviceid=\"{0}:\"", drive[0]);
using (ManagementObject disk = new ManagementObject(cmd))
{
disk.Get();
diskSize = Int64.Parse(disk["Size"].ToString());
}
}
catch (Exception)
{
return -1;
}
return diskSize;
}
private static char[] sizes = new char[] {'K', 'M', 'G', 'T'};
// converts bytes to bytes / 1024^n
private static Func<long, int, double> sizeConverter = (size, expo) => size / Math.Pow(1024, expo);
public static string GetSize(long dwFileSize)
{
int i = sizes.Length;
double beautySize = 0.0D;
// get the highest power of 1024 that yields a value above 1
while ((beautySize = sizeConverter(dwFileSize, i)) < 1 && i > 1)
i--;
// we force close enough values to the next higher, so we get 0.99 GB instead of 1010 MB for instance
if (beautySize >= 1000 && i < sizes.Length)
beautySize = sizeConverter(dwFileSize, ++i);
return string.Format("{0:f} {1}B", beautySize, sizes[i - 1]);
}
/// <summary>
/// Returns whether a file is TV
/// Will also return true is file is Radio as both share same format
/// </summary>
/// <param name="strPath">path to file</param>
/// <returns>Whether file is TV</returns>
public static bool IsLiveTv(string strPath)
{
if (strPath == null) return false;
Match ex = Regex.Match(strPath, @"(live\d+-\d+\.ts(\.tsbuffer(\d+\.ts)?)?)$");
return ex.Success;
}
public static bool IsRTSP(string strPath)
{
if (strPath == null) return false;
return strPath.Contains("rtsp:");
}
/// <summary>
/// Should return whether a file is radio but is bugged
/// because file format for radio is the same as TV
/// </summary>
/// <param name="strPath">path to file</param>
/// <returns>Whether file is radio</returns>
public static bool IsLiveRadio(string strPath)
{
if (strPath == null) return false;
//
// Bugged implementation: files are named "live3-0.ts.tsbuffer" as for LiveTv
//
return strPath.Contains("live-radio.ts");
}
/// <summary>
/// This returns whether a file is video or not
/// There is an issue in the logic for multi-seat radio
/// => if (strPath.ToLower().StartsWith("rtsp:")) return true;
/// means this will incorrectly return true for multi-seat radio
/// </summary>
/// <param name="strPath">path to file</param>
/// <returns>Whether file is a video file</returns>
public static bool IsVideo(string strPath)
{
if (strPath == null) return false;
if (IsLastFMStream(strPath)) return false;
if (strPath.ToLower().StartsWith("rtsp:")) return true;
if (strPath.ToLower().StartsWith("mms:")
&& strPath.ToLower().EndsWith(".ymvp")) return true;
try
{
if (!Path.HasExtension(strPath))
return false;
string extensionFile = Path.GetExtension(strPath).ToLower();
if (IsPlayListExtension(extensionFile))
return false;
if (extensionFile == ".ts")
{
// Forced check to avoid users messed configuration ( .ts remove from Videos extensions list)
return true;
}
if (extensionFile == ".bdmv")
{
// Forced check to avoid users messed configuration ( .bdmv remove from Videos extensions list)
return true;
}
if (VirtualDirectory.IsImageFile(extensionFile.ToLower()))
return true;
return m_VideoExtensions.Contains(extensionFile);
}
catch (Exception) {}
return false;
}
public static bool IsLastFMStream(string aPath)
{
try
{
if (aPath.StartsWith(@"http://"))
{
if (aPath.Contains(@"/last.mp3?") || aPath.Contains(@"last.fm/"))
{
return true;
}
}
}
catch (Exception ex)
{
Log.Warn("Util: Error in IsLastFMStream - {0}", ex.Message);
}
return false;
}
public static bool IsAVStream(string strPath)
{
if (strPath == null) return false;
if (strPath.StartsWith("http:")) return true;
if (strPath.StartsWith("https:")) return true;
if (strPath.StartsWith("mms:")) return true;
return false;
}
public static bool IsRemoteUrl(string strPath)
{
Uri playbackUri = null;
if (Uri.TryCreate(strPath, UriKind.Absolute, out playbackUri) && playbackUri.Scheme != "file")
{
return true;
}
return false;
}
public static bool IsAudio(string strPath)
{
if (strPath == null) return false;
if (IsLastFMStream(strPath)) return true;
try
{
if (!Path.HasExtension(strPath)) return false;
string extensionFile = Path.GetExtension(strPath).ToLower();
if (IsPlayListExtension(extensionFile)) return false;
return m_AudioExtensions.Contains(extensionFile);
}
catch (Exception) {}
return false;
}
public static bool IsPicture(string strPath)
{
if (strPath == null) return false;
try
{
if (!Path.HasExtension(strPath)) return false;
if (IsPlayList(strPath)) return false;
string extensionFile = Path.GetExtension(strPath).ToLower();
return m_PictureExtensions.Contains(extensionFile);
}
catch (Exception) {}
return false;
}
private static bool IsPlayListExtension(string extensionFile)
{
if (extensionFile == ".m3u") return true;
if (extensionFile == ".pls") return true;
if (extensionFile == ".b4s") return true;
if (extensionFile == ".wpl") return true;
return false;
}
public static bool IsPlayList(string strPath)
{
if (strPath == null) return false;
try
{
if (!Path.HasExtension(strPath)) return false;
string extensionFile = Path.GetExtension(strPath).ToLower();
return IsPlayListExtension(extensionFile);
}
catch (Exception) {}
return false;
}
public static bool IsProgram(string strPath)
{
if (strPath == null) return false;
try
{
if (!Path.HasExtension(strPath)) return false;
string extensionFile = Path.GetExtension(strPath).ToLower();
if (extensionFile == ".exe") return true;
}
catch (Exception) {}
return false;
}
public static bool IsShortcut(string strPath)
{
if (strPath == null) return false;
try
{
if (!Path.HasExtension(strPath)) return false;
string extensionFile = Path.GetExtension(strPath).ToLower();
if (extensionFile == ".lnk") return true;
}
catch (Exception) {}
return false;
}
public static void SetDefaultIcons(GUIListItem item)
{
if (item == null) return;
if (!item.IsFolder)
{
if (IsPlayList(item.Path))
{
item.IconImage = "DefaultPlaylist.png";
item.IconImageBig = "DefaultPlaylistBig.png";
}
else if (IsVideo(item.Path))
{
item.IconImage = "defaultVideo.png";
item.IconImageBig = "defaultVideoBig.png";
}
else if (IsCDDA(item.Path))
{
item.IconImage = "defaultCdda.png";
item.IconImageBig = "defaultCddaBig.png";
}
else if (IsAudio(item.Path))
{
item.IconImage = "defaultAudio.png";
item.IconImageBig = "defaultAudioBig.png";
}
else if (IsPicture(item.Path))
{
item.IconImage = "defaultPicture.png";
item.IconImageBig = "defaultPictureBig.png";
}
else if (IsProgram(item.Path))
{
item.IconImage = "DefaultProgram.png";
item.IconImageBig = "DefaultProgramBig.png";
}
else if (IsShortcut(item.Path))
{
item.IconImage = "DefaultShortcut.png";
item.IconImageBig = "DefaultShortcutBig.png";
}
}
else
{
if (item.Label == "..")
{
item.IconImage = "defaultFolderBack.png";
item.IconImageBig = "defaultFolderBackBig.png";
}
else
{
if (IsNetwork(item.Path))
{
item.IconImage = "defaultNetwork.png";
item.IconImageBig = "defaultNetworkBig.png";
}
else if (item.Path.Length <= 3)
{
if (IsDVD(item.Path))
{
item.IconImage = "defaultDVDRom.png";
item.IconImageBig = "defaultDVDRomBig.png";
}
else if (IsHD(item.Path))
{
item.IconImage = "defaultHardDisk.png";
item.IconImageBig = "defaultHardDiskBig.png";
}
else if (IsRemovable(item.Path))
{
item.IconImage = "defaultRemovable.png";
item.IconImageBig = "defaultRemovableBig.png";
}
else
{
item.IconImage = "defaultFolder.png";
item.IconImageBig = "defaultFolderBig.png";
}
}
else
{
item.IconImage = "defaultFolder.png";
item.IconImageBig = "defaultFolderBig.png";
}
}
}
}
public static void SetThumbnails(ref GUIListItem item)
{
if (item == null || String.IsNullOrEmpty(item.Path))
{
//Disable verbose logging
//Log.Debug("SetThumbnails: nothing to do.");
return;
}
string strThumb = string.Empty;
if (!item.IsFolder || (item.IsFolder && VirtualDirectory.IsImageFile(Path.GetExtension(item.Path).ToLower())))
{
if (!IsVideo(item.Path))
{
//Disable verbose logging
//Log.Debug("SetThumbnails: nothing to do.");
return;
}
string[] thumbs = {
Path.ChangeExtension(item.Path, ".jpg"),
Path.ChangeExtension(item.Path, ".tbn"),
Path.ChangeExtension(item.Path, ".png"),
String.Format(@"{0}\{1}.jpg", Thumbs.Videos, EncryptLine(item.Path))
};
bool foundVideoThumb = false;
foreach (string s in thumbs)
{
string thumbStr = s;
if (FileExistsInCache(thumbStr))
{
strThumb = thumbStr;
foundVideoThumb = true;
break;
}
}
//
bool createVideoThumbs;
bool getItemThumb = true;
using (Settings xmlreader = new MPSettings())
{
createVideoThumbs = xmlreader.GetValueAsBool("thumbnails", "tvrecordedondemand", true);
//
//Get movies shares and check for video thumb create
//
const int maximumShares = 128;
for (int index = 0; index < maximumShares; index++)
{
// Get share dir
string sharePath = String.Format("sharepath{0}", index);
string shareDir = xmlreader.GetValueAsString("movies", sharePath, "");
// Get item dir
string itemDir = string.Empty;
if (!item.IsRemote)
{
itemDir = (GetParentDirectory(item.Path));
}
// Check if share dir correspond to item dir
if (AreEqual(shareDir, itemDir))
{
string thumbsCreate = String.Format("videothumbscreate{0}", index);
getItemThumb = xmlreader.GetValueAsBool("movies", thumbsCreate, true);
break;
}
}
}
if (createVideoThumbs && !foundVideoThumb && getItemThumb)
{
if (Path.IsPathRooted(item.Path) && IsVideo(item.Path) &&
!VirtualDirectory.IsImageFile(Path.GetExtension(item.Path).ToLower()))
{
Log.Debug("SetThumbnails: Thumbs for video (" + GetFilename(item.Path) +
") not found. Creating a new video thumb...");
// creating and starting a thread for potentially every file in a list is very expensive, we should use the threadpool
//Thread extractVideoThumbThread = new Thread(GetVideoThumb)
//{
// Name = "ExtractVideoThumb",
// IsBackground = true,
// Priority = ThreadPriority.Lowest
//};
//extractVideoThumbThread.Start(item);
ThreadPool.QueueUserWorkItem(GetVideoThumb, item);
}
return;
}
if (item.ThumbnailImage == string.Empty)
{
item.ThumbnailImage = strThumb;
item.IconImage = strThumb;
item.IconImageBig = strThumb;
}
else
{
strThumb = item.ThumbnailImage;
}
}
else
{
if (item.Label != "..")
{
strThumb = item.Path + @"\folder.jpg";
if (FileExistsInCache(strThumb))
{
item.ThumbnailImage = strThumb;
item.IconImage = strThumb;
item.IconImageBig = strThumb;
}
}
}
if (!string.IsNullOrEmpty(strThumb))
{
strThumb = ConvertToLargeCoverArt(strThumb);
if (FileExistsInCache(strThumb))
{
item.ThumbnailImage = strThumb;
}
}
}
/// <summary>
/// Function to check share path and selected item path.
/// Item path can have deeper subdir level but must begin
/// with share path to return TRUE, selected item extra
/// subdir levels will be ignored
/// </summary>
/// <param name="dir1">share path</param>
/// <param name="dir2">selected item path</param>
/// <returns>true: paths are equal, false: paths do not match</returns>
public static bool AreEqual(string dir1, string dir2)
{
if (dir1 == string.Empty | dir2 == string.Empty)
return false;
try
{
DirectoryInfo parent1 = new DirectoryInfo(dir1);
DirectoryInfo parent2 = new DirectoryInfo(dir2);
// Build a list of parents
List<string> folder1Parents = new List<string>();
List<string> folder2Parents = new List<string>();
while (parent1 != null)
{
folder1Parents.Add(parent1.Name);
parent1 = parent1.Parent;
}
while (parent2 != null)
{
folder2Parents.Add(parent2.Name);
parent2 = parent2.Parent;
}
// Share path can't be deeper than item path
if (folder1Parents.Count > folder2Parents.Count)
{
return false;
}
// Remove extra subdirs from item path
if (folder2Parents.Count > folder1Parents.Count)
{
int diff = folder2Parents.Count - folder1Parents.Count;
for (int i = 0; i < diff; i++)
{
folder2Parents.RemoveAt(0);
}
}
bool equal = true;
// Final check
for (int i = 0; i < folder1Parents.Count; i++)
{
if (folder1Parents[i] != folder2Parents[i])
{
equal = false;
break;
}
}
return equal;
}
catch (Exception)
{
return false;
}
}
public static bool IsFolderDedicatedMovieFolder(string directory)
{
using (MPSettings xmlreader = new MPSettings())
{
const int maximumShares = 128;
for (int index = 0; index < maximumShares; index++)
{
// Get share dir
string sharePath = String.Format("sharepath{0}", index);
string shareDir = xmlreader.GetValueAsString("movies", sharePath, "");
// Get item dir
string itemDir = string.Empty;
itemDir = (GetParentDirectory(directory));
// Check if share dir correspond to item dir
if (AreEqual(shareDir, itemDir))
{
string eachFolderIsMovie = String.Format("eachfolderismovie{0}", index);
bool folderMovie = xmlreader.GetValueAsBool("movies", eachFolderIsMovie, false);
return folderMovie;
}
}
}
return false;
}
public static void GetVideoThumb(object i)
{
GUIListItem item = (GUIListItem)i;
string path = item.Path;
string strThumb = String.Format(@"{0}\{1}.jpg", Thumbs.Videos, EncryptLine(path));
if (FileExistsInCache(strThumb))
{
return;
}
// Do not try to create thumbnails for DVDs/BDs
if (path.Contains("VIDEO_TS\\VIDEO_TS.IFO") || path.Contains("BDMV\\index.bdmv"))
{
return;
}
IVideoThumbBlacklist blacklist = GlobalServiceProvider.Get<IVideoThumbBlacklist>();
if (blacklist != null && blacklist.Contains(path))
{
Log.Debug("Skipped creating thumbnail for {0}, it has been blacklisted because last attempt failed", path);
return;
}
Image thumb = null;
try
{
bool success = VideoThumbCreator.CreateVideoThumb(path, strThumb, true, false);
if (!success)
{
//Failed due to incompatible format or no write permissions on folder. Try querying Explorer for thumb.
Log.Warn("Failed to extract thumb for {0}, trying another method.", path);
if (OSInfo.OSInfo.VistaOrLater())
{
thumb = VistaToolbelt.Shell.ThumbnailGenerator.GenerateThumbnail(path); //only works for Vista/7
}
else
{
using (ThumbnailExtractor extractor = new ThumbnailExtractor())
{
thumb = extractor.GetThumbnail(path); //works on XP but not too well threaded
}
}
if (thumb != null)
if (Picture.CreateThumbnail(thumb, strThumb, (int)Thumbs.ThumbLargeResolution,
(int)Thumbs.ThumbLargeResolution, 0, false))
SetThumbnails(ref item);
}
else
SetThumbnails(ref item);
}
catch (COMException comex)
{
if (comex.ErrorCode == unchecked((int)0x8004B200))
{
Log.Warn("Could not create thumbnail for {0} [Unknown error 0x8004B200]", path);
}
else
{
Log.Error("Could not create thumbnail for {0}", path);
Log.Error(comex);
}
}
catch (Exception ex)
{
Log.Error("Could not create thumbnail for {0}", path);
Log.Error(ex);
}
finally
{
if (thumb != null)
thumb.SafeDispose();
if (!FileExistsInCache(strThumb) && blacklist != null)
{
blacklist.Add(path);
}
}
}
public static void CheckThumbExtractorVersion()
{
try
{
using (Profile.Settings xmlreader = new Profile.MPSettings())
{
if (!xmlreader.GetValueAsBool("thumbnails", "tvrecordedondemand", true))
return;
string lastVersion = xmlreader.GetValueAsString("thumbnails", "extractorversion", "");
string newVersion = VideoThumbCreator.GetThumbExtractorVersion();
if (newVersion != lastVersion)
{
IVideoThumbBlacklist blacklist = GlobalServiceProvider.Get<IVideoThumbBlacklist>();
if (blacklist != null)
{
blacklist.Clear();
}
xmlreader.SetValue("thumbnails", "extractorversion", newVersion);
}
}
}
catch (Exception ex)
{
Log.Error("CheckThumbExtractorVersion failed:");
Log.Error(ex);
}
}
public static string SecondsToShortHMSString(int lSeconds)
{
if (lSeconds < 0) return ("0:00");
int hh = lSeconds / 3600;
lSeconds = lSeconds % 3600;
int mm = lSeconds / 60;
int ss = lSeconds % 60;
string strHMS = "";
strHMS = String.Format("{0}:{1:00}", hh, mm);
return strHMS;
}
public static string SecondsToHMSString(TimeSpan timespan)
{
return SecondsToHMSString(timespan.Seconds);
}
public static string SecondsToHMSString(int lSeconds)
{
if (lSeconds < 0) return ("0:00");
int hh = lSeconds / 3600;
lSeconds = lSeconds % 3600;
int mm = lSeconds / 60;
int ss = lSeconds % 60;
string strHMS = "";
if (hh >= 1)
strHMS = String.Format("{0}:{1:00}:{2:00}", hh, mm, ss);
else
strHMS = String.Format("{0}:{1:00}", mm, ss);
return strHMS;
}
public static string GetNamedMonth(string aTwoLetterMonth)
{