private async Task <TransmissionResponse> SendRequestAsync(TransmissionRequest request) { TransmissionResponse result = new TransmissionResponse(); request.Tag = ++CurrentTag; try { byte[] byteArray = Encoding.UTF8.GetBytes(request.ToJson()); //Prepare http web request HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url); webRequest.ContentType = "application/json-rpc"; webRequest.Headers["X-Transmission-Session-Id"] = SessionID; webRequest.Method = "POST"; if (_needAuthorization) { webRequest.Headers["Authorization"] = _authorization; } using (Stream dataStream = await webRequest.GetRequestStreamAsync()) { dataStream.Write(byteArray, 0, byteArray.Length); } //Send request and prepare response using (var webResponse = await webRequest.GetResponseAsync()) { using (Stream responseStream = webResponse.GetResponseStream()) { var reader = new StreamReader(responseStream, Encoding.UTF8); var responseString = reader.ReadToEnd(); result = JsonConvert.DeserializeObject <TransmissionResponse>(responseString); if (result.Result != "success") { throw new Exception(result.Result); } } } } catch (WebException ex) { if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.Conflict) { if (ex.Response.Headers.Count > 0) { //If session id expiried, try get session id and send request SessionID = ex.Response.Headers["X-Transmission-Session-Id"]; if (SessionID == null) { throw new Exception("Session ID Error"); } result = await SendRequestAsync(request); } } else { throw ex; } } return(result); }
/// <summary> /// Add torrents (API: torrent-add) /// </summary> /// <param name="torrents"></param> /// <returns>Torrent info (ID, Name and HashString)</returns> public async Task <AddTorrentsResponse> TorrentsAddAsync(List <NewTorrent> torrents) { var successes = new List <AddTorrentSuccess>(); var failures = new List <AddTorrentFailure>(); foreach (var torrent in torrents) { try { var request = new TransmissionRequest("torrent-add", torrent.ToDictionary()); TransmissionResponse response = await SendRequestAsync(request); if (!response.Result.Equals("success", StringComparison.OrdinalIgnoreCase)) { failures.Add(new AddTorrentFailure { SubmittedData = torrent.Filename ?? torrent.MetaInfo, SubmittedDataType = !string.IsNullOrEmpty(torrent.Filename) ? "file or url" : "meta info", Error = response.Result }); continue; } JObject jObject = response.Deserialize <JObject>(); if (jObject?.First == null) { failures.Add(new AddTorrentFailure { SubmittedData = torrent.Filename ?? torrent.MetaInfo, SubmittedDataType = !string.IsNullOrEmpty(torrent.Filename) ? "file or url" : "meta info", Error = "Deserialization error" }); continue; } if (jObject.TryGetValue("torrent-duplicate", out JToken value)) { successes.Add(new AddTorrentSuccess { SubmittedData = torrent.Filename ?? torrent.MetaInfo, SubmittedDataType = !string.IsNullOrEmpty(torrent.Filename) ? "file or url" : "meta info", TransmissionResponse = JsonConvert.DeserializeObject <CreatedTorrent>(value.ToString()) }); continue; } if (jObject.TryGetValue("torrent-added", out value)) { successes.Add(new AddTorrentSuccess { SubmittedData = torrent.Filename ?? torrent.MetaInfo, SubmittedDataType = !string.IsNullOrEmpty(torrent.Filename) ? "file or url" : "meta info", TransmissionResponse = JsonConvert.DeserializeObject <CreatedTorrent>(value.ToString()) }); } } catch (Exception e) { failures.Add(new AddTorrentFailure { SubmittedData = torrent.Filename ?? torrent.MetaInfo, SubmittedDataType = !string.IsNullOrEmpty(torrent.Filename) ? "file or url" : "meta info", Error = $"Unknown error occurred: {e.Message}" }); } } return(new AddTorrentsResponse { Successes = successes.Any() ? successes : null, Failures = failures.Any() ? failures : null }); }
private async Task <TransmissionResponse> SendRequestAsync(TransmissionRequest request, CancellationToken token) { var result = new TransmissionResponse(); request.Tag = ++CurrentTag; var counter = 0; var byteArray = Encoding.UTF8.GetBytes(request.ToJson()); //Prepare http web request if (!CheckURLValid(Url)) { throw new WebException("Host error", WebExceptionStatus.NameResolutionFailure); } while (counter < NumberOfAttempts) { try { var webRequest = (HttpWebRequest)WebRequest.Create(Url); webRequest.ContentType = "application/json-rpc"; webRequest.Method = "POST"; if (_needAuthorization) { webRequest.Headers["Authorization"] = _authorization; } webRequest.Headers["X-Transmission-Session-Id"] = SessionId; await using (var dataStream = await webRequest.GetRequestStreamAsync()) { await dataStream.WriteAsync(byteArray, 0, byteArray.Length, token); } //Send request and prepare response using var webResponse = await webRequest.GetResponseAsync(token); await using var responseStream = await webResponse.GetResponseStream(token); if (responseStream == null) { result.CustomException = new Exception("Stream resonse is null"); Log.Error(result.WebException); return(result); } var reader = new StreamReader(responseStream, Encoding.UTF8); var responseString = await reader.ReadToEndAsync(token); result = JsonConvert.DeserializeObject <TransmissionResponse>(responseString); if (result.Result != "success") { throw new Exception(result.Result); } break; } catch (TaskCanceledException) { result.Result = "canceled"; return(result); } }