FFMpegDownloader.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using SharpCompress.Archive.SevenZip;
  7. using SharpCompress.Common;
  8. using SharpCompress.Reader;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.ServerApplication.Implementations
  17. {
  18. public class FFMpegDownloader
  19. {
  20. private readonly IHttpClient _httpClient;
  21. private readonly IApplicationPaths _appPaths;
  22. private readonly ILogger _logger;
  23. private const string Version = "ffmpeg20130904";
  24. private const string FontUrl = "https://www.dropbox.com/s/pj847twf7riq0j7/ARIALUNI.7z?dl=1";
  25. private readonly string[] _ffMpegUrls = new[]
  26. {
  27. "http://ffmpeg.zeranoe.com/builds/win32/static/ffmpeg-20130904-git-f974289-win32-static.7z",
  28. "https://www.dropbox.com/s/a81cb2ob23fwcfs/ffmpeg-20130904-git-f974289-win32-static.7z?dl=1"
  29. };
  30. public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient)
  31. {
  32. _logger = logger;
  33. _appPaths = appPaths;
  34. _httpClient = httpClient;
  35. }
  36. public async Task<FFMpegInfo> GetFFMpegInfo()
  37. {
  38. var versionedDirectoryPath = Path.Combine(GetMediaToolsPath(true), Version);
  39. var info = new FFMpegInfo
  40. {
  41. ProbePath = Path.Combine(versionedDirectoryPath, "ffprobe.exe"),
  42. Path = Path.Combine(versionedDirectoryPath, "ffmpeg.exe"),
  43. Version = Version
  44. };
  45. if (!Directory.Exists(versionedDirectoryPath))
  46. {
  47. Directory.CreateDirectory(versionedDirectoryPath);
  48. }
  49. var tasks = new List<Task>();
  50. if (!File.Exists(info.ProbePath) || !File.Exists(info.Path))
  51. {
  52. tasks.Add(DownloadFFMpeg(info));
  53. }
  54. tasks.Add(DownloadFonts(versionedDirectoryPath));
  55. await Task.WhenAll(tasks).ConfigureAwait(false);
  56. return info;
  57. }
  58. private async Task DownloadFFMpeg(FFMpegInfo info)
  59. {
  60. foreach (var url in _ffMpegUrls)
  61. {
  62. try
  63. {
  64. var tempFile = await DownloadFFMpeg(info, url).ConfigureAwait(false);
  65. ExtractFFMpeg(tempFile, Path.GetDirectoryName(info.Path));
  66. return;
  67. }
  68. catch (HttpException ex)
  69. {
  70. }
  71. }
  72. throw new ApplicationException("Unable to download required components. Please try again later.");
  73. }
  74. private Task<string> DownloadFFMpeg(FFMpegInfo info, string url)
  75. {
  76. return _httpClient.GetTempFile(new HttpRequestOptions
  77. {
  78. Url = url,
  79. CancellationToken = CancellationToken.None,
  80. Progress = new Progress<double>(),
  81. // Make it look like a browser
  82. // Try to hide that we're direct linking
  83. UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.47 Safari/537.36"
  84. });
  85. }
  86. private void ExtractFFMpeg(string tempFile, string targetFolder)
  87. {
  88. _logger.Debug("Extracting ffmpeg from {0}", tempFile);
  89. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  90. if (!Directory.Exists(tempFolder))
  91. {
  92. Directory.CreateDirectory(tempFolder);
  93. }
  94. try
  95. {
  96. Extract7zArchive(tempFile, tempFolder);
  97. var files = Directory.EnumerateFiles(tempFolder, "*.exe", SearchOption.AllDirectories).ToList();
  98. foreach (var file in files)
  99. {
  100. File.Copy(file, Path.Combine(targetFolder, Path.GetFileName(file)));
  101. }
  102. }
  103. finally
  104. {
  105. DeleteFile(tempFile);
  106. }
  107. }
  108. private void Extract7zArchive(string archivePath, string targetPath)
  109. {
  110. using (var archive = SevenZipArchive.Open(archivePath))
  111. {
  112. using (var reader = archive.ExtractAllEntries())
  113. {
  114. reader.WriteAllToDirectory(targetPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
  115. }
  116. }
  117. }
  118. private void DeleteFile(string path)
  119. {
  120. try
  121. {
  122. File.Delete(path);
  123. }
  124. catch (IOException ex)
  125. {
  126. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  127. }
  128. }
  129. /// <summary>
  130. /// Extracts the fonts.
  131. /// </summary>
  132. /// <param name="targetPath">The target path.</param>
  133. private async Task DownloadFonts(string targetPath)
  134. {
  135. try
  136. {
  137. var fontsDirectory = Path.Combine(targetPath, "fonts");
  138. if (!Directory.Exists(fontsDirectory))
  139. {
  140. Directory.CreateDirectory(fontsDirectory);
  141. }
  142. const string fontFilename = "ARIALUNI.TTF";
  143. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  144. if (!File.Exists(fontFile))
  145. {
  146. await DownloadFontFile(fontsDirectory, fontFilename).ConfigureAwait(false);
  147. }
  148. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  149. }
  150. catch (HttpException ex)
  151. {
  152. // Don't let the server crash because of this
  153. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  154. }
  155. catch (Exception ex)
  156. {
  157. // Don't let the server crash because of this
  158. _logger.ErrorException("Error writing ffmpeg font files", ex);
  159. }
  160. }
  161. /// <summary>
  162. /// Downloads the font file.
  163. /// </summary>
  164. /// <param name="fontsDirectory">The fonts directory.</param>
  165. /// <param name="fontFilename">The font filename.</param>
  166. /// <returns>Task.</returns>
  167. private async Task DownloadFontFile(string fontsDirectory, string fontFilename)
  168. {
  169. var existingFile = Directory
  170. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  171. .FirstOrDefault();
  172. if (existingFile != null)
  173. {
  174. try
  175. {
  176. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  177. return;
  178. }
  179. catch (IOException ex)
  180. {
  181. // Log this, but don't let it fail the operation
  182. _logger.ErrorException("Error copying file", ex);
  183. }
  184. }
  185. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  186. {
  187. Url = FontUrl,
  188. Progress = new Progress<double>()
  189. });
  190. Extract7zArchive(tempFile, fontsDirectory);
  191. try
  192. {
  193. File.Delete(tempFile);
  194. }
  195. catch (IOException ex)
  196. {
  197. // Log this, but don't let it fail the operation
  198. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  199. }
  200. }
  201. /// <summary>
  202. /// Writes the font config file.
  203. /// </summary>
  204. /// <param name="fontsDirectory">The fonts directory.</param>
  205. /// <returns>Task.</returns>
  206. private async Task WriteFontConfigFile(string fontsDirectory)
  207. {
  208. const string fontConfigFilename = "fonts.conf";
  209. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  210. if (!File.Exists(fontConfigFile))
  211. {
  212. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  213. var bytes = Encoding.UTF8.GetBytes(contents);
  214. using (var fileStream = new FileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  215. FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize,
  216. FileOptions.Asynchronous))
  217. {
  218. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Gets the media tools path.
  224. /// </summary>
  225. /// <param name="create">if set to <c>true</c> [create].</param>
  226. /// <returns>System.String.</returns>
  227. private string GetMediaToolsPath(bool create)
  228. {
  229. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  230. if (create && !Directory.Exists(path))
  231. {
  232. Directory.CreateDirectory(path);
  233. }
  234. return path;
  235. }
  236. }
  237. public class FFMpegInfo
  238. {
  239. public string Path { get; set; }
  240. public string ProbePath { get; set; }
  241. public string Version { get; set; }
  242. }
  243. }