Beispiel #1
0
        public void DecodeTorrentWithString()
        {
            var dict = new BEncodedDictionary {
                { "info", (BEncodedString)"value" }
            };

            var result = BEncodedDictionary.DecodeTorrent(dict.Encode());

            Assert.IsTrue(Toolbox.ByteMatch(dict.Encode(), result.Encode()));
        }
        public void benDictionaryEncoding()
        {
            var data = Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");

            var dict = new BEncodedDictionary();
            var list = new BEncodedList();
            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            Assert.Equal(Encoding.UTF8.GetString(data), Encoding.UTF8.GetString(dict.Encode()));
            Assert.True(Toolbox.ByteMatch(data, dict.Encode()));
        }
Beispiel #3
0
        public void benDictionaryEncoding()
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");

            BEncodedDictionary dict = new BEncodedDictionary();
            BEncodedList list = new BEncodedList();
            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            Assert.AreEqual(System.Text.Encoding.UTF8.GetString(data), System.Text.Encoding.UTF8.GetString(dict.Encode()));
            Assert.IsTrue(Toolbox.ByteMatch(data, dict.Encode()));
        }
Beispiel #4
0
        public void DecodeTorrentWithDict()
        {
            var dict = new BEncodedDictionary {
                { "other", new BEncodedDictionary   {
                      { "test", new BEncodedString("value") }
                  } }
            };

            var result = BEncodedDictionary.DecodeTorrent(dict.Encode());

            Assert.IsTrue(Toolbox.ByteMatch(dict.Encode(), result.Encode()));
        }
Beispiel #5
0
        public void DecodeTorrentWithInfo()
        {
            var dict = new BEncodedDictionary();

            dict.Add("info", new BEncodedDictionary {
                { (BEncodedString)"test", (BEncodedString)"value" }
            });

            var result = BEncodedDictionary.DecodeTorrent(dict.Encode());

            Assert.IsTrue(Toolbox.ByteMatch(dict.Encode(), result.Encode()));
        }
Beispiel #6
0
        public void benDictionaryEncoding()
        {
            byte[] data = Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");

            BEncodedDictionary dict = new BEncodedDictionary();
            BEncodedList       list = new BEncodedList();

            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            Assert.AreEqual(Encoding.UTF8.GetString(data), Encoding.UTF8.GetString(dict.Encode()));
            Assert.IsTrue(Toolbox.ByteMatch(data, dict.Encode()));
        }
 public void DownloadMagnetLink_CachedTorrent ()
 {
     var metadataCacheDir = Path.Combine (Path.GetTempPath (), "magnetLinkDir");
     var filePath = Path.Combine (metadataCacheDir, $"{MagnetLink.InfoHash.ToHex()}.torrent");
     Directory.CreateDirectory (metadataCacheDir);
     try {
         File.WriteAllBytes (filePath, torrentInfo.Encode ());
         var provider = new StreamProvider (Engine, "testDir", MagnetLink, metadataCacheDir);
         Assert.IsNotNull (provider.Files);
     } finally {
         Directory.Delete (metadataCacheDir, true);
     }
 }
