Beispiel #1
0
 private void rssEntryAddClicked(object sender, RoutedEventArgs e)
 {
     var button = (sender as Button);
     var entry = (RssFeedEntry)button.Tag;
     var magnetLink = new MagnetLink(entry.Link);
     AddTorrent(magnetLink, SettingsManager.DefaultDownloadLocation);
 }
Beispiel #2
0
 private void rssEntryAddClicked(object sender, RoutedEventArgs e)
 {
     var button = (sender as Button);
     var entry = (RssFeedEntry)button.Tag;
     var magnetLink = new MagnetLink(entry.Link);
     if (!SettingsManager.PromptForSaveOnShellLinks)
         AddTorrent(magnetLink, SettingsManager.DefaultDownloadLocation);
     else
     {
         var window = new AddTorrentWindow(SettingsManager);
         window.MagnetLink = magnetLink;
         if (window.ShowDialog().Value)
             AddTorrent(window.MagnetLink, window.DestinationPath);
     }
 }
Beispiel #3
0
 public void AddTorrent(MagnetLink link, string path, bool suppressMessages = false)
 {
     if (!Directory.Exists(path))
         Directory.CreateDirectory(path);
     var name = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(link.Name));
     var cache = Path.Combine(
             SettingsManager.TorrentCachePath,
             ClientManager.CleanFileName(name) + ".torrent");
     var wrapper = new TorrentWrapper(link, path, new TorrentSettings(), cache);
     if (Client.Torrents.Any(t => t.Torrent.InfoHash == wrapper.InfoHash))
     {
         if (!suppressMessages)
             MessageBox.Show(name + " has already been added.", "Error");
         return;
     }
     var periodic = Client.AddTorrent(wrapper);
     File.WriteAllText(Path.Combine(
             SettingsManager.TorrentCachePath,
             ClientManager.CleanFileName(name) + ".info"),
             path);
     periodic.CacheFilePath = cache;
 }
Beispiel #4
0
        public static byte[] GetMagnetFromCache(MagnetLink mg)
        {
            for (int i = 0; i < TorrentCaches.Length; i++)
            {
                try
                {
                    byte[] res = TorrentCaches[i].Fetch(mg);

                    if (res != null)
                        return res;
                }
                catch
                {
                    continue;
                }
            }

            return null;
        }
Beispiel #5
0
        public async void AddTorrentByMagnet(string magnet, bool notifyIfAdded = true)
        {
            MagnetLink mg = null;

            try { mg = new MagnetLink(magnet); }
            catch { MessageBox.Show("Invalid magnet link", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; }

            if (this.ContainTorrent(mg.InfoHash.ToHex()))
            {
                if (notifyIfAdded)
                {
                    NotificationManager.Notify(new TorrentAlreadyAddedNotification(mg.Name, mg.InfoHash.ToHex()));
                }
                return;
            }

            if (App.Settings.PreferMagnetCacheWebsites)
            {
                byte[] torrent_data = await System.Threading.Tasks.Task.Run<byte[]>(() => State.GetMagnetFromCache(mg));
                if (torrent_data != null)
                {
                    string path = this.SaveMagnetLink(torrent_data, mg.Name);
                    this.AddTorrentByPath(path);
                    return;
                }
            }

            this.LibtorrentSession.AsyncAddTorrent(new Ragnar.AddTorrentParams()
            {
                SavePath = App.Settings.DefaultDownloadPath,
                Url = magnet,
                Name = string.IsNullOrEmpty(mg.Name) ? "" : mg.Name
            });

            //NotificationManager.Notify(new MagnetLinkNotification(MagnetLinkNotification.EventType.MetadataDownloadStarted, mg));
        }
Beispiel #6
0
 private void CheckMagnetLinks()
 {
     var visibility = Visibility.Collapsed;
     if (Clipboard.ContainsText())
     {
         var text = Clipboard.GetText();
         if (IgnoredClipboardValue != text)
         {
             if (Uri.IsWellFormedUriString(text, UriKind.Absolute))
             {
                 var uri = new Uri(text);
                 if (uri.Scheme == "magnet")
                 {
                     try
                     {
                         var link = new MagnetLink(text);
                         if (!Client.Torrents.Any(t => t.Torrent.InfoHash == link.InfoHash))
                         {
                             quickAddName.Text = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(link.Name));
                             visibility = Visibility.Visible;
                         }
                     }
                     catch { }
                 }
             }
         }
     }
     quickAddGrid.Visibility = visibility;
 }
