Esempio n. 1
0
        /// <summary>
        /// Rename a file or directory in a torrent (API: torrent-rename-path)
        /// </summary>
        /// <param name="ids">The torrent whose path will be renamed</param>
        /// <param name="path">The path to the file or folder that will be renamed</param>
        /// <param name="name">The file or folder's new name</param>
        public async Task <RenameTorrentInfo> TorrentRenamePathAsync(int id, string path, string name)
        {
            var arguments = new Dictionary <string, object>();

            arguments.Add("ids", new int[] { id });
            arguments.Add("path", path);
            arguments.Add("name", name);

            var request  = new TransmissionRequest("torrent-rename-path", arguments);
            var response = await SendRequestAsync(request);

            var result = response.Deserialize <RenameTorrentInfo>();

            return(result);
        }
Esempio n. 2
0
        private async Task <TorrentGetResponse> GetTorrentFieldsInternal(object ids, TorrentFields[] fields)
        {
            var readableFields = fields ?? GetAllEnumItems <TorrentFields>();

            var request = new TransmissionRequest()
            {
                Method    = GetAttributeOfType <DisplayAttribute, Methods>(Methods.TorrentGet).Description,
                Arguments = new TorrentGetRequest()
                {
                    Ids    = ids,
                    Fields = GetDisplayAttributeDescriptions(readableFields)
                }
            };

            return(await this.ExecuteMethodChecked <TorrentGetResponse>(request));
        }
Esempio n. 3
0
        /// <summary>
        /// Rename a file or directory in a torrent (API: torrent-rename-path)
        /// </summary>
        /// <param name="ids">The torrent whose path will be renamed</param>
        /// <param name="path">The path to the file or folder that will be renamed</param>
        /// <param name="name">The file or folder's new name</param>
        public async Task <RenamedTorrent> TorrentRenamePathAsync(object id, string path, string name)
        {
            var arguments = new Dictionary <string, object>
            {
                { "ids", new object[] { id } },
                { "path", path },
                { "name", name }
            };

            var request  = new TransmissionRequest("torrent-rename-path", arguments);
            var response = await SendRequestAsync(request);

            var result = response.Deserialize <RenamedTorrent>();

            return(result);
        }
Esempio n. 4
0
        /// <summary>
        /// Get fields of torrents from ids (API: torrent-get)
        /// </summary>
        /// <param name="fields">Fields of torrents</param>
        /// <param name="ids">IDs of torrents (null or empty for get all torrents)</param>
        /// <returns>Torrents info</returns>
        public TransmissionTorrents TorrentGet(string[] fields, params int[] ids)
        {
            var arguments = new Dictionary <string, object>();

            arguments.Add("fields", fields);

            if (ids != null && ids.Length > 0)
            {
                arguments.Add("ids", ids);
            }

            var request = new TransmissionRequest("torrent-get", arguments);

            var response = SendRequest(request);
            var result   = response.Deserialize <TransmissionTorrents>();

            return(result);
        }
        /// <summary>
        /// Get fields of torrents from ids (API: torrent-get)
        /// </summary>
        /// <param name="fields">Fields of torrents</param>
        /// <param name="ids">IDs of torrents (null or empty for get all torrents)</param>
        /// <returns>Torrents info</returns>
        public async Task <Torrents> TorrentGetAsync(string[] fields, params int[] ids)
        {
            var arguments = new Dictionary <string, object>
            {
                { "fields", fields }
            };

            if (ids != null && ids.Length > 0)
            {
                arguments.Add("ids", ids);
            }

            var request = new TransmissionRequest("torrent-get", arguments);

            var response = await SendRequestAsync(request);

            return(response.Deserialize <Torrents>());
        }
Esempio n. 6
0
        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(Host);

                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);
        }
Esempio n. 7
0
 /// <summary>
 /// Close current session (API: session-close)
 /// </summary>
 public async void CloseSessionAsync()
 {
     var request  = new TransmissionRequest("session-close");
     var response = await SendRequestAsync(request);
 }
Esempio n. 8
0
 /// <summary>
 /// Close current session (API: session-close)
 /// </summary>
 public void CloseSession()
 {
     var request  = new TransmissionRequest("session-close");
     var response = SendRequest(request);
 }
Esempio n. 9
0
 /// <summary>
 /// Set torrent params (API: torrent-set)
 /// </summary>
 /// <param name="torrentSet">New torrent params</param>
 public async void TorrentSetAsync(TorrentSettings settings)
 {
     var request  = new TransmissionRequest("torrent-set", settings);
     var response = await SendRequestAsync(request);
 }
Esempio n. 10
0
 /// <summary>
 /// Set torrent params (API: torrent-set)
 /// </summary>
 /// <param name="torrentSet">New torrent params</param>
 public void TorrentSet(TorrentSettings settings)
 {
     var request  = new TransmissionRequest("torrent-set", settings);
     var response = SendRequest(request);
 }
        /// <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
            });
        }
Esempio n. 12
0
 /// <summary>
 /// Set torrent params (API: torrent-set)
 /// </summary>
 /// <param name="torrentSet">New torrent params</param>
 public void SetTorrents(TorrentSettings settings)
 {
     var request  = new TransmissionRequest("torrent-set", settings.ToDictionary());
     var response = SendRequest(request);
 }
        /// <summary>
        /// Set information to current session (API: session-set)
        /// </summary>
        /// <param name="settings">New session settings</param>
        public async void SessionSetAsync(SessionSettings settings)
        {
            var request = new TransmissionRequest("session-set", settings.ToDictionary());

            await SendRequestAsync(request);
        }
        /// <summary>
        /// Close current session (API: session-close)
        /// </summary>
        public async void SessionCloseAsync()
        {
            var request = new TransmissionRequest("session-close", null);

            await SendRequestAsync(request);
        }
        /// <summary>
        /// Set torrent params (API: torrent-set)
        /// </summary>
        /// <param name="settings">New torrent params</param>
        public async void TorrentSetAsync(TorrentSettings settings)
        {
            var request = new TransmissionRequest("torrent-set", settings.ToDictionary());

            await SendRequestAsync(request);
        }
Esempio n. 16
0
 /// <summary>
 /// Set information to current session (API: session-set)
 /// </summary>
 /// <param name="settings">New session settings</param>
 public void SetSessionSettings(SessionSettings settings)
 {
     var request  = new TransmissionRequest("session-set", settings);
     var response = SendRequest(request);
 }
Esempio n. 17
0
 /// <summary>
 /// Set information to current session (API: session-set)
 /// </summary>
 /// <param name="settings">New session settings</param>
 public async void SetSessionSettingsAsync(SessionSettings settings)
 {
     var request  = new TransmissionRequest("session-set", settings);
     var response = await SendRequestAsync(request);
 }
Esempio n. 18
0
        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);
                }
            }