Beispiel #8
0
 private void WindowClosed(object sender, EventArgs e)
 {
     if (SettingsManager.SaveSession)
     {
         var resume     = new BEncodedDictionary();
         var serializer = new JsonSerializer();
         foreach (var torrent in Client.Torrents)
         {
             torrent.UpdateInfo();
             torrent.Stop();
             var start = DateTime.Now;
             while (torrent.Torrent.State != TorrentState.Stopped && torrent.Torrent.State != TorrentState.Error &&
                    (DateTime.Now - start).TotalSeconds < 2) // Time limit for trying to let it stop on its own
             {
                 Thread.Sleep(100);
             }
             using (var writer = new StreamWriter(Path.Combine(SettingsManager.TorrentCachePath,
                                                               Path.GetFileNameWithoutExtension(torrent.CacheFilePath) + ".info")))
                 serializer.Serialize(new JsonTextWriter(writer), torrent.TorrentInfo);
             // TODO: Notify users on error? The application is shutting down here, it wouldn't be particualry
             // easy to get information to the user
             if (torrent.Torrent.HashChecked)
             {
                 resume.Add(torrent.Torrent.InfoHash.ToHex(), torrent.Torrent.SaveFastResume().Encode());
             }
         }
         File.WriteAllBytes(SettingsManager.FastResumePath, resume.Encode());
     }
     SettingsManager.WindowWidth  = (int)Width;
     SettingsManager.WindowHeight = (int)Height;
     SaveSettings();
     Client.Shutdown();
 }
        public async Task Shutdown()
        {
            var fastResume = new BEncodedDictionary();

            for (var i = 0; i < torrentsManagers.Count; i++)
            {
                var stoppingTask = torrentsManagers[i].StopAsync();
                while (torrentsManagers[i].State != TorrentState.Stopped)
                {
                    Thread.Sleep(250);
                }
                await stoppingTask;

                if (torrentsManagers[i].HashChecked)
                {
                    fastResume.Add(torrentsManagers[i].Torrent.InfoHash.ToHex(), torrentsManagers[i].SaveFastResume().Encode());
                }
            }

            var nodes = await engine.DhtEngine.SaveNodesAsync();

            File.WriteAllBytes(pathsManager.DhtNodeFilePath, nodes);
            File.WriteAllBytes(pathsManager.FastResumeFilePath, fastResume.Encode());
            engine.Dispose();

            Thread.Sleep(2000);
        }
Beispiel #10
0
        private static async Task Shutdown()
        {
            BEncodedDictionary fastResume = new BEncodedDictionary();

            for (int i = 0; i < torrents.Count; i++)
            {
                var stoppingTask = torrents[i].StopAsync();
                while (torrents[i].State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", torrents[i].Torrent.Name, torrents[i].State);
                    Thread.Sleep(250);
                }
                await stoppingTask;

                if (torrents[i].HashChecked)
                {
                    fastResume.Add(torrents[i].Torrent.InfoHash.ToHex(), torrents[i].SaveFastResume().Encode());
                }
            }

            var nodes = await engine.DhtEngine.SaveNodesAsync();

            File.WriteAllBytes(dhtNodeFile, nodes);
            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();

            Thread.Sleep(2000);
        }
        private static async Task Shutdown()
        {
            BEncodedDictionary fastResume = new BEncodedDictionary();

            for (int i = 0; i < torrents.Count; i++)
            {
                var stoppingTask = torrents[i].StopAsync();
                while (torrents[i].State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", torrents[i].Torrent.Name, torrents[i].State);
                    Thread.Sleep(250);
                }
                await stoppingTask;

                if (torrents[i].HashChecked)
                {
                    fastResume.Add(torrents[i].Torrent.InfoHash.ToHex(), torrents[i].SaveFastResume().Encode());
                }
            }


            byte[] EncodedEvryNet = FileFunctions.ObjectToByteArray(MainProps.EvryNet).Result;
            File.WriteAllBytes(Environment.CurrentDirectory + "\\EvryNet", EncodedEvryNet);

            var nodes = await engine.DhtEngine.SaveNodesAsync();

            File.WriteAllBytes(dhtNodeFile, nodes);
            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();

            Thread.Sleep(2000);
        }
Beispiel #12
0
        private static void shutdown()
        {
            BEncodedDictionary fastResume = new BEncodedDictionary();

            for (int i = 0; i < torrents.Count; i++)
            {
                torrents[i].Stop();;
                while (torrents[i].State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", torrents[i].Torrent.Name, torrents[i].State);
                    Thread.Sleep(250);
                }

                fastResume.Add(torrents[i].Torrent.InfoHash.ToHex(), torrents[i].SaveFastResume().Encode());
            }

#if !DISABLE_DHT
            File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes());
#endif
            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();

            foreach (TraceListener lst in Debug.Listeners)
            {
                lst.Flush();
                lst.Close();
            }

            System.Threading.Thread.Sleep(2000);
        }
