public void AddTorrent_Test()
            {
                if (!File.Exists(_filePath))
                {
                    throw new Exception("Torrent file not found");
                }

                var fstream = File.OpenRead(_filePath);

                byte[] filebytes = new byte[fstream.Length];
                fstream.Read(filebytes, 0, Convert.ToInt32(fstream.Length));

                string encodedData = Convert.ToBase64String(filebytes);

                //The path relative to the server (priority than the metadata)
                //string filename = "/DataVolume/shares/Public/Transmission/torrents/ubuntu-10.04.4-server-amd64.iso.torrent";

                var torrent = new NewTorrent
                {
                    //Filename = filename,
                    Metainfo = encodedData,
                    Paused   = true
                };

                var newTorrentInfo = _client.TorrentAdd(torrent);

                Assert.IsNotNull(newTorrentInfo);
                Assert.IsTrue(newTorrentInfo.ID != 0);
            }
Esempio n. 2
0
        internal void Parse(TorrentsList TorrentsToParse, bool IsFresh)
        {
            List <string> ListOfHashes = new List <string>();

            foreach (string[] TorrentArray in TorrentsToParse)
            {
                if (TorrentArray.Length == 0)
                {
                    throw new FormatException("The array of torrent data was not in the expected format, it contains 0 elements.");
                }
                ListOfHashes.Add(TorrentArray[0]);
                Torrent NewTorrent = GetByHashCode(TorrentArray[0]);
                if (NewTorrent == null)
                {
                    NewTorrent = new Torrent(TorrentArray, this);
                    _torrentCollectionInternal.Add(NewTorrent);
                    if (!IsFresh)
                    {
                        ParentClient.CallEvent(UTorrentWebClient.EventType.Added, NewTorrent);
                    }
                    CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, NewTorrent));
                }
                else
                {
                    NewTorrent.UpdateValuesFromStringArray(TorrentArray);
                }
            }
            IEnumerable <Torrent> RemovedTorrents = RemoveWhereHashCodeIsNotInList(ListOfHashes);

            foreach (Torrent RemovedTorrent in RemovedTorrents)
            {
                CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, RemovedTorrent));
            }
        }
        /// <summary>
        /// Add torrent (API: torrent-add)
        /// </summary>
        /// <param name="torrent"></param>
        /// <returns>Torrent info (ID, Name and HashString)</returns>
        public async Task <CreatedTorrent> TorrentAddAsync(NewTorrent torrent)
        {
            if (string.IsNullOrWhiteSpace(torrent.MetaInfo) && string.IsNullOrWhiteSpace(torrent.Filename))
            {
                throw new Exception("Either \"filename\" or \"metainfo\" must be included.");
            }

            var request = new TransmissionRequest("torrent-add", torrent.ToDictionary());

            TransmissionResponse response = await SendRequestAsync(request);

            JObject jObject = response.Deserialize <JObject>();

            if (jObject?.First == null)
            {
                return(null);
            }

            if (jObject.TryGetValue("torrent-duplicate", out JToken value))
            {
                return(JsonConvert.DeserializeObject <CreatedTorrent>(value.ToString()));
            }

            if (jObject.TryGetValue("torrent-added", out value))
            {
                return(JsonConvert.DeserializeObject <CreatedTorrent>(value.ToString()));
            }

            return(null);
        }
Esempio n. 4
0
        public async Task AddTorrent_Test()
        {
            Assert.IsTrue(File.Exists(FILE_PATH), "Torrent file not found");

            var fstream = File.OpenRead(FILE_PATH);

            byte[] filebytes = new byte[fstream.Length];
            fstream.Read(filebytes, 0, Convert.ToInt32(fstream.Length));

            string encodedData = Convert.ToBase64String(filebytes);

            //The path relative to the server (priority than the metadata)
            //string filename = "/DataVolume/shares/Public/Transmission/torrents/ubuntu-10.04.4-server-amd64.iso.torrent";
            var torrent = new NewTorrent
            {
                //Filename = filename,
                Metainfo = encodedData,
                Paused   = false
            };

            var newTorrentInfo = await client.TorrentAddAsync(torrent);

            Assert.IsNotNull(newTorrentInfo);
            Assert.IsTrue(newTorrentInfo.ID != 0);
        }