Beispiel #7
0
        private void QuickAddClicked(object sender, RoutedEventArgs e)
        {
            IgnoredClipboardValue = Clipboard.GetText();
            CheckMagnetLinks();

            var link = new MagnetLink(IgnoredClipboardValue);
            var name = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(link.Name));

            var path = Path.Combine(SettingsManager.DefaultDownloadLocation,
                ClientManager.CleanFileName(name));

            AddTorrent(link, path);
        }
Beispiel #8
0
 private string ConvertMagnetToString(MagnetLink value)
 {
     var result = "magnet:?";
     result += "xt=urn:btih:" + value.InfoHash.ToHex();
     result += "&dn=" + value.Name;
     foreach (var url in value.AnnounceUrls)
         result += "&tr=" + Uri.EscapeUriString(url);
     return result;
 }
Beispiel #9
0
 private void UpdateRss()
 {
     // Runs outside UI thread
     var entries = new List<RssFeedEntry>();
     var newTorrents = new List<RssFeedEntry>();
     if (SettingsManager.RssFeeds == null) return;
     foreach (var feed in SettingsManager.RssFeeds)
     {
         try
         {
             var diff = feed.Update();
             foreach (var item in diff)
             {
                 foreach (var rule in feed.TorrentRules)
                 {
                     if (rule.Type == RssTorrentRule.RuleType.Title)
                     {
                         if (rule.Regex.IsMatch(item.Title))
                         {
                             item.MatchingRule = rule;
                             newTorrents.Add(item);
                         }
                     }
                     else if (rule.Type == RssTorrentRule.RuleType.CreatedBy)
                     {
                         if (rule.Regex.IsMatch(item.Creator))
                         {
                             item.MatchingRule = rule;
                             newTorrents.Add(item);
                         }
                     }
                 }
             }
             entries.AddRange(feed.Entries);
         }
         catch { }
     }
     entries = new List<RssFeedEntry>(entries.OrderBy(e => e.PublishTime).ToArray());
     RssEntries = entries;
     Dispatcher.BeginInvoke(new Action(() => rssListView.ItemsSource = RssEntries));
     // Add new torrents
     foreach (var torrentEntry in newTorrents)
     {
         try
         {
             var magnetLink = new MagnetLink(torrentEntry.Link);
             Dispatcher.BeginInvoke(new Action(() =>
                 {
                     BalloonTorrent = null;
                     NotifyIcon.ShowBalloonTip(5000, "Added torrent from feed", torrentEntry.Title, System.Windows.Forms.ToolTipIcon.Info);
                     var torrent = AddTorrent(magnetLink, torrentEntry.MatchingRule.DownloadPath, true);
                     if (torrent != null)
                         torrent.Label = torrentEntry.MatchingRule.Label;
                 }));
         }
         catch { }
     }
 }
