BoxStorageClient.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Net;
  6. using FastReport.Cloud.OAuth;
  7. using FastReport.Cloud.StorageClient.SkyDrive;
  8. using FastReport.Utils;
  9. namespace FastReport.Cloud.StorageClient.Box
  10. {
  11. /// <summary>
  12. /// Box cloud storage client.
  13. /// </summary>
  14. public class BoxStorageClient : CloudStorageClient
  15. {
  16. #region Fields
  17. private ClientInfo clientInfo;
  18. private string authCode;
  19. private string accessToken;
  20. #endregion // Fields
  21. #region Properties
  22. /// <summary>
  23. /// Gets or sets the client info.
  24. /// </summary>
  25. public ClientInfo ClientInfo
  26. {
  27. get { return clientInfo; }
  28. set { clientInfo = value; }
  29. }
  30. /// <summary>
  31. /// Gets or sets the authorization code.
  32. /// </summary>
  33. public string AuthCode
  34. {
  35. get { return authCode; }
  36. set { authCode = value; }
  37. }
  38. /// <summary>
  39. /// Gets or sets the access token.
  40. /// </summary>
  41. public string AccessToken
  42. {
  43. get { return accessToken; }
  44. set { accessToken = value; }
  45. }
  46. #endregion // Properties
  47. #region Constructors
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="BoxStorageClient"/> class.
  50. /// </summary>
  51. public BoxStorageClient() : base()
  52. {
  53. this.clientInfo = new ClientInfo("", "", "");
  54. authCode = "";
  55. accessToken = "";
  56. }
  57. /// <summary>
  58. /// Initializes a new instance of the <see cref="BoxStorageClient"/> class.
  59. /// </summary>
  60. /// <param name="clientInfo">The storage client info.</param>
  61. public BoxStorageClient(ClientInfo clientInfo) : base()
  62. {
  63. this.clientInfo = clientInfo;
  64. authCode = "";
  65. accessToken = "";
  66. }
  67. /// <summary>
  68. /// Initializes a new instance of the <see cref="BoxStorageClient"/> class.
  69. /// </summary>
  70. /// <param name="clientId">Client ID.</param>
  71. /// <param name="clientSecret">Client Secret.</param>
  72. public BoxStorageClient(string clientId, string clientSecret) : base()
  73. {
  74. this.clientInfo = new ClientInfo("", clientId, clientSecret);
  75. authCode = "";
  76. accessToken = "";
  77. }
  78. #endregion // Constructors
  79. #region Private Methods
  80. private byte[] BuildGetAccessTokenRequestContent()
  81. {
  82. Dictionary<string, string> data = new Dictionary<string, string>();
  83. data.Add("client_id", clientInfo.Id);
  84. data.Add("client_secret", clientInfo.Secret);
  85. data.Add("code", authCode);
  86. //data.Add("redirect_uri", @"urn:ietf:wg:oauth:2.0:oob");
  87. data.Add("grant_type", "authorization_code");
  88. return Encoding.UTF8.GetBytes(HttpUtils.UrlDataEncode(data));
  89. }
  90. private string GetUploadUri(string fileid = "")
  91. {
  92. if (String.IsNullOrEmpty(fileid))
  93. return @"https://upload.box.com/api/2.0/files/content";
  94. else
  95. return String.Format(@"https://upload.box.com/api/2.0/files/{0}/content", fileid);
  96. }
  97. private void UploadNewFile(MemoryStream ms, string fileid = "")
  98. {
  99. System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
  100. string uri = GetUploadUri(fileid);
  101. WebRequest request = WebRequest.Create(uri);
  102. request.Method = HttpMethod.Post;
  103. RequestUtils.SetProxySettings(request, ProxySettings);
  104. request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
  105. request.ContentType = "multipart/form-data; boundary=\"foo_bar_baz\"";
  106. List<byte> content = new List<byte>();
  107. StringBuilder sb = new StringBuilder("--foo_bar_baz\r\n");
  108. sb.Append(String.Format("Content-Disposition: form-data; filename=\"{0}\"; name=\"filename\"\r\n", Filename));
  109. sb.Append("Content-Type: application/octet-stream\r\n");
  110. sb.Append("\r\n");
  111. content.AddRange(Encoding.UTF8.GetBytes(sb.ToString()));
  112. int msLength = Convert.ToInt32(ms.Length);
  113. byte[] msBuffer = new byte[msLength];
  114. ms.Read(msBuffer, 0, msLength);
  115. content.AddRange(msBuffer);
  116. sb = new StringBuilder("\r\n--foo_bar_baz\r\n");
  117. sb.Append("Content-Disposition: form-data; name=\"folder_id\"");
  118. sb.Append("\r\n\r\n0\r\n");
  119. sb.Append("--foo_bar_baz--");
  120. content.AddRange(Encoding.UTF8.GetBytes(sb.ToString()));
  121. int length = content.Count;
  122. byte[] buffer = new byte[length];
  123. buffer = content.ToArray();
  124. request.ContentLength = buffer.Length;
  125. using (Stream rs = request.GetRequestStream())
  126. {
  127. rs.Write(buffer, 0, buffer.Length);
  128. }
  129. WebResponse response = request.GetResponse();
  130. Stream stream = response.GetResponseStream();
  131. }
  132. private void UploadExistFile(MemoryStream ms)
  133. {
  134. UploadNewFile(ms, GetFileID());
  135. }
  136. private string GetFileID()
  137. {
  138. WebRequest request = WebRequest.Create(@"https://api.box.com/2.0/folders/0/items/");
  139. request.ContentType = "application/json";
  140. request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
  141. WebResponse response = request.GetResponse();
  142. string JSONString = String.Empty;
  143. using (Stream responseStream = response.GetResponseStream())
  144. {
  145. StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
  146. JSONString += reader.ReadToEnd();
  147. }
  148. int indexFilename = JSONString.IndexOf(Filename);
  149. int firstBracketIndex = 0;
  150. int i = 1;
  151. bool file_version_bracketWas = false;
  152. while (true)
  153. {
  154. if (JSONString[indexFilename - i].ToString() == "{")
  155. {
  156. if (file_version_bracketWas)
  157. {
  158. firstBracketIndex = indexFilename - i;
  159. break;
  160. }
  161. else
  162. {
  163. file_version_bracketWas = true;
  164. }
  165. }
  166. i++;
  167. }
  168. string fileJson = JSONString.Substring(firstBracketIndex, indexFilename - firstBracketIndex);
  169. int idIndex = fileJson.IndexOf("id");
  170. string idString = fileJson.Substring(idIndex + 4, fileJson.IndexOf(",", idIndex) - idIndex - 4);
  171. //string str = fileJson.Substring(idIndex, fileJson.Length - fileJson)
  172. return idString.Replace("\"", "");
  173. }
  174. #endregion // Private Methods
  175. #region Protected Methods
  176. /// <inheritdoc/>
  177. protected override void SaveMemoryStream(MemoryStream ms)
  178. {
  179. bool isExist = false;
  180. try
  181. {
  182. UploadNewFile(ms);
  183. }
  184. catch (Exception ex)
  185. {
  186. if (ex.Message.Contains("409"))
  187. isExist = true;
  188. else
  189. throw new CloudStorageException(ex.Message, ex);
  190. }
  191. try
  192. {
  193. if (isExist)
  194. UploadExistFile(ms);
  195. }
  196. catch (Exception ex)
  197. {
  198. throw new CloudStorageException(ex.Message, ex);
  199. }
  200. }
  201. #endregion // Protected Methods
  202. #region Public Methods
  203. /// <summary>
  204. /// Gets the authorization URL.
  205. /// </summary>
  206. /// <returns>The authorization URL stirng.</returns>
  207. public string GetAuthorizationUrl()
  208. {
  209. return String.Format($@"https://account.box.com/api/oauth2/authorize?client_id={clientInfo.Id}&response_type=code");
  210. }
  211. /// <summary>
  212. /// Gets the access token.
  213. /// </summary>
  214. /// <returns>The access token string.</returns>
  215. public string GetAccessToken()
  216. {
  217. System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
  218. WebRequest request = WebRequest.Create(@"https://api.box.com/oauth2/token");
  219. request.Method = HttpMethod.Post;
  220. RequestUtils.SetProxySettings(request, ProxySettings);
  221. request.ContentType = "application/x-www-form-urlencoded";
  222. byte[] content = BuildGetAccessTokenRequestContent();
  223. request.ContentLength = content.Length;
  224. using (Stream rs = request.GetRequestStream())
  225. {
  226. rs.Write(content, 0, content.Length);
  227. }
  228. using (WebResponse response = request.GetResponse())
  229. {
  230. accessToken = Parser.ParseGoogleDriveToken(response.GetResponseStream());
  231. }
  232. //WebResponse response = request.GetResponse();
  233. //accessToken = Parser.ParseGoogleDriveToken(response.GetResponseStream());
  234. return accessToken;
  235. }
  236. #endregion // Public Methods
  237. }
  238. }