Ejemplo n.º 1
0
        private void OkDialogButton_Click(object sender, EventArgs e)
        {
            JsonObject request   = Requests.CreateBasicObject(ProtocolConstants.METHOD_TORRENTSET);
            JsonObject arguments = Requests.GetArgObject(request);

            arguments.Put(ProtocolConstants.KEY_IDS, Toolbox.ListViewSelectionToIdArray(selections));
            arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITUPENABLED, uploadLimitEnableField.Checked ? 1 : 0);
            arguments.Put(ProtocolConstants.FIELD_UPLOADLIMITED, uploadLimitEnableField.Checked ? 1 : 0);
            arguments.Put(ProtocolConstants.FIELD_UPLOADLIMIT, uploadLimitField.Value);
            arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITUP, uploadLimitField.Value);
            arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITDOWNENABLED, downloadLimitEnableField.Checked ? 1 : 0);
            arguments.Put(ProtocolConstants.FIELD_DOWNLOADLIMITED, downloadLimitEnableField.Checked ? 1 : 0);
            arguments.Put(ProtocolConstants.FIELD_DOWNLOADLIMIT, downloadLimitField.Value);
            arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITDOWN, downloadLimitField.Value);
            arguments.Put(ProtocolConstants.FIELD_PEERLIMIT, peerLimitValue.Value);
            if (seedRatioLimitValue.Enabled)
            {
                arguments.Put(ProtocolConstants.FIELD_SEEDRATIOLIMIT, seedRatioLimitValue.Value);
            }
            if (seedIdleLimitValue.Enabled)
            {
                arguments.Put(ProtocolConstants.FIELD_SEEDIDLELIMIT, seedIdleLimitValue.Value);
            }
            if (honorsSessionLimits.Enabled)
            {
                arguments.Put(ProtocolConstants.FIELD_HONORSSESSIONLIMITS, honorsSessionLimits.Checked);
            }
            if (seedRatioLimitedCheckBox.Enabled)
            {
                arguments.Put(ProtocolConstants.FIELD_SEEDRATIOMODE, (int)(2 - seedRatioLimitedCheckBox.CheckState));
            }
            if (seedIdleLimitedCheckBox.Enabled)
            {
                arguments.Put(ProtocolConstants.FIELD_SEEDIDLEMODE, (int)(2 - seedIdleLimitedCheckBox.CheckState));
            }
            if (bandwidthComboBox.Enabled)
            {
                int bandwidthPriority = 0;
                if (bandwidthComboBox.SelectedIndex == 0)
                {
                    bandwidthPriority = -1;
                }
                else if (bandwidthComboBox.SelectedIndex == 2)
                {
                    bandwidthPriority = 1;
                }
                arguments.Put(ProtocolConstants.FIELD_BANDWIDTHPRIORITY, bandwidthPriority);
            }

            Torrent   firstTorrent  = (Torrent)selections[0];
            JsonArray trackerRemove = new JsonArray();

            foreach (JsonObject tracker in firstTorrent.Trackers)
            {
                int id = Toolbox.ToInt(tracker[ProtocolConstants.FIELD_ID]);
                if (!trackersList.Items.Contains(id))
                {
                    trackerRemove.Add(id);
                }
            }
            JsonArray trackerReplace = new JsonArray();

            foreach (TrackerListItem t in trackersList.Items)
            {
                if (!t.Changed)
                {
                    continue;
                }
                trackerReplace.Add(t.Id);
                trackerReplace.Add(t.Announce);
            }
            JsonArray trackerAdd = new JsonArray();

            foreach (TrackerListItem t in trackersList.Items)
            {
                if (t.Id == -1)
                {
                    trackerAdd.Add(t.Announce);
                }
            }
            if (trackerRemove.Count > 0)
            {
                arguments.Put(ProtocolConstants.FIELD_TRACKER_REMOVE, trackerRemove);
            }
            if (trackerReplace.Count > 0)
            {
                arguments.Put(ProtocolConstants.FIELD_TRACKER_REPLACE, trackerReplace);
            }
            if (trackerAdd.Count > 0)
            {
                arguments.Put(ProtocolConstants.FIELD_TRACKER_ADD, trackerAdd);
            }
            Program.Form.SetupAction(CommandFactory.RequestAsync(request));
            this.Close();
        }
        static void wc_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                ICommand cmd;
                if (e.Error != null)
                {
                    var    ex    = e.Error as WebException;
                    string title = OtherStrings.Error;
                    if (ex?.Response != null)
                    {
                        HttpWebResponse response = (HttpWebResponse)ex.Response;
                        if (response.StatusCode == HttpStatusCode.Conflict && ((TransmissonRequest)e.UserState).allowRecursion)
                        {
                            try
                            {
                                string sessionid = ex.Response.Headers["X-Transmission-Session-Id"];
                                if (!string.IsNullOrEmpty(sessionid))
                                {
                                    TransmissionWebClient.XTransmissionSessionId = sessionid;
                                    ((TransmissionWebClient)sender).UploadDataAsync(new Uri(Program.Settings.Current.RpcUrl), null, ((TransmissonRequest)e.UserState).data, new TransmissonRequest(((TransmissonRequest)e.UserState).requestid, ((TransmissonRequest)e.UserState).data, false));
                                    return;
                                }
                            }
                            catch { }
                        }
                        else if (response.StatusCode == HttpStatusCode.NotFound)
                        {
                            title = OtherStrings.NotFound;
                            ex    = new WebException(OtherStrings.NotFoundError);
                        }
                        else if (response.StatusCode == HttpStatusCode.Forbidden || response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
                            {
                                String s = sr.ReadToEnd();
                                if (s.Contains("Unauthorized IP Address."))
                                {
                                    title = OtherStrings.UnauthorizedIP;
                                    ex    = new WebException(OtherStrings.UnauthorizedIPError);
                                }
                                else if (s.Contains("Unauthorized User"))
                                {
                                    title = OtherStrings.UnauthorizedUser;
                                    ex    = new WebException(OtherStrings.UnauthorizedUserError);
                                }
                            }
                        }
                    }
                    cmd = new ErrorCommand(title, ex?.Message, false);
                }
                else
                {
                    try
                    {
#if LOGRPC
                        Program.LogDebug("RPC response: " + ((TransmissonRequest)e.UserState).requestid, GetString(e.Result));
#endif
                        JsonObject jsonResponse = (JsonObject)JsonConvert.Import(GetString(e.Result));
                        if ((string)jsonResponse["result"] != "success")
                        {
                            string response = (string)jsonResponse["result"];
                            if (response.StartsWith("http error"))
                            {
                                int i = response.IndexOf(':');
                                if (i >= 0)
                                {
                                    response = response.Substring(i + 2);
                                }
                                else
                                {
                                    response = response.Remove(0, 11); /* strlen("http error") = 11 */
                                }
                                cmd = new ErrorCommand(OtherStrings.UnsuccessfulRequest, string.Format(OtherStrings.HttpError, Environment.NewLine, response), true);
                            }
                            else
                            {
                                cmd = new ErrorCommand(OtherStrings.UnsuccessfulRequest, response, true);
                            }
                            if (Toolbox.ToShort(jsonResponse[ProtocolConstants.KEY_TAG]).Equals((short)ResponseTag.UpdateBlocklist))
                            {
                                RemoteSettingsDialog.BlocklistUpdateDone(-1);
                            }
                        }
                        else
                        {
                            switch (Toolbox.ToShort(jsonResponse[ProtocolConstants.KEY_TAG]))
                            {
                            case (short)ResponseTag.TorrentGet:
                                cmd = new TorrentGetCommand(jsonResponse);
                                break;

                            case (short)ResponseTag.SessionGet:
                                cmd = new SessionCommand(jsonResponse, ((WebClient)sender).Headers);
                                break;

                            case (short)ResponseTag.SessionStats:
                                cmd = new SessionStatsCommand(jsonResponse);
                                break;

                            case (short)ResponseTag.UpdateFiles:
                                cmd = new UpdateFilesCommand(jsonResponse);
                                break;

                            case (short)ResponseTag.PortTest:
                                cmd = new PortTestCommand(jsonResponse);
                                break;

                            case (short)ResponseTag.UpdateBlocklist:
                                cmd = new UpdateBlocklistCommand(jsonResponse);
                                break;

                            case (short)ResponseTag.DoNothing:
                                cmd = new NoCommand();
                                break;

                            default:
                                cmd = new ErrorCommand(OtherStrings.UnknownResponseTag, e.Result != null ? GetString(e.Result) : "null", false);
                                break;
                            }
                        }
                    }
                    catch (InvalidCastException)
                    {
                        cmd = new ErrorCommand(OtherStrings.UnableToParse, e.Result != null ? GetString(e.Result) : "Null", false);
                    }
                    catch (JsonException ex)
                    {
                        cmd = new ErrorCommand($"{OtherStrings.UnableToParse} ({ex.GetType()})", GetString(e.Result), false);
                    }
                    catch (Exception ex)
                    {
                        cmd = new ErrorCommand(ex, false);
                    }
                }
                try
                {
                    cmd.Execute();
                }
                catch (Exception ee)
                { // just for debugging...
                    Console.WriteLine(ee.Message);
                    Program.LogDebug(ee.Source, ee.Message);
                }
                ((TransmissionWebClient)sender).OnCompleted(cmd);
            }
            else
            {
                if (!Program.Connected)
                {
                    Program.Connected = false;
                    Program.Form.UpdateStatus("", false);
                    Program.Form.connectButton.Enabled = Program.Form.connectToolStripMenuItem.Enabled = true;
                }
            }
        }