Beispiel #10
0
 public ITorrentManager AddMagnetLink(string url, string savePath)
 {
     var ml = new MagnetLink(url);
     return RegisterTorrentManager(new TorrentManager(ml, savePath, new TorrentSettings(), _torrentFileSavePath));
 }
        private void AddClicked(object sender, RoutedEventArgs e)
        {
            if (customDestinationTextBox.IsFocused)
                return;
            try
            {
                string name;
                if (magnetLinkRadioButton.IsChecked.Value)
                {
                    MagnetLink = new MagnetLink(magnetLinkTextBox.Text);
                    name = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(MagnetLink.Name));
                }
                else
                {
                    Torrent = Torrent.Load(torrentFileTextBox.Text);
                    name = Torrent.Name;
                }
                if (defaultDestinationRadioButton.IsChecked.Value)
                    DestinationPath = DefaultLocation;
                else if (recentRadioButton.IsChecked.Value)
                {
                    // TODO
                    MessageBox.Show("Recent locations is not yet implemented.");
                    return;
                }
                else
                    DestinationPath = customDestinationTextBox.Text;

                DestinationPath = Path.Combine(DestinationPath, ClientManager.CleanFileName(name));
            }
            catch
            {
                MessageBox.Show("Unable to load this torrent.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            DialogResult = true;
            Close();
        }
Beispiel #12
0
        HttpResponse ProcessRequest(IHttpContext context)
        {
            string diskPath = context.Request.Uri.OriginalString.TrimStart('/');
            //Console.WriteLine("Requesting: {0}", diskPath);

            SimpleTorrentSession mySession = ((SimpleTorrentSession)context.State.Session);

            if (mySession != null && !((SimpleTorrentSession)context.State.Session).LoggedIn)
            {
                if (diskPath == "simple.potato" || diskPath == "simple-action.potato")
                {
                    if (diskPath == "simple-action.potato")
                    {
                        try
                        {
                            var data = Encoding.UTF8.GetString(context.Request.Post).Split(new string[] { ":" }, 2, StringSplitOptions.None);
                            var action = data[0].ToLower();
                            var payload = data[1];

                            if (action == "login")
                            {
                                //<username>:<pass>
                                var loginPair = payload.Split(new string[] { ":" }, 2, StringSplitOptions.None);

                                foreach (var i in config.GetValues("SimpleUser"))
                                {
                                    //<username>:<scrypt N>:<32-byte scrypt output>
                                    var configPair = i.Split(new string[] { ":" }, 3, StringSplitOptions.None);

                                    if (loginPair[0].ToLower() == configPair[0].ToLower())
                                    {
                                        string calculatedHash =
                                            Convert.ToBase64String(Org.BouncyCastle.Crypto.Generators.SCrypt.Generate(Encoding.UTF8.GetBytes(loginPair[1]),
                                                Encoding.UTF8.GetBytes(config.GetValue("SimpleSalt")),
                                                int.Parse(configPair[1]), 8, 1, 32));

                                        if (configPair[2] == calculatedHash)
                                        {
                                            mySession.LoggedIn = true;
                                            mySession.Username = configPair[0];
                                            Console.WriteLine("simpletorrent: Login succeeded for {0}...", loginPair[0]);
                                            return new HttpResponse(HttpResponseCode.Ok, "OK", context.Request.Headers.KeepAliveConnection());
                                        }

                                        break;
                                    }
                                }

                                if (!mySession.LoggedIn)
                                {
                                    Console.WriteLine("simpletorrent: Failed login for {0}...", loginPair[0]);

                                    //Sleep to make brute force infeasable
                                    System.Threading.Thread.Sleep(1000);
                                    return new HttpResponse("text/plain; charset=utf-8",
                                                new MemoryStream(Encoding.UTF8.GetBytes("NO")),
                                                context.Request.Headers.KeepAliveConnection());
                                }
                            }
                        }
                        catch { }
                    }

                    return new HttpResponse("text/plain; charset=utf-8",
                            new MemoryStream(Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?><simpletorrent Login=\"None\" />")),
                            context.Request.Headers.KeepAliveConnection());
                }
            }

            if (mySession == null)
            {
                return new HttpResponse("text/plain; charset=utf-8",
                            new MemoryStream(Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?><simpletorrent Login=\"None\" />")),
                            context.Request.Headers.KeepAliveConnection());
            }

            if (diskPath == "simple.potato" && mySession.LoggedIn)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                sb.Append("<simpletorrent>");

                sb.Append(string.Format("<dht>{0}</dht>", engine.DhtEngine.TotalNodes));

                long freeSpace = -1;

                if (downloadsPathDrive != null)
                {
                    freeSpace = downloadsPathDrive.AvailableFreeSpace;
                }

                sb.Append(string.Format("<freespace>{0}</freespace>", freeSpace));

                //TODO: Might want to make udp detection more robust later.
                //For now, we're not including it.
                if (!dhtListner.HasReceivedMessages)
                {
                    sb.Append(string.Format("<noincomingudp/>"));
                }

                if (!engine.HasAcceptedConnections)
                {
                    sb.Append(string.Format("<noincomingtcp/>"));
                }

                foreach (var manager in engine.Torrents)
                {
                    var ti = torrentInformation[manager.InfoHash.ToHex()];

                    bool metaDataMode = manager.Torrent == null;
                    sb.Append("<torrent>");
                    sb.Append(string.Format("<state>{0}</state>", manager.State.ToString()));
                    sb.Append(string.Format("<name{0}>{1}</name>", metaDataMode ? " MetaDataMode=\"true\"" : "",
                        metaDataMode ? "" : WebUtility.HtmlEncode(manager.Torrent.Name)));
                    sb.Append(string.Format("<size>{0}</size>", metaDataMode ? -1 : manager.Torrent.Size));
                    sb.Append(string.Format("<progress>{0}</progress>", manager.Progress));
                    sb.Append(string.Format("<download>{0}</download>", manager.Monitor.DownloadDataSpeed));
                    sb.Append(string.Format("<upload>{0}</upload>", manager.Monitor.UploadDataSpeed));
                    sb.Append(string.Format("<leech>{0}</leech>", manager.Peers.Leechs));
                    sb.Append(string.Format("<seed>{0}</seed>", manager.Peers.Seeds));
                    sb.Append(string.Format("<infohash>{0}</infohash>", manager.InfoHash.ToHex()));

                    if (ti.CreationDateTime.HasValue)
                    {
                        sb.Append(string.Format("<starttime>{0}</starttime>",
                            ti.CreationDateTime.Value.ToJavaScriptMilliseconds().ToString()));
                        sb.Append(string.Format("<starttimeago>{0}</starttimeago>",
                            Math.Floor((DateTime.Now - ti.CreationDateTime.Value).TotalMilliseconds).ToString()));
                    }

                    sb.Append("</torrent>");
                }

                lock (messages)
                {
                    foreach (var message in messages.Where(a => a.id == mySession.ID))
                    {
                        sb.Append("<message>");
                        sb.Append(string.Format("<title>{0}</title>", WebUtility.HtmlEncode(message.Title)));
                        sb.Append(string.Format("<payload>{0}</payload>", WebUtility.HtmlEncode(message.Message)));
                        sb.Append(string.Format("<type>{0}</type>", WebUtility.HtmlEncode(message.Type.ToString())));
                        sb.Append(string.Format("<id>{0}</id>", WebUtility.HtmlEncode(Guid.NewGuid().ToString("N"))));
                        sb.Append("</message>");
                    }

                    messages.Clear();
                }

                sb.Append("</simpletorrent>");

                return new HttpResponse("text/plain; charset=utf-8", new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())),
                    context.Request.Headers.KeepAliveConnection());
            }
            else if (diskPath == "simple-files.potato" && mySession.LoggedIn)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                sb.Append("<simpletorrent>");

                foreach (var torrent in engine.Torrents)
                {
                    sb.Append("<torrent infohash=\"" + torrent.InfoHash.ToHex() + "\">");

                    var files = torrent.Torrent.Files.OrderBy(a => a.Path.Contains(Path.DirectorySeparatorChar) ? Path.DirectorySeparatorChar + a.Path : a.Path).ToArray();

                    foreach (var file in files)
                    {
                        sb.Append("<file>");
                        sb.Append(string.Format("<path>{0}</path>", WebUtility.HtmlEncode(file.Path.Contains(Path.DirectorySeparatorChar) ? Path.DirectorySeparatorChar + file.Path : file.Path)));
                        sb.Append(string.Format("<size>{0}</size>", file.Length));
                        sb.Append(string.Format("<progress>{0}</progress>", (decimal)file.BytesDownloaded / (decimal)file.Length));
                        sb.Append(string.Format("<priority>{0}</priority>", WebUtility.HtmlEncode(Enum.GetName(typeof(Priority), file.Priority))));
                        sb.Append("</file>");
                    }

                    sb.Append("</torrent>");
                }

                sb.Append("</simpletorrent>");

                return new HttpResponse("text/plain; charset=utf-8", new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())),
                    context.Request.Headers.KeepAliveConnection());
            }
            else if (diskPath == "simple-action.potato" && mySession.LoggedIn)
            {
                try
                {
                    var data = Encoding.UTF8.GetString(context.Request.Post).Split(new string[] { ":" }, 2, StringSplitOptions.None);
                    var action = data[0].ToLower();
                    var payload = data[1];

                    if (action == "add-torrent-links")
                    {
                        foreach (var i in payload.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            try
                            {
                                if (i.Trim().Length > 0)
                                {
                                    if (i.StartsWith("magnet"))
                                    {
                                        MagnetLink ml = new MagnetLink(i);
                                        if (engine.Torrents.Where(torrent => torrent.InfoHash == ml.InfoHash).Count() == 0)
                                        {
                                            TorrentManager tm = new TorrentManager(ml, downloadsPath, torrentDefaults, torrentsPath);
                                            engine.Register(tm);
                                            SetupTorrent(tm);
                                        }
                                    }
                                    else
                                    {
                                        var guid = torrentsPath + @"\" + Guid.NewGuid().ToString("N") + ".torrent";
                                        Torrent t = Torrent.Load(new Uri(i), guid);
                                        if (engine.Torrents.Where(torrent => torrent.InfoHash == t.InfoHash).Count() == 0)
                                        {
                                            TorrentManager tm = new TorrentManager(t, downloadsPath, torrentDefaults);
                                            engine.Register(tm);
                                            SetupTorrent(tm);
                                        }
                                        else
                                        {
                                            try
                                            {
                                                System.Threading.Thread.Sleep(100);
                                                File.Delete(guid);
                                            }
                                            catch
                                            {

                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                new SimpleMessage()
                                {
                                    Message = ex.ToString(),
                                    Type = SimpleMessageType.Exception,
                                    Title = "Exception: add-torrent-links",
                                    id = mySession.ID
                                }.AddMessage(messages);
                            }
                        }
                    }
                    else if (action == "delete-torrent")
                    {
                        try
                        {
                            var torrent = engine.Torrents.Where(a => a.InfoHash.ToHex().ToLower()
                                == payload.ToLower().Trim()).First();
                            File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes());
                            var ti = torrentInformation[torrent.InfoHash.ToHex()];
                            ti.ToRemove = "delete-torrent";
                            torrent.Stop();
                        }
                        catch (Exception ex)
                        {
                            new SimpleMessage()
                            {
                                Message = ex.ToString(),
                                Type = SimpleMessageType.Exception,
                                Title = "Exception: delete-torrent",
                                id = mySession.ID
                            }.AddMessage(messages);
                        }
                    }
                    else if (action == "delete-torrent-and-data")
                    {
                        try
                        {
                            var torrent = engine.Torrents.Where(a => a.InfoHash.ToHex().ToLower()
                                == payload.ToLower().Trim()).First();
                            File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes());
                            var ti = torrentInformation[torrent.InfoHash.ToHex()];
                            ti.ToRemove = "delete-torrent-and-data";
                            torrent.Stop();
                        }
                        catch (Exception ex)
                        {
                            new SimpleMessage()
                            {
                                Message = ex.ToString(),
                                Type = SimpleMessageType.Exception,
                                Title = "Exception: delete-torrent",
                                id = mySession.ID
                            }.AddMessage(messages);
                        }
                    }
                    else if (action == "logout")
                    {
                        Console.WriteLine("simpletorrent: Logout succeeded for {0}...", mySession.Username);
                        mySession.LoggedIn = false;
                        mySession.Username = null;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("EXCEPTY: {0}", ex.ToString());
                }
            }
            else if (diskPath == "simple-version.potato")
            {
                return new HttpResponse(HttpResponseCode.Ok, VERSION, context.Request.Headers.KeepAliveConnection());
            }
            else
            {
                if (diskPath.Trim() == "")
                {
                    diskPath = "simple.htm";
                }

                if (File.Exists(Path.Combine(@"web", diskPath)))
                {
                    var mime = new Dictionary<string, string>
                            {
                                {".css", "text/css"},
                                {".gif", "image/gif"},
                                {".htm", "text/html"},
                                {".html", "text/html"},
                                {".jpg", "image/jpeg"},
                                {".js", "application/javascript"},
                                {".png", "image/png"},
                                {".xml", "application/xml"},
                                {".svg", "image/svg+xml"}
                            };

                    var mimetype = "text/plain";
                    mime.TryGetValue(Path.GetExtension(diskPath), out mimetype);

                    return new HttpResponse(mimetype, File.OpenRead(Path.Combine(@"web", diskPath)),
                        context.Request.Headers.KeepAliveConnection());
                }
            }

            return new HttpResponse(HttpResponseCode.Ok, "", context.Request.Headers.KeepAliveConnection());
        }
Beispiel #13
0
 public static InfoHash FromMagnetLink(string magnetLink)
 => MagnetLink.Parse(magnetLink).InfoHash;
Beispiel #14
0
        public static byte[] GetMagnetFromCache(string uri)
        {
            MagnetLink mg = null;

            try { mg = new MagnetLink(uri); }
            catch { return null; }

            return GetMagnetFromCache(mg);
        }
Beispiel #15
0
        public void HandleArguments(string[] args)
        {
            if (args.Length == 0)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                    {
                        Visibility = Visibility.Visible;
                        Activate();
                    }));
                return;
            }
            if (args[0] == "--minimized")
            {
                Visibility = Visibility.Hidden;
                ShowInTaskbar = false;
                ShowActivated = false;
                WindowStyle = WindowStyle.None;
                Width = Height = 0;
                return;
            }
            Dispatcher.BeginInvoke(new Action(() =>
                {
                    try
                    {
                        var magnetLink = new MagnetLink(args[0]);
                        if (SettingsManager.PromptForSaveOnShellLinks)
                        {
                            var window = new AddTorrentWindow(SettingsManager);
                            window.MagnetLink = magnetLink;
                            if (window.ShowDialog().Value)
                            {
                                if (window.IsMagnet)
                                    AddTorrent(window.MagnetLink, window.DestinationPath);
                                else
                                    AddTorrent(window.Torrent, window.DestinationPath);

                                SaveSettings();

                                Visibility = Visibility.Visible;
                                Activate();
                                FlashWindow(new WindowInteropHelper(this).Handle, true);
                            }
                        }
                        else
                        {
                            var path = Path.Combine(SettingsManager.DefaultDownloadLocation, ClientManager.CleanFileName(magnetLink.Name));
                            if (!Directory.Exists(path))
                                Directory.CreateDirectory(path);
                            AddTorrent(magnetLink, path, true);
                        }
                    }
                    catch
                    {
                        try
                        {
                            var torrent = Torrent.Load(args[0]);
                            if (SettingsManager.PromptForSaveOnShellLinks)
                            {
                                var window = new AddTorrentWindow(SettingsManager, args[0]);
                                if (window.ShowDialog().Value)
                                {
                                    if (window.IsMagnet)
                                        AddTorrent(window.MagnetLink, window.DestinationPath);
                                    else
                                        AddTorrent(window.Torrent, window.DestinationPath);

                                    SaveSettings();

                                    Visibility = Visibility.Visible;
                                    Activate();
                                    FlashWindow(new WindowInteropHelper(this).Handle, true);
                                }
                            }
                            else
                            {
                                var path = Path.Combine(SettingsManager.DefaultDownloadLocation, ClientManager.CleanFileName(torrent.Name));
                                if (!Directory.Exists(path))
                                    Directory.CreateDirectory(path);
                                AddTorrent(torrent, path, true);

                                Visibility = Visibility.Visible;
                                Activate();
                                FlashWindow(new WindowInteropHelper(this).Handle, true);
                            }
                        }
                        catch { }
                    }
                }));
        }
