Guest User

Untitled

a guest
Feb 14th, 2012
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.93 KB | None | 0 0
  1. // JSON-RPC messages to transmission-daemon
  2. // http://groups.google.com/group/jayrock/t/c74e23f257e601b1
  3.  
  4. using System;
  5. using System.Net;
  6. using System.Collections;
  7. using Jayrock.Json;
  8. using Jayrock.Json.Conversion;
  9.  
  10. static class Program
  11. {
  12.     static void Main()
  13.     {
  14.         var url = new Uri("http://192.168.0.8:9091/transmission/rpc");
  15.         var client = new TransmissionClient(url);
  16.         string[] torrentNames = new string[100];
  17.         string[] torrentPercent = new string[100];
  18.         JsonObject session = (JsonObject)client.Invoke("session-stats", null);
  19.         JsonNumber num = (JsonNumber)session["activeTorrentCount"];
  20.         int numTorrents = (int)num;
  21.         Console.WriteLine("Active Torrents: " + session["activeTorrentCount"]);
  22.         Console.WriteLine("Download Speed: " + session["downloadSpeed"] + " Bytes/s");
  23.         Console.WriteLine("Upload Speed: " + session["uploadSpeed"] + " Bytes/s");
  24.         var torrent = (IDictionary) client.Invoke("torrent-get", new { fields = new[] { "name", "percentDone" } }, null);
  25.         var i=0;
  26.         Console.WriteLine();
  27.         Console.WriteLine("Current Torrents:");
  28.           foreach (IDictionary torrents in (IList) torrent["torrents"]){
  29.           Console.WriteLine();
  30.             if (i<numTorrents)
  31.             {
  32.               torrentNames[i] = (string)torrents["name"];
  33.               JsonNumber percent = (JsonNumber)torrents["percentDone"];
  34.               double tempPercent = (double)percent;
  35.               torrentPercent[i] = tempPercent.ToString("0%");
  36.               Console.WriteLine(torrentNames[i] + " - " + (torrentPercent[i]));
  37.               i++;
  38.             }
  39.           }
  40.       }
  41. }
  42.  
  43. class TransmissionClient
  44. {
  45.     public Uri Url { get; private set; }
  46.     public WebClient WebClient { get; set; }
  47.     public string SessionId { get; private set; }
  48.  
  49.     public TransmissionClient(Uri url) : this(url, null) {}
  50.  
  51.     public TransmissionClient(Uri url, WebClient wc)
  52.     {
  53.         if (url == null) throw new ArgumentNullException("url");
  54.         Url = url;
  55.         WebClient = wc;
  56.     }
  57.  
  58.     public object Invoke(string method, object args)
  59.     {
  60.         return Invoke(method, args, null);
  61.     }
  62.  
  63.     public virtual object Invoke(string method, object args, JsonNumber? tag)
  64.     {
  65.         if (method == null) throw new ArgumentNullException("method");
  66.  
  67.         var sessionId = SessionId;
  68.         var wc = WebClient ?? new WebClient();
  69.         var url = Url;
  70.  
  71.         // 2.1.  Requests
  72.         //  
  73.         //     Requests support three keys:
  74.         //  
  75.         //     (1) A required "method" string telling the name of the method to invoke
  76.         //     (2) An optional "arguments" object of key/value pairs
  77.         //     (3) An optional "tag" number used by clients to track responses.
  78.         //         If provided by a request, the response MUST include the same tag.
  79.  
  80.         var request = new
  81.         {
  82.             method,
  83.             arguments = args,
  84.             tag,
  85.         };
  86.  
  87.         while (true)
  88.         {
  89.             try
  90.             {
  91.                 if (!string.IsNullOrEmpty(sessionId))
  92.                     wc.Headers.Add("X-Transmission-Session-Id", sessionId);
  93.                 var requestJson = JsonConvert.ExportToString(request);
  94.                 var responseJson = wc.UploadString(url, requestJson);
  95.  
  96.                 // 2.2.  Responses
  97.                 //  
  98.                 //     Reponses support three keys:
  99.                 //  
  100.                 //     (1) A required "result" string whose value MUST be "success" on success,
  101.                 //         or an error string on failure.
  102.                 //     (2) An optional "arguments" object of key/value pairs
  103.                 //     (3) An optional "tag" number as described in 2.1.
  104.  
  105.                 var responseObject = JsonConvert.Import<JsonObject>(responseJson);
  106.  
  107.                 var result = (responseObject["result"] ?? string.Empty).ToString();
  108.                 if ("error".Equals(result, StringComparison.OrdinalIgnoreCase))
  109.                     throw new Exception("Method failed.");
  110.                 if (!"success".Equals(result, StringComparison.OrdinalIgnoreCase))
  111.                     throw new Exception("Unexpected response result.");
  112.                
  113.                 if (tag != null && tag.Value.LogicallyEquals(responseObject["tag"]))
  114.                     throw new Exception("Missing or unexpected tag in response.");
  115.                
  116.                 return responseObject["arguments"];
  117.             }
  118.             catch (WebException e)
  119.             {
  120.                 // 2.3.1.  CSRF Protection
  121.                 //
  122.                 //     Most Transmission RPC servers require a X-Transmission-Session-Id
  123.                 //     header to be sent with requests, to prevent CSRF attacks.
  124.                 //  
  125.                 //     When your request has the wrong id -- such as when you send your first
  126.                 //     request, or when the server expires the CSRF token -- the
  127.                 //     Transmission RPC server will return an HTTP 409 error with the
  128.                 //     right X-Transmission-Session-Id in its own headers.
  129.                 //
  130.                 //     So, the correct way to handle a 409 response is to update your
  131.                 //     X-Transmission-Session-Id and to resend the previous request.
  132.  
  133.                 HttpWebResponse response;
  134.                 if (e.Status == WebExceptionStatus.ProtocolError
  135.                     && (response = e.Response as HttpWebResponse) != null
  136.                     && response.StatusCode == /* 409 */ HttpStatusCode.Conflict)
  137.                 {
  138.                     sessionId = response.GetResponseHeader("X-Transmission-Session-Id");
  139.                     if (!string.IsNullOrEmpty(sessionId))
  140.                     {
  141.                         SessionId = sessionId;
  142.                         continue;
  143.                     }
  144.                 }
  145.  
  146.                 throw;
  147.             }
  148.         }
  149.     }
  150. }
Advertisement
Add Comment
Please, Sign In to add comment