Beispiel #13
0
        public async Task Shutdown()
        {
            BEncodedDictionary fastResume = new BEncodedDictionary();

            for (int i = 0; i < TorrentInfoList.Count; i++)
            {
                TorrentInfoList[i].WriteToFile();
                //writeTorrentInfoToFile(TorrentInfoList[i]);
                var stoppingTask = TorrentInfoList[i].manager.StopAsync();
                while (TorrentInfoList[i].manager.State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", TorrentInfoList[i].manager.Torrent.Name, TorrentInfoList[i].manager.State);
                    Thread.Sleep(250);
                }
                await stoppingTask;

                if (TorrentInfoList[i].manager.HashChecked)
                {
                    fastResume.Add(TorrentInfoList[i].manager.Torrent.InfoHash.ToHex(), TorrentInfoList[i].manager.SaveFastResume().Encode());
                }
            }

            var nodes = await engine.DhtEngine.SaveNodesAsync();

            File.WriteAllBytes(dhtNodeFile, nodes);
            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();
            Thread.Sleep(200);
            System.Environment.Exit(0);
        }
Beispiel #14
0
        public FileResult Download(int id)
        {
            try
            {
                var repositorio = new DataRepository <BitShareData.Torrent>();
                var torrent     = (from item in repositorio.Fetch() where item.IdTorrent == id select item).First();

                byte[] buffer;
                using (var torrentStream = System.IO.File.Open(String.Format("{0}\\{1}", PastaTorrents, torrent.Arquivo), FileMode.Open))
                {
                    BEncodedDictionary torrentDict = (BEncodedDictionary)BEncodedValue.Decode(torrentStream);
                    BEncodedString     trackers    = (BEncodedString)torrentDict["announce"];
                    trackers = String.Format("http://tracker.bit-share.net/announce.aspx?passkey={0}", UsuarioLogado.PassKey);
                    torrentDict["announce"] = trackers;
                    buffer = torrentDict.Encode();
                }

                return(File(buffer, "application/x-bittorrent", torrent.Arquivo));
            }
            catch (Exception)
            {
                //TODO: tratar erro
                throw;
            }
        }
Beispiel #15
0
        void Stop()
        {
            File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes());

            BEncodedDictionary fastResume = new BEncodedDictionary();

            for (int i = 0; i < torrents.Count; i++)
            {
                torrents[i].Stop();
                try
                {
                    long count = 0;
                    while (torrents[i].State != TorrentState.Stopped && count < 5000)
                    {
                        Console.WriteLine("{0} is {1}", torrents[i].Torrent.Name, torrents[i].State);
                        count += 250;
                        Thread.Sleep(250);
                    }
                }
                catch
                {
                }

                fastResume.Add(torrents[i].Torrent.InfoHash.ToHex(), torrents[i].SaveFastResume().Encode());
            }

            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();
            System.Threading.Thread.Sleep(2000);
        }
        public async Task<byte[]> SaveStateAsync ()
        {
            await MainLoop;
            var state = new BEncodedDictionary {
                {nameof (Settings), Serializer.Serialize (Settings) },
            };

            state[nameof (Torrents)] = new BEncodedList (Torrents.Select (t => {
                var dict = new BEncodedDictionary {
                    { nameof (t.MagnetLink),  (BEncodedString) t.MagnetLink.ToV1String () },
                    { nameof(t.SavePath), (BEncodedString) t.SavePath },
                    { nameof(t.Settings), Serializer.Serialize (t.Settings) },
                    { "Streaming", (BEncodedString) (t.StreamProvider != null).ToString ()},
                };

                if (t.HasMetadata) {
                    dict[nameof (t.Files)] = new BEncodedList (t.Files.Select (file =>
                       new BEncodedDictionary {
                            { nameof(file.FullPath), (BEncodedString) file.FullPath },
                            { nameof(file.Path), (BEncodedString) file.Path },
                            { nameof(file.Priority), (BEncodedString) file.Priority.ToString () },
                       }
                    ));
                    dict[nameof (t.MetadataPath)] = (BEncodedString) t.MetadataPath;
                } else {
                }

                return dict;
            }));

            foreach (var v in Torrents)
                await v.MaybeWriteFastResumeAsync ();

            return state.Encode ();
        }