Esempio n. 5
0
        /// <summary>
        /// Add torrent (API: torrent-add)
        /// </summary>
        /// <returns>Torrent info (ID, Name and HashString)</returns>
        public async Task <NewTorrentInfo> TorrentAddAsync(NewTorrent torrent)
        {
            if (String.IsNullOrWhiteSpace(torrent.Metainfo) && String.IsNullOrWhiteSpace(torrent.Filename))
            {
                throw new Exception("Either \"filename\" or \"metainfo\" must be included.");
            }

            var request  = new TransmissionRequest("torrent-add", torrent);
            var response = await SendRequestAsync(request);

            var jObject = response.Deserialize <JObject>();

            if (jObject == null || jObject.First == null)
            {
                return(null);
            }

            NewTorrentInfo result = null;
            JToken         value  = null;

            if (jObject.TryGetValue("torrent-duplicate", out value))
            {
                result = JsonConvert.DeserializeObject <NewTorrentInfo>(value.ToString());
            }
            else if (jObject.TryGetValue("torrent-added", out value))
            {
                result = JsonConvert.DeserializeObject <NewTorrentInfo>(value.ToString());
            }

            return(result);
        }
Esempio n. 6
0
        private static void AddTorrent(NewTorrent torrent)
        {
            var client = CFG.Configuration.Default.TransmissionClient;

            var torrentInfo = client.TorrentAdd(torrent);

            ReportBack($"Torrent {torrentInfo.Name} was added to Transmission.");
        }
Esempio n. 7
0
        private static void AddBase64Torrent(string base64Torrent)
        {
            var torrent = new NewTorrent()
            {
                Metainfo = base64Torrent
            };

            AddTorrent(torrent);
        }
Esempio n. 8
0
        public async Task <NewTorrentInfo> TorrentAddAsync(NewTorrent torrent)
        {
            var newTorrent = mapper.Map <Transmission.API.RPC.Entity.NewTorrent>(torrent);

            newTorrent.Paused = true;
            var addedTorrents = await client.TorrentAddAsync(newTorrent);

            return(mapper.Map <NewTorrentInfo>(addedTorrents));
        }
Esempio n. 9
0
        private static void ProcessMagnetLink(string magnetUrl)
        {
            var torrent = new NewTorrent
            {
                Filename = magnetUrl
            };

            AddTorrent(torrent);
        }
Esempio n. 10
0
        public static void Main(string[] args)
        {
            var argIndex          = 0;
            var directory         = args[argIndex++];
            var url               = "http://osmc:9091/transmission/rpc";
            var downloadDirectory = "/media/EXTERNAL/downloads";
            var files             = Directory.GetFiles(directory, "*.torrent");

            foreach (var i in files)
            {
                var file = i;
                if (file.StartsWith(directory))
                {
                    file = file.Substring(directory.Length).TrimStart(Path.DirectorySeparatorChar);
                }
                Console.WriteLine(file);
            }
            Console.ReadLine();

            var client = new Client(url);

            foreach (var i in files)
            {
                var file = i;
                if (file.StartsWith(directory))
                {
                    file = file.Substring(directory.Length).TrimStart(Path.DirectorySeparatorChar);
                }
                var bytes   = File.ReadAllBytes(i);
                var base64  = Convert.ToBase64String(bytes);
                var torrent = new NewTorrent
                {
                    Metainfo          = base64,
                    DownloadDirectory = downloadDirectory,
                    Paused            = false,
                };
                var result = client.TorrentAdd(torrent);
                if ((result?.ID ?? 0) != 0)
                {
                    var loaded = Path.Combine("torrents", i + ".loaded");
                    if (File.Exists(loaded))
                    {
                        File.Delete(loaded);
                    }
                    if (!Directory.Exists("torrents"))
                    {
                        Directory.CreateDirectory("torrents");
                    }
                    File.Move(i, loaded);
                }
                else
                {
                    Console.Error.WriteLine("Error adding torrent", file);
                }
            }
        }
Esempio n. 11
0
        public void Download(DownloadHandle download)
        {
            // logically, "filename" can also be a URL
            var torrent = new NewTorrent {
                Filename = download.Uri
            };
            var response = _client.TorrentAdd(torrent);

            download.ClientMetadata["TransmissionTorrentId"] = response.ID;
        }