Ejemplo n.º 3
0
        private void TorrentPropertiesDialog_Load(object sender, EventArgs e)
        {
            Torrent firstTorrent = (Torrent)selections[0];

            this.Text = selections.Count == 1 ? firstTorrent.TorrentName : OtherStrings.MultipleTorrentProperties;
            uploadLimitField.Value     = firstTorrent.SpeedLimitUp >= 0 && firstTorrent.SpeedLimitUp <= uploadLimitField.Maximum ? firstTorrent.SpeedLimitUp : 0;
            downloadLimitField.Value   = firstTorrent.SpeedLimitDown >= 0 && firstTorrent.SpeedLimitDown <= downloadLimitField.Maximum ? firstTorrent.SpeedLimitDown : 0;
            uploadLimitField.Enabled   = uploadLimitEnableField.Checked = firstTorrent.SpeedLimitUpEnabled;
            downloadLimitField.Enabled = downloadLimitEnableField.Checked = firstTorrent.SpeedLimitDownEnabled;
            bandwidthComboBox.Items.Add(OtherStrings.Low);
            bandwidthComboBox.Items.Add(OtherStrings.Normal);
            bandwidthComboBox.Items.Add(OtherStrings.High);
            bandwidthComboBox.SelectedIndex = 1;
            try
            {
                honorsSessionLimits.Checked = firstTorrent.HonorsSessionLimits;
                honorsSessionLimits.Enabled = true;
            }
            catch
            {
                honorsSessionLimits.Enabled = false;
            }
            try
            {
                seedRatioLimitValue.Value           = firstTorrent.SeedRatioLimit >= 0 && (decimal)firstTorrent.SeedRatioLimit <= seedRatioLimitValue.Maximum ? (decimal)firstTorrent.SeedRatioLimit : 0;
                seedRatioLimitedCheckBox.CheckState = (CheckState)(2 - firstTorrent.SeedRatioMode);
                seedRatioLimitValue.Enabled         = seedRatioLimitedCheckBox.CheckState == CheckState.Checked;
                seedRatioLimitedCheckBox.Enabled    = true;
            }
            catch
            {
                seedRatioLimitValue.Enabled = seedRatioLimitedCheckBox.Enabled = false;
            }
            try
            {
                seedIdleLimitValue.Value           = firstTorrent.SeedIdleLimit >= 0 && (decimal)firstTorrent.SeedIdleLimit <= seedIdleLimitValue.Maximum ? (decimal)firstTorrent.SeedIdleLimit : 0;
                seedIdleLimitedCheckBox.CheckState = (CheckState)(2 - firstTorrent.SeedIdleMode);
                seedIdleLimitValue.Enabled         = seedIdleLimitedCheckBox.CheckState == CheckState.Checked;
                seedIdleLimitedCheckBox.Enabled    = true;
            }
            catch
            {
                seedIdleLimitValue.Enabled = seedIdleLimitedCheckBox.Enabled = false;
            }
            try
            {
                if (firstTorrent.BandwidthPriority < 0)
                {
                    bandwidthComboBox.SelectedIndex = 0;
                }
                else if (firstTorrent.BandwidthPriority > 0)
                {
                    bandwidthComboBox.SelectedIndex = 2;
                }
                else
                {
                    bandwidthComboBox.SelectedIndex = 1;
                }
                bandwidthLabel.Enabled = bandwidthComboBox.Enabled = true;
            }
            catch
            {
                bandwidthLabel.Enabled = bandwidthComboBox.Enabled = false;
            }
            peerLimitValue.Value = firstTorrent.MaxConnectedPeers >= 0 && (decimal)firstTorrent.MaxConnectedPeers <= peerLimitValue.Maximum ? (decimal)firstTorrent.MaxConnectedPeers : 0;
            // TODO: http://www.codeguru.com/cpp/controls/controls/lists,treesandcombos/article.php/c2291
            removeTrackerButton.Enabled = false;
            trackersList.Items.AddRange(
                Array.ConvertAll <JsonObject, TrackerListItem>((JsonObject[])firstTorrent.Trackers.ToArray(typeof(JsonObject)), delegate(JsonObject jo)
            {
                return(new TrackerListItem((string)jo[ProtocolConstants.ANNOUNCE], Toolbox.ToInt(jo[ProtocolConstants.FIELD_ID])));
            })
                );
        }
 public void UpdateStats(JsonObject stats)
 {
     try
     {
         Toolbox.MaxSize ms              = (Toolbox.MaxSize)(unitFactorComboBox.SelectedIndex + 1);
         JsonObject      sessionstats    = (JsonObject)stats["current-stats"];
         JsonObject      cumulativestats = (JsonObject)stats["cumulative-stats"];
         TimeSpan        ts              = TimeSpan.FromSeconds(Toolbox.ToLong(sessionstats["secondsActive"]));
         downloadedBytesValue1.Text = Toolbox.GetFileSize(Toolbox.ToLong(sessionstats["downloadedBytes"]), ms);
         uploadedBytesValue1.Text   = Toolbox.GetFileSize(Toolbox.ToLong(sessionstats["uploadedBytes"]), ms);
         filesAddedValue1.Text      = ((JsonNumber)sessionstats["filesAdded"]).ToString();
         sessionCountValue1.Text    = ((JsonNumber)sessionstats["sessionCount"]).ToString();
         secondsActiveValue1.Text   = Toolbox.FormatTimespanLong(ts);
         ts = TimeSpan.FromSeconds(Toolbox.ToLong(cumulativestats["secondsActive"]));
         downloadedBytesValue2.Text = Toolbox.GetFileSize(Toolbox.ToLong(cumulativestats["downloadedBytes"]), ms);
         uploadedBytesValue2.Text   = Toolbox.GetFileSize(Toolbox.ToLong(cumulativestats["uploadedBytes"]), ms);
         filesAddedValue2.Text      = ((JsonNumber)cumulativestats["filesAdded"]).ToString();
         sessionCountValue2.Text    = ((JsonNumber)cumulativestats["sessionCount"]).ToString();
         secondsActiveValue2.Text   = ts.Ticks < 0 ? OtherStrings.UnknownNegativeResult : Toolbox.FormatTimespanLong(ts);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Unable to load stats data", MessageBoxButtons.OK, MessageBoxIcon.Error);
         CloseAndDispose();
     }
 }