Beispiel #17
0
        public void Dispose()
        {
            logger.Info("Disposing torrents provider");
            var fastResume = new BEncodedDictionary();

            foreach (var t in _torrents)
            {
                t.Stop();

                try
                {
                    if (t.HasMetadata && t.HashChecked)
                    {
                        fastResume.Add(t.Torrent.InfoHash.ToHex(), t.SaveFastResume().Encode());
                    }
                }
                catch (Exception x)
                {
                    logger.Error("Unable to save the torrent {0}: {1}", t, x.Message);
                }
            }

            File.WriteAllBytes(TorrentDhtNodesPath, _engine.DhtEngine.SaveNodes());
            File.WriteAllBytes(TorrentFastResumePath, fastResume.Encode());
            _engine.Dispose();

            logger.Info("Torrents provider is disposed");
        }
Beispiel #18
0
        private static void Shutdown()
        {
            var fastResume = new BEncodedDictionary();

            foreach (var torrentManager in _torrents)
            {
                torrentManager.Stop();
                while (torrentManager.State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", torrentManager.Torrent.Name, torrentManager.State);
                    Thread.Sleep(250);
                }

                fastResume.Add(torrentManager.Torrent.InfoHash.ToHex(), torrentManager.SaveFastResume().Encode());
            }

#if !DISABLE_DHT
            File.WriteAllBytes(_dhtNodeFile, _engine.DhtEngine.SaveNodes());
#endif
            File.WriteAllBytes(_fastResumeFile, fastResume.Encode());
            _engine.Dispose();

            foreach (TraceListener lst in Debug.Listeners)
            {
                lst.Flush();
                lst.Close();
            }

            Thread.Sleep(2000);
        }
Beispiel #19
0
 /// <summary>
 /// Loads a torrent from the provided <see cref="BEncodedDictionary"/>
 /// </summary>
 /// <param name="dictionary">The BEncodedDictionary containing the torrent data</param>
 /// <returns></returns>
 public static Torrent Load(BEncodedDictionary dictionary)
 {
     using (MemoryPool.Default.Rent(dictionary.LengthInBytes(), out Memory <byte> buffer)) {
         dictionary.Encode(buffer.Span);
         return(Load(buffer.Span));
     }
 }
Beispiel #20
0
        public async Task CreateAsync(ITorrentFileSource fileSource, string savePath, CancellationToken token)
        {
            Check.SavePath(savePath);

            BEncodedDictionary data = await CreateAsync(fileSource, token);

            File.WriteAllBytes(savePath, data.Encode());
        }
Beispiel #21
0
        public async Task CreateAsync(ITorrentFileSource fileSource, Stream stream, CancellationToken token)
        {
            Check.Stream(stream);

            BEncodedDictionary dictionary = await CreateAsync(fileSource, token);

            byte[] data = dictionary.Encode();
            stream.Write(data, 0, data.Length);
        }
 private async Task SaveFastResume()
 {
     var fastResume = new BEncodedDictionary
     {
         { _manager.Torrent.InfoHash.ToHex(), _manager.SaveFastResume().Encode() }
     };
     // TODO: read from file
     await File.WriteAllBytesAsync(FastResumeFile, fastResume.Encode());
 }
Beispiel #23
0
        public static byte[] GetBytesFromFile(string PathToFile)
        {
            TorrentCreator TC = new TorrentCreator();

            TC.Private = false;
            ITorrentFileSource filePath = new TorrentFileSource(PathToFile);
            BEncodedDictionary bed      = TC.Create(filePath);

            return(bed.Encode());
        }
