Utilities.cs 9.0 KB

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