Utilities.cs 8.6 KB

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