Esempio n. 12
0
 private async Task AddItemsToTorrentAsync(IEnumerable <ManagedItem> items)
 {
     foreach (var item in items)
     {
         logger.LogInformation($"Item Add: {item.Path}");
         NewTorrent torrent = new NewTorrent()
         {
             Filename          = item.Link,
             DownloadDirectory = item.Path
         };
         await client.TorrentAddAsync(torrent);
     }
 }
Esempio n. 13
0
        public async Task AddTorrentAsync(string torrentName, string torrentFile, string downloadDir, int nrOfFilesToInclude)
        {
            downloadDir = downloadDir.Replace('\\', '/');

            var torrent = new NewTorrent
            {
                Metainfo          = Convert.ToBase64String(File.ReadAllBytes(torrentFile)),
                DownloadDirectory = downloadDir,
                FilesWanted       = Enumerable.Range(0, nrOfFilesToInclude).ToArray()
            };

            await _rpcClient.TorrentAddAsync(torrent);
        }
Esempio n. 14
0
        public void AddTorrent_Magnet_Test()
        {
            var torrent = new NewTorrent
            {
                Filename = "magnet:?xt=urn:btih:9e241c218299b1d813275e066f94dbe05bc25e53&dn=Rick.and.Morty.S03E03.720p.HDTV.x264-BATV%5Bettv%5D&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969",
                Paused   = false
            };

            var newTorrentInfo = client.TorrentAdd(torrent);

            Assert.IsNotNull(newTorrentInfo);
            Assert.IsTrue(newTorrentInfo.ID != 0);
        }
 private void AddItemsToTorrent(IEnumerable <ManagedItem> items)
 {
     foreach (var item in items)
     {
         Debugger.Log(1, "Torrent", $"Item Add: {item.Path}");
         NewTorrent torrent = new NewTorrent()
         {
             Filename          = item.Link,
             DownloadDirectory = item.Path
         };
         client.TorrentAddAsync(torrent);
     }
 }
Esempio n. 16
0
        public NewTorrentInfo AddTorrent(NewTorrent torrent)
        {
            var newTorrent = this.transmissionClient.TorrentAdd(
                new NewTorrentCommand
            {
                Filename          = torrent.FileName,
                DownloadDirectory = torrent.DownloadDirectory
            });

            return(new NewTorrentInfo
            {
                Id = newTorrent.ID,
                Name = newTorrent.Name,
                HashString = newTorrent.HashString
            });
        }
Esempio n. 17
0
 internal void Parse(TorrentsList TorrentsToParse, RemovedTorrentsList RemovedTorrentsToParse, ChangedTorrentsList ChangedTorrentsToParse)
 {
     if (RemovedTorrentsToParse == null || ChangedTorrentsToParse == null)
     {
         if (TorrentsToParse != null)
         {
             Parse(TorrentsToParse, false);
         }
     }
     else
     {
         List <Torrent> RemovedTorrents = new List <Torrent>();
         foreach (string[] TorrentArray in RemovedTorrentsToParse)
         {
             if (TorrentArray.Length == 0)
             {
                 throw new FormatException("The array of torrent data was not in the expected format, it contains 0 elements.");
             }
             RemovedTorrents.Clear();
             RemovedTorrents.AddRange(RemoveByHashCode(TorrentArray[0]));
             foreach (Torrent RemovedTorrent in RemovedTorrents)
             {
                 CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, RemovedTorrent));
             }
         }
         foreach (string[] TorrentArray in ChangedTorrentsToParse)
         {
             if (TorrentArray.Length == 0)
             {
                 throw new FormatException("The array of torrent data was not in the expected format, it contains 0 elements.");
             }
             Torrent NewTorrent = GetByHashCode(TorrentArray[0]);
             if (NewTorrent == null)
             {
                 NewTorrent = new Torrent(TorrentArray, this);
                 _torrentCollectionInternal.Add(NewTorrent);
                 ParentClient.CallEvent(UTorrentWebClient.EventType.Added, NewTorrent);
                 CallCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, NewTorrent));
             }
             else
             {
                 NewTorrent.UpdateValuesFromStringArray(TorrentArray);
             }
         }
     }
 }