Beispiel #24
0
        public void benDictionaryStackedTest()
        {
            string benString = "d4:testd5:testsli12345ei12345ee2:tod3:tomi12345eeee";

            byte[]             data    = System.Text.Encoding.UTF8.GetBytes(benString);
            BEncodedDictionary dict    = (BEncodedDictionary)BEncodedValue.Decode(data);
            string             decoded = System.Text.Encoding.UTF8.GetString(dict.Encode());

            Assert.AreEqual(benString, decoded);
        }
        public override int Encode(byte[] buffer, int offset)
        {
            int written = offset;

            written += Write(buffer, offset, ByteLength - 4);
            written += Write(buffer, written, ExtensionMessage.MessageId);
            written += Write(buffer, written, ExtensionId);
            written += peerDict.Encode(buffer, written);

            return(CheckWritten(written - offset));
        }
 public void benDictionaryEncodingBuffered()
 {
     var data = Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");
     var dict = new BEncodedDictionary();
     var list = new BEncodedList();
     list.Add(new BEncodedString("a"));
     list.Add(new BEncodedString("b"));
     dict.Add("spam", list);
     var result = new byte[dict.LengthInBytes()];
     dict.Encode(result, 0);
     Assert.True(Toolbox.ByteMatch(data, result));
 }
        public override int Encode(byte[] buffer, int offset)
        {
            int written             = offset;
            BEncodedDictionary dict = Create();

            written += Write(buffer, written, dict.LengthInBytes() + 1 + 1);
            written += Write(buffer, written, MessageId);
            written += Write(buffer, written, Support.MessageId);
            written += dict.Encode(buffer, written);

            return(written - offset);
        }
Beispiel #28
0
        public void benDictionaryEncodingBuffered()
        {
            byte[]             data = System.Text.Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");
            BEncodedDictionary dict = new BEncodedDictionary();
            BEncodedList       list = new BEncodedList();

            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            byte[] result = new byte[dict.LengthInBytes()];
            dict.Encode(result, 0);
            Assert.IsTrue(Toolbox.ByteMatch(data, result));
        }
Beispiel #29
0
        /// <summary>
        /// 生成一个 GotPeer 消息。
        /// </summary>
        /// <param name="localEP">消息源的端点。</param>
        /// <param name="infoHash">用户所持有的 InfoHash。</param>
        /// <param name="bitTorrentClientPort">用户所监听的端口(即 BitTorrent 客户端的监听端口)。</param>
        /// <returns>创建的 GotPeer 消息。</returns>
        public static KMessage GotPeer(KEndPoint localEP, InfoHash infoHash, ushort bitTorrentClientPort)
        {
            var message = KMessage.CreateEmptyMessage();

            message.Header.Code           = KMessageCode.GotPeer;
            message.Header.SourceEndPoint = localEP;
            message.Header.MessageID      = GetMessageHash();

            BEncodedDictionary data = new BEncodedDictionary();

            data.Add("infohash", infoHash.ToByteArray());
            data.Add("bt client port", bitTorrentClientPort);
            message.Content = KMessageContent.FromByteArray(data.Encode());
            return(message);
        }
Beispiel #30
0
        /// <summary>
        /// 生成一个 ClientEnterNetwork 消息。
        /// </summary>
        /// <param name="localEP">消息源的端点。</param>
        /// <param name="realPort">非零表示这是接入点要连接接入点,该端口是本机正在监听的端口;零表示只是普通用户连接接入点。</param>
        /// <returns>创建的 ClientEnterNetwork 消息。</returns>
        public static KMessage ClientEnterNetwork(KEndPoint localEP, ushort realPort)
        {
            var message = KMessage.CreateEmptyMessage();

            message.Header.Code           = KMessageCode.ClientEnterNetwork;
            message.Header.SourceEndPoint = localEP;
            message.Header.MessageID      = GetMessageHash();

            BEncodedDictionary data = new BEncodedDictionary();

            data.Add("message handled", 0);
            data.Add("real port", realPort);
            message.Content = KMessageContent.FromByteArray(data.Encode());
            return(message);
        }
Beispiel #31
0
        public async Task <TorrentManager> AddAsync(Torrent torrent, string saveDirectory, TorrentSettings settings)
        {
            await MainLoop.SwitchThread();

            var metadata = new BEncodedDictionary {
                { "info", BEncodedValue.Decode(torrent.InfoMetadata) }
            };

            var metadataCachePath = Settings.GetMetadataPath(torrent.InfoHash);

            Directory.CreateDirectory(Path.GetDirectoryName(metadataCachePath));
            File.WriteAllBytes(metadataCachePath, metadata.Encode());

            return(await AddAsync(null, torrent, saveDirectory, settings));
        }
 private void BeginCreateCb(IAsyncResult result)
 {
     logger.Debug("Torrent creation finished");
     progressDialog.Destroy();
     try{
         BEncodedDictionary dict = creator.EndCreate(result);
         System.IO.File.WriteAllBytes(savePathChooser.Filename, dict.Encode());
         if (startSeedingCheckBox.Active)
         {
             torrentController.addTorrent(savePathChooser.Filename, startSeedingCheckBox.Active);
         }
         logger.Debug("Torrent file created");
     }catch (Exception e) {
         logger.Error("Failed to create torrent - " + e.Message);
     }
 }
