FFMpegDownloader.cs 10 KB

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