Utilities.cs 9.5 KB

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