Utilities.cs 9.1 KB

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