Utilities.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /* This file is part of OpenSubtitles Handler
  2. A library that handle OpenSubtitles.org XML-RPC methods.
  3. Copyright © Ala Ibrahim Hadid 2013
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Text;
  18. using System.IO;
  19. using System.Security.Cryptography;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using MediaBrowser.Common.Net;
  23. namespace OpenSubtitlesHandler
  24. {
  25. /// <summary>
  26. /// Include helper methods. All member are statics.
  27. /// </summary>
  28. public sealed class Utilities
  29. {
  30. private const string XML_RPC_SERVER = "https://api.opensubtitles.org/xml-rpc";
  31. /// <summary>
  32. /// Compute movie hash
  33. /// </summary>
  34. /// <param name="fileName">The complete media file path</param>
  35. /// <returns>The hash as Hexadecimal string</returns>
  36. public static string ComputeHash(string fileName)
  37. {
  38. byte[] hash = MovieHasher.ComputeMovieHash(File.OpenRead(fileName));
  39. return MovieHasher.ToHexadecimal(hash);
  40. }
  41. /// <summary>
  42. /// Compute md5 for a file
  43. /// </summary>
  44. /// <param name="filename">The complete file path</param>
  45. /// <returns>MD5 of the file</returns>
  46. public static string ComputeMd5(string filename)
  47. {
  48. var md5 = MD5.Create();
  49. var sb = new StringBuilder();
  50. Stream str = new FileStream(filename, FileMode.Open, FileAccess.Read);
  51. foreach (var b in md5.ComputeHash(str))
  52. sb.Append(b.ToString("x2").ToLower());
  53. str.Close();
  54. return sb.ToString();
  55. }
  56. /// <summary>
  57. /// Decompress data using GZip
  58. /// </summary>
  59. /// <param name="dataToDecompress">The stream that hold the data</param>
  60. /// <returns>Bytes array of decompressed data</returns>
  61. public static byte[] Decompress(Stream dataToDecompress)
  62. {
  63. MemoryStream target = new MemoryStream();
  64. using (System.IO.Compression.GZipStream decompressionStream = new System.IO.Compression.GZipStream(dataToDecompress,
  65. System.IO.Compression.CompressionMode.Decompress))
  66. {
  67. decompressionStream.CopyTo(target);
  68. }
  69. return target.GetBuffer();
  70. }
  71. /// <summary>
  72. /// Compress data using GZip (the retunred buffer will be WITHOUT HEADER)
  73. /// </summary>
  74. /// <param name="dataToCompress">The stream that hold the data</param>
  75. /// <returns>Bytes array of compressed data WITHOUT HEADER bytes</returns>
  76. public static byte[] Compress(Stream dataToCompress)
  77. {
  78. /*using (var compressed = new MemoryStream())
  79. {
  80. using (var compressor = new System.IO.Compression.GZipStream(compressed,
  81. System.IO.Compression.CompressionMode.Compress))
  82. {
  83. dataToCompress.CopyTo(compressor);
  84. }
  85. // Get the compressed bytes only after closing the GZipStream
  86. return compressed.ToArray();
  87. }*/
  88. //using (var compressedOutput = new MemoryStream())
  89. //{
  90. // using (var compressedStream = new ZlibStream(compressedOutput,
  91. // Ionic.Zlib.CompressionMode.Compress,
  92. // CompressionLevel.Default, false))
  93. // {
  94. // var buffer = new byte[4096];
  95. // int byteCount;
  96. // do
  97. // {
  98. // byteCount = dataToCompress.Read(buffer, 0, buffer.Length);
  99. // if (byteCount > 0)
  100. // {
  101. // compressedStream.Write(buffer, 0, byteCount);
  102. // }
  103. // } while (byteCount > 0);
  104. // }
  105. // return compressedOutput.ToArray();
  106. //}
  107. throw new NotImplementedException();
  108. }
  109. /// <summary>
  110. /// Handle server response stream and decode it as given encoding string.
  111. /// </summary>
  112. /// <param name="responseStream">The response stream. Expects a stream that doesn't support seek.</param>
  113. /// <param name="encoding">The encoding that should be used to decode buffer</param>
  114. /// <returns>The string of the stream after decode using given encoding</returns>
  115. public static string GetStreamString(Stream responseStream, Encoding encoding)
  116. {
  117. // Handle response, should be XML text.
  118. List<byte> data = new List<byte>();
  119. while (true)
  120. {
  121. int r = responseStream.ReadByte();
  122. if (r < 0)
  123. break;
  124. data.Add((byte)r);
  125. }
  126. responseStream.Close();
  127. return encoding.GetString(data.ToArray());
  128. }
  129. /// <summary>
  130. /// Handle server response stream and decode it as ASCII encoding string.
  131. /// </summary>
  132. /// <param name="responseStream">The response stream. Expects a stream that doesn't support seek.</param>
  133. /// <returns>The string of the stream after decode using ASCII encoding</returns>
  134. public static string GetStreamString(Stream responseStream)
  135. {
  136. return GetStreamString(responseStream, Encoding.ASCII);
  137. }
  138. public static IHttpClient HttpClient { get; set; }
  139. /// <summary>
  140. /// Send a request to the server
  141. /// </summary>
  142. /// <param name="request">The request buffer to send as bytes array.</param>
  143. /// <param name="userAgent">The user agent value.</param>
  144. /// <returns>Response of the server or stream of error message as string started with 'ERROR:' keyword.</returns>
  145. public static Stream SendRequest(byte[] request, string userAgent)
  146. {
  147. return SendRequestAsync(request, userAgent, CancellationToken.None).Result;
  148. //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(XML_RPC_SERVER);
  149. //req.ContentType = "text/xml";
  150. //req.Host = "api.opensubtitles.org:80";
  151. //req.Method = "POST";
  152. //req.UserAgent = "xmlrpc-epi-php/0.2 (PHP)";
  153. //req.ContentLength = request.Length;
  154. //ServicePointManager.Expect100Continue = false;
  155. //try
  156. //{
  157. // using (Stream stm = req.GetRequestStream())
  158. // {
  159. // stm.Write(request, 0, request.Length);
  160. // }
  161. // WebResponse response = req.GetResponse();
  162. // return response.GetResponseStream();
  163. //}
  164. //catch (Exception ex)
  165. //{
  166. // Stream errorStream = new MemoryStream();
  167. // byte[] dd = Encoding.ASCII.GetBytes("ERROR: " + ex.Message);
  168. // errorStream.Write(dd, 0, dd.Length);
  169. // errorStream.Position = 0;
  170. // return errorStream;
  171. //}
  172. }
  173. public static async Task<Stream> SendRequestAsync(byte[] request, string userAgent, CancellationToken cancellationToken)
  174. {
  175. var options = new HttpRequestOptions
  176. {
  177. RequestContentBytes = request,
  178. RequestContentType = "text/xml",
  179. UserAgent = userAgent,
  180. Host = "api.opensubtitles.org:443",
  181. Url = XML_RPC_SERVER,
  182. // Response parsing will fail with this enabled
  183. EnableHttpCompression = false,
  184. CancellationToken = cancellationToken
  185. };
  186. if (string.IsNullOrEmpty(options.UserAgent))
  187. {
  188. options.UserAgent = "xmlrpc-epi-php/0.2 (PHP)";
  189. }
  190. var result = await HttpClient.Post(options).ConfigureAwait(false);
  191. return result.Content;
  192. //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(XML_RPC_SERVER);
  193. //req.ContentType = "text/xml";
  194. //req.Host = "api.opensubtitles.org:80";
  195. //req.Method = "POST";
  196. //req.UserAgent = "xmlrpc-epi-php/0.2 (PHP)";
  197. //req.ContentLength = request.Length;
  198. //ServicePointManager.Expect100Continue = false;
  199. //try
  200. //{
  201. // using (Stream stm = req.GetRequestStream())
  202. // {
  203. // stm.Write(request, 0, request.Length);
  204. // }
  205. // WebResponse response = req.GetResponse();
  206. // return response.GetResponseStream();
  207. //}
  208. //catch (Exception ex)
  209. //{
  210. // Stream errorStream = new MemoryStream();
  211. // byte[] dd = Encoding.ASCII.GetBytes("ERROR: " + ex.Message);
  212. // errorStream.Write(dd, 0, dd.Length);
  213. // errorStream.Position = 0;
  214. // return errorStream;
  215. //}
  216. }
  217. }
  218. }