Beispiel #33
0
        public void SaveFastResume()
        {
            BEncodedDictionary dict = new BEncodedDictionary();

            foreach (TorrentManager manager in items)
            {
                dict.Add(manager.Torrent.InfoHash, manager.SaveFastResume().Encode());
            }
            try
            {
                File.WriteAllBytes(TorrentCurses.fast_resume, dict.Encode());
            }
            catch
            {
            }
        }
Beispiel #34
0
        private static void shutdown()
        {
            BEncodedDictionary fastResume = new BEncodedDictionary();
            for (int i = 0; i < torrents.Count; i++)
            {
                torrents[i].Stop(); ;
                while (torrents[i].State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", torrents[i].Torrent.Name, torrents[i].State);
                    Thread.Sleep(250);
                }

                fastResume.Add(torrents[i].Torrent.InfoHash.ToHex (), torrents[i].SaveFastResume().Encode());
            }

            #if !DISABLE_DHT
            File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes());
            #endif
            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();

            foreach (TraceListener lst in Debug.Listeners)
            {
                lst.Flush();
                lst.Close();
            }

            System.Threading.Thread.Sleep(2000);
        }
Beispiel #35
0
		public void SaveFastResume ()
		{
			
			BEncodedDictionary dict = new BEncodedDictionary();
			foreach (TorrentManager manager in items)
				dict.Add (manager.Torrent.InfoHash, manager.SaveFastResume ().Encode ());
			try
			{
				File.WriteAllBytes (TorrentCurses.fast_resume, dict.Encode ());
			}
			catch
			{
			}
		}
        protected override async void HandleLtMetadataMessage(PeerId id, LTMetadata message)
        {
            base.HandleLtMetadataMessage(id, message);

            switch (message.MetadataMessageType)
            {
                case LTMetadata.eMessageType.Data:
                    if (Stream == null)
                        throw new Exception("Need extention handshake before ut_metadata message.");

                    Stream.Seek(message.Piece*LTMetadata.BlockSize, SeekOrigin.Begin);
                    Stream.Write(message.MetadataPiece, 0, message.MetadataPiece.Length);
                    _bitField[message.Piece] = true;
                    if (_bitField.AllTrue)
                    {
                        Stream.Position = 0;
                        var hash = SHA1Helper.ComputeHash(Stream.ToArray());

                        if (!Manager.InfoHash.Equals(hash))
                        {
                            _bitField.SetAll(false);
                        }
                        else
                        {
                            Common.Torrent t;
                            Stream.Position = 0;
                            var dict = new BEncodedDictionary {{"info", BEncodedValue.Decode(Stream)}};
                            // FIXME: Add the trackers too
                            if (Common.Torrent.TryLoad(dict.Encode(), out t))
                            {
                                try
                                {
                                    var file = await _saveFolder.CreateFileAsync(Manager.InfoHash.ToHex() + ".torrent",
                                        CreationCollisionOption.ReplaceExisting);
                                    File.WriteAllBytes(file.Path, dict.Encode());
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine("*METADATA EXCEPTION* - Can not write in {0} : {1}", _saveFolder,
                                        ex);
                                    Manager.Error = new Error(Reason.WriteFailure, ex);
                                    Manager.Mode = new ErrorMode(Manager);
                                    return;
                                }
                                t.TorrentPath = _saveFolder.Path;
                                Manager.Torrent = t;
                                SwitchToRegular();
                            }
                            else
                            {
                                _bitField.SetAll(false);
                            }
                        }
                    }
                    //Double test because we can change the bitfield in the other block
                    if (!_bitField.AllTrue)
                    {
                        RequestNextNeededPiece(id);
                    }
                    break;
                case LTMetadata.eMessageType.Reject:
                    //TODO
                    //Think to what we do in this situation
                    //for moment nothing ;)
                    //reject or flood?
                    break;
                case LTMetadata.eMessageType.Request: //ever done in base class but needed to avoid default
                    break;
                default:
                    throw new MessageException(string.Format("Invalid messagetype in LTMetadata: {0}",
                        message.MetadataMessageType));
            }
        }
