forked from Abasz/rtorrent-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rTorrentRequest.cs
executable file
·64 lines (53 loc) · 2.24 KB
/
rTorrentRequest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using rTorrentLib.Model;
namespace rTorrentLib
{
public class rTorrentRequest
{
public List<TorrentCommand> TorrentCommands { get; }
public string CommandString { get; }
public rTorrentClient TorrentClient { get; }
public rTorrentRequest(List<TorrentCommand> torrentCommands, string ipAddress = "127.0.0.1", int port = 5000)
{
if (torrentCommands.Count == 0)throw new NullReferenceException("XMLRPC command is missing");
TorrentClient = new rTorrentClient(ipAddress, port);
TorrentCommands = torrentCommands;
CommandString = XmlRpcTorrentSerialize();
}
public async Task<rTorrentResponse<T>> SendCommand<T>(Func<IEnumerable<XElement>, T> parser)
{
var response = TorrentClient.Connect(CommandString);
return new rTorrentResponse<T>(await response, parser);
}
private string XmlRpcTorrentSerialize()
{
var str = new StringBuilder();
str.Append($"<?xml version='1.0' encoding='iso-8859-1'?><methodCall><methodName>");
str.Append($"system.multicall</methodName><params><param><value><array><data>");
foreach (var command in TorrentCommands)
{
str.Append($"<value><struct><member><name>methodName</name><value><string>{command.Command}</string></value></member><member><name>params</name><value><array><data>");
foreach (var param in command.Parameters)
{
str.Append($"<value><{GetParameterType(param)}>{param}</{GetParameterType(param)}></value>");
}
str.Append("</data></array></value></member></struct></value>");
}
str.Append($"</data></array></value></param>");
str.Append("</params></methodCall>");
return str.ToString();
}
protected static string GetParameterType(object parameter)
{
if ((parameter is long))
return "i4";
if (parameter is float)
return "i8";
return "string";
}
}
}