Esempio n. 18
0
        public override Task <string> Download(string path, ITorrentSearchResult searchResult)
        {
            return(Task.Run(() => {
                var client = CreateClient();

                var torrent = new NewTorrent {
                    Filename = searchResult.MagnetUri, DownloadDirectory = Path.Combine(path, searchResult.Name)
                };
                var result = client.AddTorrent(torrent);
                if (!string.IsNullOrEmpty(result.ErrorString))
                {
                    throw new NovaromaException(result.ErrorString + " (" + result.Error + ")");
                }

                return result.HashString;
            }));
        }
        public async void Download(SearchResponse sr, long chatId)
        {
            System.Console.WriteLine($"downloading {sr.Title}...");


            //services
            var transmission = _scope.CreateScope().ServiceProvider.GetRequiredService <TransmissionService>().Client;
            var database     = _scope.CreateScope().ServiceProvider.GetRequiredService <DatabaseContext>();

            System.Console.WriteLine(Directory.GetCurrentDirectory());

            var torrentSettings = new TorrentSettings();

            NewTorrent torrent;

            System.Console.WriteLine("trying with magnet");
            var metadata = await _engine.DownloadMetadataAsync(MagnetLink.Parse(sr.MagnetUrl), CancellationToken.None);

            System.Console.WriteLine("downloaded metadata");

            torrent = new NewTorrent()
            {
                Metainfo = Convert.ToBase64String(metadata)
            };


            var torrentInfo = transmission.TorrentAdd(torrent);

            if (database.ActiveTorrents.Any(at => at.TorrentId == torrentInfo.ID))
            {
                return;
            }

            var activeTorrent = new ActiveTorrent()
            {
                ChatId     = chatId,
                TorrentId  = torrentInfo.ID,
                IsFinished = false,
            };

            database.ActiveTorrents.Add(activeTorrent);
            database.SaveChanges();
        }
Esempio n. 20
0
        public async Task DownloadLink(string url)
        {
            if (!_isDownload)
            {
                return;
            }

            //TODO add disc space check


            var name = url.Split("//")[1].Replace('/', '_');
            await NetUtills.DownloadFileFromUrl(url, "/home/pi/torrents/", name);

            var info = new NewTorrent {
                Filename = name
            };


            await _client.TorrentAddAsync(info);
        }
        public IHttpActionResult PostBottom([FromBody] NewTorrent torrent)
        {
            if (torrent == null)
            {
                return(BadRequest());
            }

            lock (accessObj)
            {
                string[] newData = new string[] { torrent.link };

                if (!File.Exists(FilePath))
                {
                    File.WriteAllLines(FilePath, newData);
                }
                else
                {
                    string[] lines = File.ReadAllLines(FilePath);
                    File.WriteAllLines(FilePath, lines.Concat(newData));
                }
            }

            return(Ok());
        }
Esempio n. 22
0
        private async void BtnOK_Click(object sender, EventArgs e)
        {
            string s1 = this.tbSaveFolder.Text;

            if (!Helper.CheckPath(ref s1, this.isWindowsPath))
            {
                return;
            }

            string s2 = Path.GetFileName(s1);

            try
            {
                if (this.cbSkipHashCheck.Checked)
                {
                    if (!Helper.CanSkipCheck(
                            this.bencodeTorrent,
                            Helper.GetVirtualPath(s1, this.actualToVirtualDic), false))
                    {
                        this.isAddTorrentSuccess = false;
                        this.failedReason        = "跳过哈希检测失败";
                        return;
                    }
                }

                if (this.btClient == Config.BTClient.qBittorrent)
                {
                    await QbtWebAPI.API.DownloadFromDisk(
                        new List <string>() { torrentPath },
                        s1, null,
                        string.IsNullOrWhiteSpace(this.cbCategory.Text)?
                        null : this.cbCategory.Text,
                        this.cbSkipHashCheck.Checked, !this.cbStartTorrent.Checked,
                        false, s2, null, null, null, null);
                }
                else if (this.btClient == Config.BTClient.Transmission)
                {
                    Debug.Assert(transmissionClient != null);
                    var addedTorrent = new NewTorrent
                    {
                        Metainfo          = Helper.GetTransmissionTorrentAddMetainfo(torrentPath),
                        DownloadDirectory = (
                            bencodeTorrent.FileMode == BencodeNET.Torrents.TorrentFileMode.Single ?
                            s1 :
                            Helper.GetDirectoryNameDonntChangeDelimiter(s1)),
                        Paused = (
                            bencodeTorrent.FileMode == BencodeNET.Torrents.TorrentFileMode.Single ?
                            (!this.cbStartTorrent.Checked) : true)
                    };
                    var addedTorrentInfo = transmissionClient.TorrentAdd(addedTorrent);
                    Debug.Assert(addedTorrentInfo != null && addedTorrentInfo.ID != 0);

                    if (bencodeTorrent.FileMode == BencodeNET.Torrents.TorrentFileMode.Multi)
                    {
                        var result = transmissionClient.TorrentRenamePath(
                            addedTorrentInfo.ID,
                            bencodeTorrent.DisplayName,
                            Path.GetFileName(s1));
                        Debug.Assert(result != null && result.ID != 0);

                        if (this.cbStartTorrent.Checked)
                        {
                            transmissionClient.TorrentStartNow(new object[] { result.ID });
                        }
                    }
                }

                this.isAddTorrentSuccess = true;
                this.failedReason        = "";
            }
            catch (Exception ex)
            {
                this.failedReason = ex.Message;
            }
            finally
            {
                this.Close();
            }
        }