Beispiel #37
0
 private void WindowClosed(object sender, EventArgs e)
 {
     if (SettingsManager.SaveSession)
     {
         var resume = new BEncodedDictionary();
         var serializer = new JsonSerializer();
         foreach (var torrent in Client.Torrents)
         {
             torrent.Torrent.Stop();
             var start = DateTime.Now;
             while (torrent.Torrent.State != TorrentState.Stopped && torrent.Torrent.State != TorrentState.Error &&
                 (DateTime.Now - start).TotalSeconds < 2) // Time limit for trying to let it stop on its own
                 Thread.Sleep(100);
             torrent.UpdateInfo();
             using (var writer = new StreamWriter(Path.Combine(SettingsManager.TorrentCachePath,
                 Path.GetFileNameWithoutExtension(torrent.CacheFilePath) + ".info")))
                 serializer.Serialize(new JsonTextWriter(writer), torrent.TorrentInfo);
             // TODO: Notify users on error? The application is shutting down here, it wouldn't be particualry
             // easy to get information to the user
             resume.Add(torrent.Torrent.InfoHash.ToHex(), torrent.Torrent.SaveFastResume().Encode());
         }
         File.WriteAllBytes(SettingsManager.FastResumePath, resume.Encode());
     }
     SettingsManager.WindowWidth = (int)Width;
     SettingsManager.WindowHeight = (int)Height;
     SaveSettings();
     Client.Shutdown();
 }
Beispiel #38
0
        void Stop()
        {
            File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes());

            BEncodedDictionary fastResume = new BEncodedDictionary();
            for (int i = 0; i < torrents.Count; i++)
            {
                torrents[i].Stop();
                try
                {
                    long count = 0;
                    while (torrents[i].State != TorrentState.Stopped && count < 5000)
                    {
                        Console.WriteLine("{0} is {1}", torrents[i].Torrent.Name, torrents[i].State);
                        count += 250;
                        Thread.Sleep(250);
                    }
                }
                catch
                {
                }

                fastResume.Add(torrents[i].Torrent.InfoHash.ToHex(), torrents[i].SaveFastResume().Encode());
            }

            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();
            System.Threading.Thread.Sleep(2000);
        }
Beispiel #39
0
 private void WindowClosed(object sender, EventArgs e)
 {
     var resume = new BEncodedDictionary();
     foreach (var torrent in Client.Torrents)
     {
         torrent.Torrent.Stop();
         while (torrent.Torrent.State != TorrentState.Stopped && torrent.Torrent.State != TorrentState.Error)
             Thread.Sleep(100);
         // TODO: Notify users on error? The application is shutting down here, it wouldn't be particualry
         // easy to get information to the user
         resume.Add(torrent.Torrent.InfoHash.ToHex(), torrent.Torrent.SaveFastResume().Encode());
     }
     File.WriteAllBytes(SettingsManager.FastResumePath, resume.Encode());
     Client.Shutdown();
 }