Beispiel #16
0
        private void AddClicked(object sender, RoutedEventArgs e)
        {
            if (customDestinationTextBox.IsFocused)
                return;
            try
            {
                string name;
                if (magnetLinkRadioButton.IsChecked.Value)
                {
                    MagnetLink = new MagnetLink(magnetLinkTextBox.Text);
                    name = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(MagnetLink.Name));
                }
                else
                {
                    Torrent = Torrent.Load(torrentFileTextBox.Text);
                    name = Torrent.Name;
                }
                if (defaultDestinationRadioButton.IsChecked.Value)
                    DestinationPath = DefaultLocation;
                else if (recentRadioButton.IsChecked.Value)
                {
                    var recent = recentItemsComboBox.SelectedItem as FolderBrowserItem;
                    DestinationPath = recent.FullPath;
                }
                else
                    DestinationPath = customDestinationTextBox.Text;

                Settings.RecentDownloadLocations = new[] { DestinationPath }
                        .Concat(Settings.RecentDownloadLocations.Where(r => r != DestinationPath)).ToArray();

                DestinationPath = Path.Combine(DestinationPath, ClientManager.CleanFileName(name));
            }
            catch
            {
                MessageBox.Show("Unable to load this torrent.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            DialogResult = true;
            Close();
        }
Beispiel #17
0
 public TorrentWrapper(MagnetLink magnetLink, string savePath, TorrentSettings settings, string torrentSave)
     : base(magnetLink, savePath, settings, torrentSave)
 {
     Name = magnetLink.Name;
     Name = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(Name));
     Size = -1;
     IsMagnet = true;
 }
        public TorrentManager AddMagnetUrl(string magnet)
        {
            MagnetLink link = new MagnetLink(magnet);

            string metaStorage = metaSaveDirectory + "\\";
            Random random = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < 20; i++)
                metaStorage += random.Next(0, 9).ToString();
            metaStorage += ".meta";
            CreateDir(metaStorage);

            TorrentManager manager = new TorrentManager(link, saveDirectory, torrentSettings, metaStorage);
            torrentEngine.Register(manager);
            return manager;
        }