Esempio n. 23
0
 public Task <NewTorrentInfo> TorrentAddAsync(NewTorrent torrent)
 {
     return(mapper.Map <Task <NewTorrentInfo> >(client.TorrentAddAsync(mapper.Map <Transmission.API.RPC.Entity.NewTorrent>(torrent))));
 }
Esempio n. 24
0
        public static async Task AddTorrent(
            string torrentPath, BencodeNET.Torrents.Torrent bencodeTorrent,
            string saveFolder, bool skipHashCheck,
            bool startTorrent, string category, Config.BTClient btClient,
            bool isWindowsPath,
            Dictionary <string, string> actualToVirtualDic = null,
            Transmission.API.RPC.Client transmissionClient = null)
        {
            if (bencodeTorrent != null)
            {
                string strTitle =
                    bencodeTorrent.FileMode == BencodeNET.Torrents.TorrentFileMode.Single ?
                    Path.GetFileNameWithoutExtension(bencodeTorrent.DisplayName) :
                    bencodeTorrent.DisplayName;

                strTitle = Path.GetFileNameWithoutExtension(torrentPath) +
                           AddDotOrBlank(strTitle) +
                           strTitle;

                string strSaveFolderPath = saveFolder + (isWindowsPath ? "\\" : "/") + strTitle;

                if (Helper.CheckPath(ref strSaveFolderPath, isWindowsPath))
                {
                    if (skipHashCheck)
                    {
                        if (!Helper.CanSkipCheck(
                                bencodeTorrent,
                                Helper.GetVirtualPath(strSaveFolderPath, actualToVirtualDic), false))
                        {
                            throw new Exception("跳过哈希检测失败");
                        }
                    }

                    if (btClient == Config.BTClient.qBittorrent)
                    {
                        await QbtWebAPI.API.DownloadFromDisk(
                            new List <string>() { torrentPath }, strSaveFolderPath,
                            null, string.IsNullOrWhiteSpace(category)?null : category,
                            skipHashCheck, !startTorrent, false, strTitle, null, null, null, null);
                    }
                    else if (btClient == Config.BTClient.Transmission)
                    {
                        Debug.Assert(transmissionClient != null);
                        var addedTorrent = new NewTorrent
                        {
                            Metainfo          = Helper.GetTransmissionTorrentAddMetainfo(torrentPath),
                            DownloadDirectory = (
                                bencodeTorrent.FileMode == BencodeNET.Torrents.TorrentFileMode.Single ?
                                strSaveFolderPath :
                                Helper.GetDirectoryNameDonntChangeDelimiter(strSaveFolderPath)),
                            Paused = (
                                bencodeTorrent.FileMode == BencodeNET.Torrents.TorrentFileMode.Single ?
                                (!startTorrent) : true)
                        };
                        var addedTorrentInfo = transmissionClient.TorrentAdd(addedTorrent);
                        Debug.Assert(addedTorrentInfo != null && addedTorrentInfo.ID != 0);

                        if (bencodeTorrent.FileMode == BencodeNET.Torrents.TorrentFileMode.Multi)
                        {
                            var result = transmissionClient.TorrentRenamePath(
                                addedTorrentInfo.ID,
                                bencodeTorrent.DisplayName,
                                Path.GetFileName(strSaveFolderPath));
                            Debug.Assert(result != null && result.ID != 0);

                            if (startTorrent)
                            {
                                transmissionClient.TorrentStartNow(new object[] { result.ID });
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("保存路径包含无效字符");
                }
            }
        }