Beispiel #40
0
        private static void shutdown()
        {
            BEncodedDictionary fastResume = new BEncodedDictionary();
            for (int i = 0; i < torrents.Count; i++)
            {
                WaitHandle handle = torrents[i].Stop(); ;
                while (!handle.WaitOne(10, true))
                    Console.WriteLine(handle.ToString());

                Console.WriteLine(handle.ToString());
                fastResume.Add(torrents[i].Torrent.InfoHash, torrents[i].SaveFastResume().Encode());
            }

            File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes());
            File.WriteAllBytes(fastResumeFile, fastResume.Encode());
            engine.Dispose();

            foreach (TraceListener lst in Debug.Listeners)
            {
                lst.Flush();
                lst.Close();
            }

            System.Threading.Thread.Sleep(2000);
        }
        /// <summary>
        /// Shutdowns torrent client and saves unfinished torrents to resume file
        /// This method must be called when Exit button is pressed!
        /// </summary>
        public void Shutdown()
        {
            var fastResume = new BEncodedDictionary();

            foreach (var torrent in _torrents)
            {
                torrent.Stop();

                while (torrent.State != TorrentState.Stopped)
                {
                    Thread.Sleep(250);
                }

                fastResume.Add(torrent.Torrent.InfoHash.ToHex(), torrent.SaveFastResume().Encode());
            }

            File.WriteAllBytes(FastResumeFile, fastResume.Encode());
            _engine.Dispose();

            Thread.Sleep(2000);
        }
        protected override void HandleLtMetadataMessage(PeerId id, LTMetadata message)
        {
            base.HandleLtMetadataMessage(id, message);

            switch (message.MetadataMessageType)
            {
                case LTMetadata.eMessageType.Data:
                    if (stream == null)
                        throw new Exception("Need extention handshake before ut_metadata message.");

                    stream.Seek(message.Piece * LTMetadata.BlockSize, SeekOrigin.Begin);
                    stream.Write(message.MetadataPiece, 0, message.MetadataPiece.Length);
                    bitField[message.Piece] = true;
                    if (bitField.AllTrue)
                    {
                        byte[] hash;
                        stream.Position = 0;
                        using (SHA1 hasher = HashAlgoFactory.Create<SHA1>())
                            hash = hasher.ComputeHash(stream);

                        if (!Manager.InfoHash.Equals (hash))
                        {
                            bitField.SetAll(false);
                        }
                        else
                        {
                            Torrent t;
                            stream.Position = 0;
                            BEncodedDictionary dict = new BEncodedDictionary();
                            dict.Add ("info", BEncodedValue.Decode(stream));
                            // FIXME: Add the trackers too
                            if (Torrent.TryLoad(dict.Encode (), out t))
                            {
                                try
                                {
                                    if (Directory.Exists(savePath))
                                        savePath = Path.Combine (savePath, Manager.InfoHash.ToHex() + ".torrent");
                                    File.WriteAllBytes(savePath, dict.Encode ());
                                }
                                catch (Exception ex)
                                {
                                    Logger.Log(null, "*METADATA EXCEPTION* - Can not write in {0} : {1}", savePath, ex);
                                    Manager.Error = new Error (Reason.WriteFailure, ex);
                                    Manager.Mode = new ErrorMode(Manager);
                                    return;
                                }
                                t.TorrentPath = savePath;
                                Manager.Torrent = t;
                                SwitchToRegular();
                            }
                            else
                            {
                                bitField.SetAll(false);
                            }
                        }
                    }
                    //Double test because we can change the bitfield in the other block
                    if (!bitField.AllTrue)
                    {
                        RequestNextNeededPiece(id);
                    }
                    break;
                case LTMetadata.eMessageType.Reject:
                    //TODO
                    //Think to what we do in this situation
                    //for moment nothing ;)
                    //reject or flood?
                    break;
                case LTMetadata.eMessageType.Request://ever done in base class but needed to avoid default
                    break;
                default:
                    throw new MessageException(string.Format("Invalid messagetype in LTMetadata: {0}", message.MetadataMessageType));
            }
        }
Beispiel #43
0
        private static void Shutdown()
        {
            var fastResume = new BEncodedDictionary();
            foreach (var torrentManager in torrents)
            {
                torrentManager.Stop();
                while (torrentManager.State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", torrentManager.Torrent.Name, torrentManager.State);
                    Thread.Sleep(250);
                }

                fastResume.Add(torrentManager.Torrent.InfoHash.ToHex (), torrentManager.SaveFastResume().Encode());
            }

            #if !DISABLE_DHT
            File.WriteAllBytes(_dhtNodeFile, _engine.DhtEngine.SaveNodes());
            #endif
            File.WriteAllBytes(_fastResumeFile, fastResume.Encode());
            _engine.Dispose();

            foreach (TraceListener lst in Debug.Listeners)
            {
                lst.Flush();
                lst.Close();
            }

            Thread.Sleep(2000);
        }