Beispiel #19
-1
 public PeriodicTorrent AddTorrent(MagnetLink link, string path, bool suppressMessages = false)
 {
     if (!Directory.Exists(path))
         Directory.CreateDirectory(path);
     var name = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(link.Name));
     var cache = Path.Combine(
             SettingsManager.TorrentCachePath,
             ClientManager.CleanFileName(name) + ".torrent");
     for (int i = 0; i < link.AnnounceUrls.Count; i++)
         link.AnnounceUrls[i] = HttpUtility.UrlDecode(HttpUtility.UrlDecode(link.AnnounceUrls[i]));
     var wrapper = new TorrentWrapper(link, path, new TorrentSettings(), cache);
     if (Client.Torrents.Any(t => t.Torrent.InfoHash == wrapper.InfoHash))
     {
         if (!suppressMessages)
             MessageBox.Show(name + " has already been added.", "Error");
         return null;
     }
     var periodic = Client.AddTorrent(wrapper);
     periodic.CacheFilePath = cache;
     periodic.UpdateInfo();
     var serializer = new JsonSerializer();
     using (var writer = new StreamWriter(Path.Combine(SettingsManager.TorrentCachePath,
         Path.GetFileNameWithoutExtension(periodic.CacheFilePath) + ".info")))
         serializer.Serialize(new JsonTextWriter(writer), periodic.TorrentInfo);
     return periodic;
 }