Inheritance: MonoBehaviour
 internal ListenManager(ClientEngine engine)
 {
     Engine = engine;
     Listeners = new MonoTorrentCollection<PeerListener>();
     _endCheckEncryptionCallback = ClientEngine.MainLoop.Wrap(EndCheckEncryption);
     _handshakeReceivedCallback =
         (a, b, c) => ClientEngine.MainLoop.Queue(() => OnPeerHandshakeReceived(a, b, c));
 }
        public CriticalExceptionEventArgs(Exception ex, ClientEngine engine)
        {
            if (ex == null)
                throw new ArgumentNullException(nameof(ex));
            if (engine == null)
                throw new ArgumentNullException(nameof(engine));

            Engine = engine;
            Exception = ex;
        }
Exemple #3
0
        }                                               // This is a subclass of TraceListener which remembers the last 20 statements sent to it

        public StandardDownloader(ClientEngine engine)
        {
            Engine   = engine;
            Listener = new Top10Listener(10);
        }
Exemple #4
0
 public TorrentProvider(EngineSettings defaultSettings = null)
 {
     this.defaultSettings = defaultSettings;
     engine = new ClientEngine(defaultSettings);
 }
Exemple #5
0
        private static async Task StartEngine()
        {
            int     port;
            Torrent torrent = null;

            // Ask the user what port they want to use for incoming connections
            Console.Write($"{Environment.NewLine}Choose a listen port: ");
            while (!Int32.TryParse(Console.ReadLine(), out port))
            {
            }

            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings {
                SavePath   = downloadsPath,
                ListenPort = port
            };

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;

            // Create the default settings which a torrent will have.
            TorrentSettings torrentDefaults = new TorrentSettings();

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);

            byte[] nodes = Array.Empty <byte> ();
            try {
                nodes = File.ReadAllBytes(dhtNodeFile);
            } catch {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtEngine dht = new DhtEngine(new IPEndPoint(IPAddress.Any, port));
            await engine.RegisterDhtAsync(dht);

            // This starts the Dht engine but does not wait for the full initialization to
            // complete. This is because it can take up to 2 minutes to bootstrap, depending
            // on how many nodes time out when they are contacted.
            await engine.DhtEngine.StartAsync(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            BEncodedDictionary fastResume;

            try {
                fastResume = BEncodedValue.Decode <BEncodedDictionary> (File.ReadAllBytes(fastResumeFile));
            } catch {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
                {
                    try {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = await Torrent.LoadAsync(file);

                        Console.WriteLine(torrent.InfoHash.ToString());
                    } catch (Exception e) {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    {
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                    }
                    await engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += manager_PeersFound;

                    var streamProvider = new StreamProvider(manager);
                    var stream         = await streamProvider.CreateStreamAsync(manager.Torrent.Files.First());

                    Core.Initialize();

                    libvlc      = new LibVLC();
                    mediaPlayer = new MediaPlayer(libvlc)
                    {
                        Media = new Media(libvlc, stream)
                    };
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                manager.PeerConnected += (o, e) => {
                    lock (listener)
                        listener.WriteLine($"Connection succeeded: {e.Peer.Uri}");
                };
                manager.ConnectionAttemptFailed += (o, e) => {
                    lock (listener)
                        listener.WriteLine(
                            $"Connection failed: {e.Peer.ConnectionUri} - {e.Reason} - {e.Peer.AllowedEncryption}");
                };
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine($"Piece Hashed: {e.PieceIndex} - {(e.HashPassed ? "Pass" : "Fail")}");
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                    lock (listener)
                        listener.WriteLine($"OldState: {e.OldState} NewState: {e.NewState}");
                };

                // Every time the tracker's state changes, this is fired
                manager.TrackerManager.AnnounceComplete += (sender, e) => {
                    listener.WriteLine($"{e.Successful}: {e.Tracker}");
                };

                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                await manager.StartAsync();
            }

            mediaPlayer.Play();

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(m => m.State != TorrentState.Stopped);

                    AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    AppendFormat(sb, "Total Upload Rate:   {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0);
                    AppendFormat(sb, "Disk Read Rate:      {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0);
                    AppendFormat(sb, "Disk Write Rate:     {0:0.00} kB/s", engine.DiskManager.WriteRate / 1024.0);
                    AppendFormat(sb, "Total Read:         {0:0.00} kB", engine.DiskManager.TotalRead / 1024.0);
                    AppendFormat(sb, "Total Written:      {0:0.00} kB", engine.DiskManager.TotalWritten / 1024.0);
                    AppendFormat(sb, "Open Connections:    {0}", engine.ConnectionManager.OpenConnections);

                    foreach (TorrentManager manager in torrents)
                    {
                        AppendSeparator(sb);
                        AppendFormat(sb, "State:           {0}", manager.State);
                        AppendFormat(sb, "Name:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                        AppendFormat(sb, "Progress:           {0:0.00}", manager.Progress);
                        AppendFormat(sb, "Download Speed:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                        AppendFormat(sb, "Upload Speed:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                        AppendFormat(sb, "Total Downloaded:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                        AppendFormat(sb, "Total Uploaded:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                        AppendFormat(sb, "Tracker Status");
                        foreach (var tier in manager.TrackerManager.Tiers)
                        {
                            AppendFormat(sb, $"\t{tier.ActiveTracker} : Announce Succeeded: {tier.LastAnnounceSucceeded}. Scrape Succeeded: {tier.LastScrapSucceeded}.");
                        }
                        if (manager.PieceManager != null)
                        {
                            AppendFormat(sb, "Current Requests:   {0}", await manager.PieceManager.CurrentRequestCountAsync());
                        }

                        foreach (PeerId p in await manager.GetPeersAsync())
                        {
                            AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Uri,
                                         p.Monitor.DownloadSpeed / 1024.0,
                                         p.AmRequestingPiecesCount,
                                         p.Monitor.UploadSpeed / 1024.0);
                        }

                        AppendFormat(sb, "", null);
                        if (manager.Torrent != null)
                        {
                            foreach (TorrentFile file in manager.Torrent.Files)
                            {
                                AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete);
                            }
                        }
                    }
                    Console.Clear();
                    Console.WriteLine(sb.ToString());
                    listener.ExportTo(Console.Out);
                }

                Thread.Sleep(500);
            }
        }
Exemple #6
0
        public static void Initialize()
        {
            if (!Steamworks.Load())
            {
                throw new SteamException("Unable to load steamclient library.");
            }

            try
            {
                ClientEngine = Steamworks.CreateInterface <IClientEngine>("CLIENTENGINE_INTERFACE_VERSION001");
            }
            catch (Exception ex)
            {
                throw new SteamException("Unable to get IClientEngine interface.", ex);
            }

            try
            {
                SteamClient = Steamworks.CreateInterface <ISteamClient009>("SteamClient009");
            }
            catch (Exception ex)
            {
                throw new SteamException("Unable to get ISteamClient interface.", ex);
            }

            if (ClientEngine == null)
            {
                throw new SteamException("Unable to get IClientEngine interface.");
            }

            Pipe = ClientEngine.CreateSteamPipe();

            if (Pipe == 0)
            {
                throw new SteamException("Unable to aquire steam pipe.");
            }

            User = ClientEngine.ConnectToGlobalUser(Pipe);

            if (User == 0)
            {
                throw new SteamException("Unable to connect to global user.");
            }


            ClientFriends = GetInterface <IClientFriends>(
                () => { return(ClientEngine.GetIClientFriends(User, Pipe, "CLIENTFRIENDS_INTERFACE_VERSION001")); },
                "Unable to get IClientFriends interface."
                );

            SteamUser = GetInterface <ISteamUser014>(
                () => { return(SteamClient.GetISteamUser(User, Pipe, "SteamUser014")); },
                "Unable to get ISteamUser interface."
                );

            SteamUtils = GetInterface <ISteamUtils005>(
                () => { return(SteamClient.GetISteamUtils(Pipe, "SteamUtils005")); },
                "Unable to get ISteamUtils interface."
                );

            OnStateChange = new Callback <PersonaStateChange_t>(PersonaStateChange_t.k_iCallback);
        }
Exemple #7
0
        static async Task MainAsync(string[] args, CancellationToken token)
        {
            // Give an example of how settings can be modified for the engine.
            var settingBuilder = new EngineSettingsBuilder {
                // Allow the engine to automatically forward ports using upnp/nat-pmp (if a compatible router is available)
                AllowPortForwarding = true,

                // Automatically save a cache of the DHT table when all torrents are stopped.
                AutoSaveLoadDhtCache = true,

                // Automatically save 'FastResume' data when TorrentManager.StopAsync is invoked, automatically load it
                // before hash checking the torrent. Fast Resume data will be loaded as part of 'engine.AddAsync' if
                // torrent metadata is available. Otherwise, if a magnetlink is used to download a torrent, fast resume
                // data will be loaded after the metadata has been downloaded.
                AutoSaveLoadFastResume = true,

                // If a MagnetLink is used to download a torrent, the engine will try to load a copy of the metadata
                // it's cache directory. Otherwise the metadata will be downloaded and stored in the cache directory
                // so it can be reloaded later.
                AutoSaveLoadMagnetLinkMetadata = true,

                // Use a fixed port to accept incoming connections from other peers for testing purposes. Production usages should use a random port, 0, if possible.
                ListenEndPoint = new IPEndPoint(IPAddress.Any, 55123),

                // Use a fixed port for DHT communications for testing purposes. Production usages should use a random port, 0, if possible.
                DhtEndPoint = new IPEndPoint(IPAddress.Any, 55123),
            };

            using var engine = new ClientEngine(settingBuilder.ToSettings());

            Task task;

            if (args.Length == 1 && args[0] == "--vlc")
            {
                task = new VLCStream(engine).StreamAsync(InfoHash.FromHex("AEE0F0082CC2F449412C1DD8AF4C58D9AAEE4B5C"), token);
            }
            else if (args.Length == 1 && MagnetLink.TryParse(args[0], out MagnetLink link))
            {
                task = new MagnetLinkStreaming(engine).DownloadAsync(link, token);
            }
            else
            {
                task = new StandardDownloader(engine).DownloadAsync(token);
            }

            if (engine.Settings.AllowPortForwarding)
            {
                Console.WriteLine("uPnP or NAT-PMP port mappings will be created for any ports needed by MonoTorrent");
            }

            try {
                await task;
            } catch (OperationCanceledException) {
            }

            foreach (var manager in engine.Torrents)
            {
                var stoppingTask = manager.StopAsync();
                while (manager.State != TorrentState.Stopped)
                {
                    Console.WriteLine("{0} is {1}", manager.Torrent.Name, manager.State);
                    await Task.WhenAll(stoppingTask, Task.Delay(250));
                }
                await stoppingTask;
                if (engine.Settings.AutoSaveLoadFastResume)
                {
                    Console.WriteLine($"FastResume data for {manager.Torrent?.Name ?? manager.InfoHash.ToHex ()} has been written to disk.");
                }
            }

            if (engine.Settings.AutoSaveLoadDhtCache)
            {
                Console.WriteLine($"DHT cache has been written to disk.");
            }

            if (engine.Settings.AllowPortForwarding)
            {
                Console.WriteLine("uPnP and NAT-PMP port mappings have been removed");
            }
        }
Exemple #8
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            ClassEditControl scout = new ClassEditControl("Scout");

            scout.ClassImage = Properties.Resources.scout;

            // heavy
            ClassEditControl heavy = new ClassEditControl("Heavy");

            heavy.ClassImage = Properties.Resources.heavy;

            // medic
            ClassEditControl medic = new ClassEditControl("Medic");

            medic.ClassImage = Properties.Resources.medic;

            // soldier
            ClassEditControl soldier = new ClassEditControl("Soldier");

            soldier.ClassImage = Properties.Resources.soldier;

            // engi
            ClassEditControl engineer = new ClassEditControl("Engineer");

            engineer.ClassImage = Properties.Resources.engineer;

            // spy
            ClassEditControl spy = new ClassEditControl("Spy");

            spy.ClassImage = Properties.Resources.spy;

            // sniper
            ClassEditControl sniper = new ClassEditControl("Sniper");

            sniper.ClassImage = Properties.Resources.sniper;

            // demo
            ClassEditControl demo = new ClassEditControl("Demoman");

            demo.ClassImage = Properties.Resources.demoman;

            // pyro
            ClassEditControl pyro = new ClassEditControl("Pyro");

            pyro.ClassImage = Properties.Resources.pyro;

            flowLayoutPanel1.Controls.Add(scout);
            flowLayoutPanel1.Controls.Add(heavy);
            flowLayoutPanel1.Controls.Add(medic);
            flowLayoutPanel1.Controls.Add(soldier);
            flowLayoutPanel1.Controls.Add(engineer);
            flowLayoutPanel1.Controls.Add(spy);
            flowLayoutPanel1.Controls.Add(sniper);
            flowLayoutPanel1.Controls.Add(demo);
            flowLayoutPanel1.Controls.Add(pyro);


            toolStripStatusLabel1.Text = "Initializing steamworks...";

            try
            {
                int error;
                client = ( SteamClient008 )Steamworks.CreateInterface(SteamClient008.InterfaceVersion, out error);

                if (client == null)
                {
                    throw new InvalidOperationException("Unable to create ISteamClient.");
                }

                pipe = client.CreateSteamPipe();
                if (pipe == SteamPipeHandle.InvalidHandle)
                {
                    throw new InvalidOperationException("Unable to create steam pipe.");
                }

                user = client.ConnectToGlobalUser(pipe);

                clientEngine = ( ClientEngine )Steamworks.CreateInterface(ClientEngine.InterfaceVersion, out error);

                if (clientEngine == null)
                {
                    throw new InvalidOperationException("Unable to create IClientEngine.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Unable to initialize steamworks. Please ensure the following:\n\n" +
                                " * steamclient.dll, tier0_s.dll, vstdlib_s.dll, are present in the running directory\n" +
                                " * You are logged into steam and are online.\n\nAdditional Details: " + ex.Message, "TF2 Stats Suite"
                                );

                this.Close();
                return;
            }

            toolStripStatusLabel1.Text = "Loading stats...";

            statsAcc = new StatsAccessor(client, pipe, user, 440);

            steamUser   = ( SteamUser012 )client.GetISteamUser(user, pipe, SteamUser012.InterfaceVersion);
            clientUtils = ( ClientUtils )clientEngine.GetIClientUtils(pipe, ClientUtils.InterfaceVersion);

            clientUtils.SetAppIDForCurrentPipe(new AppID(440));

            foreach (ClassEditControl cec in flowLayoutPanel1.Controls)
            {
                toolStripStatusLabel1.Text = "Loading stats for '" + cec.Class + "'...";
                cec.LoadStats(statsAcc);
                Application.DoEvents();
            }

            toolStripStatusLabel1.Text = "Stats fully loaded!";
        }
Exemple #9
0
	static void InitMonoTorrent ()
	{
		queue = new ArrayList ();
		engine_settings = new EngineSettings (config.DownloadDir, config.ListenPort);
		torrent_settings = new TorrentSettings (config.UploadSlots, config.MaxConnections,
							(int) config.UploadSpeed, (int) config.DownloadSpeed);
		
		engine = new ClientEngine (engine_settings);

		// Our store
		torrent_list = new TorrentList ();
		foreach (TorrentDesc td in config.Torrents){
			if (File.Exists (td.Filename)){
				torrent_list.Add (td.Filename);
			}
		}
	}
 public MagnetLinkStreaming(ClientEngine engine)
 {
     Engine = engine;
 }
Exemple #11
0
 public TorrentStreamService(ClientEngine engine)
 {
     _engine = engine;
 }
Exemple #12
0
        /// <summary>
        /// Check the velocity devices in the Devices.ini are available or not.
        /// If some devices are unavailable, the Devices.ini should be changed to give
        /// tester all available devices.
        /// </summary>
        /// <returns>list</returns>
        public static List <String> CheckVelocityDeviceAvailable()
        {
            // There are all devices in Device.ini.
            List <string> notAvailable = new List <string>();
            IDictionary <string, string> AllDeviceInfo = new Dictionary <string, string> ();
            IDictionary <string, string> VelDeviceInfo = new Dictionary <string, string> ();

            AllDeviceInfo = AppConfigOper.mainOp.DevConfigs;

            foreach (string key in AllDeviceInfo.Keys)
            {
                if (key.ToUpper().StartsWith("VELOCITY"))
                {
                    VelDeviceInfo.Add(key, AllDeviceInfo[key]);
                }
            }

            foreach (KeyValuePair <string, string> device in VelDeviceInfo)
            {
                Console.WriteLine("VelDeviceInfo: key={0},value={1}", device.Key, device.Value);
            }



            string      NformPath = "";
            RegistryKey Key;

            Key = Registry.LocalMachine;
            //Nform in Register table
            // The path is based on your pc
            //  RegistryKey myreg = Key.OpenSubKey("software\\Liebert\\Nform");
            RegistryKey myreg = Key.OpenSubKey("software\\Wow6432Node\\Liebert\\Nform");

            NformPath = myreg.GetValue("InstallDir").ToString();
            myreg.Close();
            Console.WriteLine("NformPath:" + NformPath);

            ClientEngine ve      = ClientEngine.GetClientEngine();
            string       GDDpath = System.IO.Path.Combine(NformPath, @"bin\mds");

            System.IO.Directory.CreateDirectory(GDDpath);
            int startupflag = ve.Startup(GDDpath);

            Console.WriteLine("GDDPath:" + GDDpath);
            Console.WriteLine("startupflag:" + startupflag);

            CommsChannel channel = null;

            try
            {
                channel = ve.OpenChannel(CommStack.BACnetIp);
            }
            catch (Exception e)
            {
                Console.WriteLine("Can not open this channel! because: " + e.StackTrace.ToString());
            }

            foreach (string deviceIp in VelDeviceInfo.Values)
            {
                if (channel != null)
                {
                    DeviceNode node = channel.StrToEntity(deviceIp);
                    if (node != null)
                    {
                        Console.WriteLine("The device:" + deviceIp + " is availabe");
                    }
                    else
                    {
                        notAvailable.Add(deviceIp);
                        Console.WriteLine("There is no device in this ip address." + deviceIp + "!");
                    }
                }
                else
                {
                    Console.WriteLine("This channel is not available!");
                }
            }
            channel.Dispose();
            return(notAvailable);
        }
Exemple #13
0
        private static void StartEngine()
        {
            int     port;
            Torrent torrent = null;

            // Ask the user what port they want to use for incoming connections
            Console.Write(Environment.NewLine + "Choose a listen port: ");
            while (!Int32.TryParse(Console.ReadLine(), out port))
            {
            }



            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings(downloadsPath, port);

            engineSettings.PreferEncryption  = false;
            engineSettings.AllowedEncryption = EncryptionTypes.All;

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;


            // Create the default settings which a torrent will have.
            // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
            // 50 open connections - should never really need to be changed
            // Unlimited download speed - valid range from 0 -> int.Max
            // Unlimited upload speed - valid range from 0 -> int.Max
            TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0);

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);
                        Console.WriteLine(torrent.InfoHash.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    {
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.infoHash.ToHex()]));
                    }
                    engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e)
                {
                    lock (listener)
                        listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail"));
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e)
                {
                    lock (listener)
                        listener.WriteLine("OldState: " + e.OldState.ToString() + " NewState: " + e.NewState.ToString());
                };

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                    foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers)
                    {
                        t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e)
                        {
                            listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                        };
                    }
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(delegate(TorrentManager m) { return(m.State != TorrentState.Stopped); });

                    AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    AppendFormat(sb, "Total Upload Rate:   {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0);
                    AppendFormat(sb, "Disk Read Rate:      {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0);
                    AppendFormat(sb, "Disk Write Rate:     {0:0.00} kB/s", engine.DiskManager.WriteRate / 1024.0);
                    AppendFormat(sb, "Total Read:         {0:0.00} kB", engine.DiskManager.TotalRead / 1024.0);
                    AppendFormat(sb, "Total Written:      {0:0.00} kB", engine.DiskManager.TotalWritten / 1024.0);
                    AppendFormat(sb, "Open Connections:    {0}", engine.ConnectionManager.OpenConnections);

                    foreach (TorrentManager manager in torrents)
                    {
                        AppendSeperator(sb);
                        AppendFormat(sb, "State:           {0}", manager.State);
                        AppendFormat(sb, "Name:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                        AppendFormat(sb, "Progress:           {0:0.00}", manager.Progress);
                        AppendFormat(sb, "Download Speed:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                        AppendFormat(sb, "Upload Speed:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                        AppendFormat(sb, "Total Downloaded:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                        AppendFormat(sb, "Total Uploaded:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                        MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker;
                        //AppendFormat(sb, "Tracker Status:     {0}", tracker == null ? "<no tracker>" : tracker.State.ToString());
                        AppendFormat(sb, "Warning Message:    {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage);
                        AppendFormat(sb, "Failure Message:    {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage);
                        if (manager.PieceManager != null)
                        {
                            AppendFormat(sb, "Current Requests:   {0}", manager.PieceManager.CurrentRequestCount());
                        }

                        foreach (PeerId p in manager.GetPeers())
                        {
                            AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Peer.ConnectionUri,
                                         p.Monitor.DownloadSpeed / 1024.0,
                                         p.AmRequestingPiecesCount,
                                         p.Monitor.UploadSpeed / 1024.0);
                        }

                        AppendFormat(sb, "", null);
                        if (manager.Torrent != null)
                        {
                            foreach (TorrentFile file in manager.Torrent.Files)
                            {
                                AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete);
                            }
                        }
                    }
                    Console.Clear();
                    Console.WriteLine(sb.ToString());
                    listener.ExportTo(Console.Out);
                }

                System.Threading.Thread.Sleep(500);
            }
        }
Exemple #14
0
        private void StartEngine(int port)
        {
            Torrent torrent = null;
            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings(downloadsPath, port);

            engineSettings.PreferEncryption  = false;
            engineSettings.AllowedEncryption = EncryptionTypes.All;

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;


            // Create the default settings which a torrent will have.
            // 4 Upload slots
            // 50 open connections
            // Unlimited download, upload speed
            TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0);

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                MessageBox.Show("No existing dht nodes could be loaded");
            }

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(BasicTorrentsPath))
            {
                Directory.CreateDirectory(BasicTorrentsPath);
            }

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(BasicTorrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);

                        // Console.WriteLine(torrent.InfoHash.ToString());
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Couldn't decode {0}: " + e.Message, file);
                        //   continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    {
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                    }
                    engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                MessageBox.Show("No torrents found in the Torrents directory");
                MessageBox.Show("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail"));
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                    lock (listener)
                        listener.WriteLine("OldState: " + e.OldState.ToString() + " NewState: " + e.NewState.ToString());
                };

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                    foreach (MonoTorrent.Client.Tracker.Tracker t in tier.GetTrackers())
                    {
                        t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) {
                            listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                        };
                    }
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();
            }
        }
Exemple #15
0
        /// <summary>
        /// Check the velocity devices in the Devices.ini are available or not.
        /// If some devices are unavailable, the Devices.ini should be changed to give
        /// tester all available devices.
        /// </summary>
        /// <returns>list</returns>
        public static List <String> CheckVelocityDeviceAvailable()
        {
            // There are all devices in Device.ini.
            List <string> notAvailable = new List <string>();
            Hashtable     DeviceInfo   = new Hashtable();

            string DeviceConfigFile = AppConfigOper.getConfigValue("DeviceConfig");

            DeviceInfo = AppConfigOper.GetDevicesInfo("velocity", DeviceConfigFile);
            string      NformPath = "";
            RegistryKey Key;

            Key = Registry.LocalMachine;
            //Nform in Register table
            RegistryKey myreg = Key.OpenSubKey("software\\Wow6432Node\\Liebert\\Nform");

            NformPath = myreg.GetValue("InstallDir").ToString();
            myreg.Close();
            Console.WriteLine("NformPath:" + NformPath);

            ClientEngine ve      = ClientEngine.GetClientEngine();
            string       GDDpath = System.IO.Path.Combine(NformPath, @"bin\mds");

            System.IO.Directory.CreateDirectory(GDDpath);
            int startupflag = ve.Startup(GDDpath);

            Console.WriteLine("GDDPath:" + GDDpath);
            Console.WriteLine("startupflag:" + startupflag);

            CommsChannel channel = null;

            try
            {
                channel = ve.OpenChannel(CommStack.BACnetIp);
            }
            catch (Exception e)
            {
                Console.WriteLine("Can not open this channel! because: " + e.StackTrace.ToString());
            }
            foreach (string deviceIp in DeviceInfo.Values)
            {
                if (channel != null)
                {
                    DeviceNode node = channel.StrToEntity(deviceIp);
                    if (node != null)
                    {
                        Console.WriteLine("The device:" + deviceIp + " is availabe");
                    }
                    else
                    {
                        notAvailable.Add(deviceIp);
                        Console.WriteLine("There is no device in this ip address." + deviceIp + "!");
                    }
                }
                else
                {
                    Console.WriteLine("This channel is not available!");
                }
            }
            channel.Dispose();
            return(notAvailable);
        }
Exemple #16
0
 internal Steam4NET.IClientAppManager GetIClientAppManager(int HSteamUser, int HSteamPipe)
 {
     return(ClientEngine.GetIClientAppManager <Steam4NET.IClientAppManager>(HSteamUser, HSteamPipe));
 }
 public EngineTestRig(string savePath, int piecelength = 256*1024, PieceWriter writer = null)
 {
     if (writer == null)
         writer = new MemoryWriter(new NullWriter());
     _listener = new CustomListener();
     _engine = new ClientEngine(new EngineSettings(), _listener, writer);
     _torrentDict = CreateTorrent(piecelength);
     _torrent = Torrent.Load(_torrentDict);
     _manager = new TorrentManager(_torrent, savePath, new TorrentSettings());
     _engine.Register(_manager);
     //manager.Start();
 }
Exemple #18
0
        protected override async void OnNavigatedTo(NavigationEventArgs ee)
        {
            var port    = 6881;
            var dhtPort = 15000;

            // Use Universal.Nat to enable upnp port mapping

            /* var natManager = new NatManager(port);
             * natManager.Start();*/

            var picker = new FileOpenPicker();

            picker.FileTypeFilter.Add(".torrent");
            var file = await picker.PickSingleFileAsync();

            var stream = await file.OpenStreamForReadAsync();

            var torrent = Common.Torrent.Load(stream);

            if (torrent != null)
            {
                var engineSettings = new EngineSettings(ApplicationData.Current.LocalFolder.Path, port)
                {
                    PreferEncryption  = true,
                    AllowedEncryption = EncryptionTypes.All
                };

                // Create the default settings which a torrent will have.
                // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
                // 50 open connections - should never really need to be changed
                // Unlimited download speed - valid range from 0 -> int.Max
                // Unlimited upload speed - valid range from 0 -> int.Max
                var torrentDefaults = new TorrentSettings(4, 150, 0, 0)
                {
                    UseDht             = true,
                    EnablePeerExchange = true
                };

                // Create an instance of the engine.
                var engine = new ClientEngine(engineSettings);
                //engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));

                var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, dhtPort));
                var dht        = new DhtEngine(dhtListner);
                engine.RegisterDht(dht);
                dhtListner.Start();
                engine.DhtEngine.Start();

                // When any preprocessing has been completed, you create a TorrentManager
                // which you then register with the engine.
                var manager = new TorrentManager(torrent, ApplicationData.Current.LocalFolder, torrentDefaults);
                engine.Register(manager);

                // Every time a piece is hashed, this is fired.
                manager.PieceHashed +=
                    delegate(object o, PieceHashedEventArgs e)
                {
                    Debug.WriteLine("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail");
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged +=
                    delegate(object o, TorrentStateChangedEventArgs e)
                {
                    Debug.WriteLine("OldState: " + e.OldState + " NewState: " + e.NewState);
                };

                // Every time the tracker's state changes, this is fired
                foreach (var t in manager.TrackerManager.SelectMany(tier => tier.Trackers))
                {
                    t.AnnounceComplete +=
                        delegate(object sender, AnnounceResponseEventArgs e)
                    {
                        Debug.WriteLine("{0}: {1}", e.Successful, e.Tracker);
                    };
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();

                var dispatcher = Window.Current.Dispatcher;
                engine.StatsUpdate +=
                    async(sender, args) =>
                {
                    await
                    dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                        () =>
                    {
                        TextBlock.Text =
                            $"{manager.Peers.Seeds} seeds / {manager.Peers.Leechs} leechs / {manager.Progress} %";
                    });
                };
            }
        }
 public LocalPeerListener(ClientEngine engine)
     : base(new IPEndPoint(IPAddress.Any, 6771))
 {
     _engine = engine;
 }
 public void Setup()
 {
     Engine     = new ClientEngine();
     Torrent    = TestRig.CreateMultiFileTorrent(new[] { new TorrentFile("path", Piece.BlockSize * 1024) }, Piece.BlockSize * 8, out torrentInfo);
     MagnetLink = new MagnetLink(Torrent.InfoHash, "MagnetDownload");
 }
Exemple #21
0
        }                                               // This is a subclass of TraceListener which remembers the last 20 statements sent to it

        public VLCStream(ClientEngine engine)
        {
            DownloadDirectory = "streaming_cache";
            Listener          = new Top10Listener(10);
            Engine            = engine;
        }
        public void BeginCheckPingInterval()
        {
            Int64 now = ClientEngine.GetCurrentSeconds();

            Interlocked.Exchange(ref lastPingTime, now);
        }
Exemple #23
0
        public async Task <ImmutableList <string> > Download(string url,
                                                             List <string>?potentialArchives,
                                                             bool enablePortForwarding,
                                                             string outputPath,
                                                             CancellationToken cancellationToken)
        {
            var stopWatch = Stopwatch.StartNew();

            var paddingFolder = _fileSystem.Path.Combine(outputPath, ".____padding_file");
            var doesPaddingFolderExistToStart = _fileSystem.Directory.Exists(paddingFolder);

            var progressBar = _console.Progress()
                              .AutoClear(false)
                              .Columns(new ProgressColumn[]
            {
                new SpinnerColumn {
                    CompletedText = Emoji.Known.CheckMark
                }, new DownloadedColumnExtended(),
                new TaskDescriptionColumn(), new TorrentProgressBarColumn(), new PercentageColumn(),
                new TransferSpeedColumn(), new RemainingTimeColumn()
            });

            ImmutableList <TorrentFile>?downloadedFiles = null;
            await progressBar.StartAsync(async ctx =>
            {
                _console.WriteLine("Loading torrent...");

                var httpClient      = new HttpClient();
                var torrentContents = await httpClient.GetByteArrayAsync(url, cancellationToken);
                var settings        = new EngineSettings
                {
                    AllowedEncryption = EncryptionTypes.All, SavePath = outputPath, MaximumHalfOpenConnections = 16
                };


                _console.WriteLine("Initializing BitTorrent engine...");
                var engine = new ClientEngine(settings);

                if (enablePortForwarding)
                {
                    _console.WriteLine("Attempting to forward ports");
                    await engine.EnablePortForwardingAsync(cancellationToken);
                }

                var torrent = await Torrent.LoadAsync(torrentContents);
                if (potentialArchives != null)
                {
                    foreach (var torrentFile in torrent.Files)
                    {
                        if (!potentialArchives.Contains(torrentFile.Path))
                        {
                            torrentFile.Priority = Priority.DoNotDownload;
                        }
                    }
                }

                var manager = new TorrentManager(
                    torrent,
                    outputPath,
                    new TorrentSettings {
                    MaximumConnections = 250
                }, string.Empty);

                await engine.Register(manager);
                await engine.StartAll();


                downloadedFiles = manager.Torrent.Files
                                  .Where(i => i.Priority != Priority.DoNotDownload).ToImmutableList();

                var fileTasks = downloadedFiles
                                .ToDictionary(
                    i => i.Path,
                    file => ctx.AddTask(file.Path,
                                        new ProgressTaskSettings {
                    MaxValue = file.Length, AutoStart = false
                })
                    );

                while (manager.State != TorrentState.Stopped && manager.State != TorrentState.Seeding)
                {
                    foreach (var torrentFile in downloadedFiles)
                    {
                        var progressTask = fileTasks[torrentFile.Path];
                        if (torrentFile.BytesDownloaded > 0 && progressTask.IsStarted == false)
                        {
                            progressTask.StartTask();
                        }

                        progressTask.Increment(torrentFile.BytesDownloaded - progressTask.Value);
                        progressTask.State.Update <BitSmuggler>("torrentBits",
                                                                _ => new BitSmuggler(torrentFile.BitField));
                    }

                    await Task.Delay(100, cancellationToken);
                }

                await manager.StopAsync();
                await engine.StopAllAsync();

                try
                {
                    // the stackoverflow torrent files, and I think all of archive.org
                    // seem to have these padding files that sneak into the download even
                    // if they aren't included in the file list. not quite sure how to prevent that
                    // so I'm gonna delete them after the fact I guess
                    if (!doesPaddingFolderExistToStart && _fileSystem.Directory.Exists(paddingFolder))
                    {
                        _fileSystem.Directory.Delete(paddingFolder, true);
                    }
                }
                catch
                {
                    /* swallow */
                }

                foreach (var progressTask in fileTasks)
                {
                    progressTask.Value.StopTask();
                }
            });


            stopWatch.Stop();
            _console.MarkupLine($"Download complete in [blue]{stopWatch.Elapsed.Humanize()}[/].");

            return(downloadedFiles?.Select(i => _fileSystem.Path.Combine(outputPath, i.Path)).ToImmutableList() ??
                   ImmutableList <string> .Empty);
        }
Exemple #24
0
        /**
         * Takes the command line arguments and uses them to determine how to
         * startup JMeter.
         *
         * Called reflectively by {@link NewDriver#main(String[])}
         */
        public void Start(String[] args)
        {
            CLArgsParser parser = new CLArgsParser(args, options);
            String       error  = parser.GetErrorString();

            if (null != error)
            {
                System.Console.WriteLine("Error: " + error);
                System.Console.WriteLine("Usage");
                System.Console.WriteLine(CLUtil.DescribeOptions(options).ToString());
                return;
            }
            try
            {
                //initializeProperties(parser); // Also initialises JMeter logging

                ///*
                // * The following is needed for HTTPClient.
                // * (originally tried doing this in HTTPSampler2,
                // * but it appears that it was done too late when running in GUI mode)
                // * Set the commons logging default to Avalon Logkit, if not already defined
                // */
                //if (System.getProperty("org.apache.commons.logging.Log") == null)
                //{ // $NON-NLS-1$
                //    System.setProperty("org.apache.commons.logging.Log" // $NON-NLS-1$
                //            , "org.apache.commons.logging.impl.LogKitLogger"); // $NON-NLS-1$
                //}


                //logProperty("java.version"); //$NON-NLS-1$
                //logProperty("java.vm.name"); //$NON-NLS-1$
                //logProperty("os.name"); //$NON-NLS-1$
                //logProperty("os.arch"); //$NON-NLS-1$
                //logProperty("os.version"); //$NON-NLS-1$
                //logProperty("file.encoding"); // $NON-NLS-1$
                //log.Info("NetMeterHome="     + NetMeterUtils.getJMeterHome());
                //logProperty("user.dir","  ="); //$NON-NLS-1$
                //log.Info("PWD       =" + new File(".").getCanonicalPath());//$NON-NLS-1$
                //log.Info("IP: "+NetMeterUtils.getLocalHostIP()
                //        +" Name: "+NetMeterUtils.getLocalHostName()
                //        +" FullName: "+NetMeterUtils.getLocalHostFullName());

                //updateClassLoader();
                //if (log.IsDebugEnabled)
                //{
                //    String jcp = System.getProperty("java.class.path");// $NON-NLS-1$
                //    String[] bits = jcp.Split(File.pathSeparator);
                //    log.Debug("ClassPath");
                //    foreach(String bit in bits)
                //    {
                //        log.Debug(bit);
                //    }
                //    log.Debug(jcp);
                //}

                // Set some (hopefully!) useful properties
                Int64 now = DateTime.Now.Ticks;
                NetMeterUtils.setProperty("START.MS", now.ToString()); // $NON-NLS-1$
                DateTime today = DateTime.Now;                         // so it agrees with above
                // TODO perhaps should share code with __time() function for this...
                //NetMeterUtils.setProperty("START.YMD",new SimpleDateFormat("yyyyMMdd").format(today));// $NON-NLS-1$ $NON-NLS-2$
                //NetMeterUtils.setProperty("START.HMS",new SimpleDateFormat("HHmmss").format(today));// $NON-NLS-1$ $NON-NLS-2$

                if (parser.GetArgumentById(SERVER_OPT) != null)
                {
                    // Start the server
                    try
                    {
                        ClientEngine.StartClient(); // $NON-NLS-1$
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine("Server failed to start: " + ex);
                        log.Error("Giving up, as server failed with:", ex);
                        throw ex;
                    }
                    //startOptionalServers();
                }
                else
                {
                    String   testFile    = null;
                    CLOption testFileOpt = parser.GetArgumentById(TESTFILE_OPT);
                    if (testFileOpt != null)
                    {
                        testFile = testFileOpt.GetArgument();
                        if (USE_LAST_JMX.Equals(testFile))
                        {
                            testFile = LoadRecentProject.getRecentFile(0);// most recent
                        }
                    }

                    CLOption rem = parser.GetArgumentById(REMOTE_OPT_PARAM);
                    if (rem == null)
                    {
                        rem = parser.GetArgumentById(REMOTE_OPT);
                    }
                    CLOption jtl     = parser.GetArgumentById(LOGFILE_OPT);
                    String   jtlFile = null;
                    //if (jtl != null)
                    //{
                    //    jtlFile=processLAST(jtl.GetArgument(), ".jtl"); // $NON-NLS-1$
                    //}
                    StartTest(testFile, jtlFile, rem);
                }
            }
            //catch (IllegalUserActionException e)
            //{
            //    System.Console.WriteLine(e);
            //    System.Console.WriteLine("Incorrect Usage");
            //    System.Console.WriteLine(CLUtil.DescribeOptions(options).toString());
            //}
            catch (Exception ex)
            {
                log.Fatal("An error occurred: ", ex);
                System.Console.WriteLine("An error occurred: " + ex.Message);
                return;
            }
        }
Exemple #25
0
        //-------------------------------------------------------------
        public void DownloadTorrent(MonoTorrent.Torrent torrent)
        //-------------------------------------------------------------
        {
            if (torrent == null)
            {
                Log.Get().Write("torrent is null", Log.LogType.Error);
            }

            if (torrent.AnnounceUrls.Count <= 0)
            {
                Log.Get().Write("torrent missing announce", Log.LogType.Error);
            }

            string path = Helper.GetDirection();

            Log.Get().Write("Client downloading files torrent: " + torrent.Name);

            if (!Helper.IsPortAvailable(CLIENT_PORT))
            {
                Log.Get().Write("Failed starting client downloading file on port: " + CLIENT_PORT + " Port in use", Log.LogType.Error);
            }

            if (settings == null || engine == null)
            {
                //Settings
                settings = new EngineSettings();
                settings.AllowedEncryption = EncryptionTypes.All;
                settings.PreferEncryption  = true;
                settings.SavePath          = path;
                settings.ListenPort        = CLIENT_PORT;

                //Create client engine
                engine = new ClientEngine(settings);
            }

            //Check if torrent exist (reStarting a torrent)
            var torrentManagersResult = torrentManagers.Where(t => t.Torrent.Name.Equals(torrent.Name)).ToList();

            if (torrentManagersResult.Count >= 1)
            {
                Log.Get().Write("ReStarting torrent: " + torrent.Name);
                torrentManagersResult.FirstOrDefault().StartAsync();
            }
            else //New torrent
            {
                Log.Get().Write("Preparing new torrent: " + torrent.Name);
                var torrentSettings = new TorrentSettings();
                torrentSettings.AllowDht          = false;
                torrentSettings.AllowPeerExchange = true;
                TorrentManager torrentManager = new TorrentManager(torrent, path, torrentSettings);

                //Add logning
                torrentManager.ConnectionAttemptFailed += delegate(object o, ConnectionAttemptFailedEventArgs e) { Log.Get().Write("TorrentManager connectionAttemptFailed reason:" + e.Reason.ToString(), Log.LogType.Error); };
                torrentManager.PeerConnected           += delegate(object o, PeerConnectedEventArgs e) { Log.Get().Write("TorrentManager PeerConnected"); };
                torrentManager.PeerDisconnected        += delegate(object o, PeerDisconnectedEventArgs e) { Log.Get().Write("TorrentManager PeerDisconnected"); };
                torrentManager.PeersFound  += delegate(object o, PeersAddedEventArgs e) { Log.Get().Write("TorrentManager PeersAdded"); };
                torrentManager.PieceHashed += pieceHashedDelegate;

                torrentManager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e)
                {
                    Log.Get().Write("TorrentManager TorrentStateChanged, oldstate: " + e.OldState + " , newState: " + e.NewState);
                    if (kobberLan != null)
                    {
                        kobberLan.Invoke(new Action(() =>
                        {
                            bool status = kobberLan.UpdateProgressBar(e.NewState, (int)(torrentManager.Progress), torrentManager.Torrent.Name);
                            if (status == false)
                            {
                                torrentManager.StopAsync();

                                if (e.NewState != MonoTorrent.Client.TorrentState.Stopped && e.NewState != MonoTorrent.Client.TorrentState.Stopping)
                                {
                                    Log.Get().Write("TorrentHandler failed", Log.LogType.Error);
                                }
                            }
                        }));
                    }
                };

                engine.CriticalException += delegate(object o, CriticalExceptionEventArgs e) { Log.Get().Write("TorrentEngine CriticalException", Log.LogType.Error); };
                engine.StatsUpdate       += delegate(object o, StatsUpdateEventArgs e)
                {
                    if (o.GetType() == typeof(MonoTorrent.Client.ClientEngine))
                    {
                        ClientEngine clientEngine = (ClientEngine)o;

                        Log.Get().Write("TorrentEngine Statsupdate running: " + clientEngine.IsRunning +
                                        " , torrent Seeds: " + torrentManager.Peers.Seeds + ", Leech: " + torrentManager.Peers.Leechs +
                                        " , progress: " + torrentManager.Progress
                                        );

                        if (kobberLan != null && kobberLan.Disposing == false)
                        {
                            kobberLan.Invoke(new Action(() =>
                            {
                                bool status = kobberLan.UpdateProgressBar(torrentManager.State, (int)(torrentManager.Progress), torrentManager.Torrent.Name);
                                if (status == false)
                                {
                                    torrentManager.StopAsync();

                                    if (torrentManager.State != MonoTorrent.Client.TorrentState.Stopped && torrentManager.State != MonoTorrent.Client.TorrentState.Stopping)
                                    {
                                        Log.Get().Write("TorrentHandler failed", Log.LogType.Error);
                                    }
                                }
                            }));
                        }
                    }
                    else
                    {
                        Log.Get().Write("TorrentEngine Statsupdate: Unknown", Log.LogType.Error);
                    }
                };

                //Start downloading
                engine.Register(torrentManager);
                engine.StartAllAsync();

                //Add torrent to list
                torrentManagers.Add(torrentManager);
            }
        }
Exemple #26
0
 public ClientPacketHandler(ClientEngine engine)
 {
     this.engine = engine;
     InitializePackageHandlers();
 }
        public static void TestReadFile(string db, string torrentPath, string baseDir, string filePath, string origianlFile)
        {
            //System.Diagnostics.Debugger.Launch();
            var kernel = new StandardKernel();

            kernel.Load(new ServiceNinjectModule());

            kernel.Bind <FileInfoTable <TorrentManager> >().ToSelf().InSingletonScope();

            var dbs = new ChunkDbService(db, false);
            var ds  = new DeduplicationService(dbs);

            kernel.Bind <DeduplicationService>().ToConstant(ds).InSingletonScope();

            var writer = new DedupDiskWriter(ds);

            var engineSettings = new EngineSettings();

            engineSettings.PreferEncryption  = false;
            engineSettings.AllowedEncryption = EncryptionTypes.All;
            int port = 33123;
            var ip   = NetUtil.GetLocalIPByInterface("Local Area Connection");

            engineSettings.ReportedAddress = new IPEndPoint(ip, port);
            var engine = new ClientEngine(engineSettings, new DedupDiskWriter(ds));

            kernel.Bind <DiskManager>().ToConstant(engine.DiskManager).InSingletonScope();
            kernel.Bind <ClientEngine>().ToConstant(engine).InSingletonScope();

            kernel.Bind <DistributedDiskManager>().ToSelf();
            kernel.Bind <FileService>().ToSelf().WithConstructorArgument("baseDir", baseDir);

            kernel.Bind <VirtualDiskDownloadService>().ToSelf();
            var vd = kernel.Get <VirtualDiskDownloadService>();

            var torrent = Torrent.Load(torrentPath);

            logger.DebugFormat("Loaded torrent file: {0}, piece length: {1}.",
                               torrent.Name, torrent.PieceLength);
            vd.StartDownloadingFile(torrent, baseDir, -1);

            KernelContainer.Kernel = kernel;

            var m = new HurricaneServiceManager();

            m.Start();

            var url = string.Format("http://{0}:18081/FileService/", ip.ToString());

            logger.DebugFormat("Contacting service at {0}", url);
            var    client = new ManualFileServiceClient(url);
            string tstmsg = "tstmsg";
            var    resp   = client.Echo(tstmsg);

            Assert.AreEqual(resp, tstmsg);

            byte[] resultData = null;

            try {
                var pathStatus = client.GetPathStatus(filePath);
                logger.DebugFormat("File size: {0}", pathStatus.FileSize);
            } catch (Exception ex) {
                logger.Error(ex);
            }

            try {
                // can only read 49352.
                resultData = client.Read(filePath, 0, 49253);
            } catch (Exception ex) {
                logger.Error(ex);
            }

            var actualData = IOUtil.Read(origianlFile, 0, 49252);

            try {
                Assert.IsTrue(actualData.SequenceEqual(resultData),
                              "File part should match.");
                logger.Debug("Read succeeded.");
            } catch (Exception ex) {
                logger.Error(ex);
            }

            Console.Read();
        }
        private void StartEngine(int maxUpload)
        {
            int     port    = 54321;
            Torrent torrent = null;
            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings(downloadsPath, port);

            engineSettings.PreferEncryption  = true;
            engineSettings.AllowedEncryption = EncryptionTypes.RC4Full | EncryptionTypes.RC4Header;

            // Create the default settings which a torrent will have.
            // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
            // 50 open connections - should never really need to be changed
            // Unlimited download speed - valid range from 0 -> int.Max
            // Unlimited upload speed - valid range from 0 -> int.Max
            TorrentSettings torrentDefaults = new TorrentSettings(100, 150, 0, maxUpload);

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);
                        RemoveReadOnly(torrent);
                    }
                    catch (Exception e)
                    {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    //if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    //    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                    engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e)
                {
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += OnTorrentStateChanged;

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i            = 0;
            bool          running      = true;
            StringBuilder sb           = new StringBuilder(1024);
            DateTime      lastAnnounce = DateTime.Now;
            bool          firstRun     = true;

            while (running)
            {
                if (firstRun || lastAnnounce < DateTime.Now.AddMinutes(-1))
                {
                    foreach (TorrentManager tm in torrents)
                    {
                        tm.TrackerManager.Announce();
                    }
                    lastAnnounce = DateTime.Now;
                    firstRun     = false;
                }
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(delegate(TorrentManager m) { return(m.State != TorrentState.Stopped); });

                    TorrentState totalState = torrents.Exists(m => m.State == TorrentState.Hashing) ? TorrentState.Hashing : torrents.Exists(m => m.State == TorrentState.Downloading) ? TorrentState.Downloading : TorrentState.Seeding;

                    string status = "";
                    switch (totalState)
                    {
                    case TorrentState.Hashing:
                        double totalHashProgress = 0;
                        foreach (TorrentManager m in torrents)
                        {
                            totalHashProgress += (m.State == TorrentState.Hashing) ? m.Progress : 100;
                        }
                        totalHashProgress = totalHashProgress / torrents.Count;
                        status            = String.Format("Checking files ({0:0.00}%)", totalHashProgress);
                        break;

                    case TorrentState.Seeding:
                        status = "";
                        break;

                    default:
                        double totalDownloadProgress = 0;
                        double totalDownloaded       = 0;
                        double totalToDownload       = 0;
                        double totalDownloadSpeed    = 0;
                        long   totalDownloadSize     = 0;
                        foreach (TorrentManager m in torrents)
                        {
                            totalDownloadSize += m.Torrent.Size;
                        }

                        foreach (TorrentManager m in torrents)
                        {
                            totalDownloaded    += m.Torrent.Size / 1024 * (m.Progress / 100);
                            totalToDownload    += m.Torrent.Size / 1024;
                            totalDownloadSpeed += m.Monitor.DownloadSpeed;
                        }
                        totalDownloadProgress = (totalDownloaded / totalToDownload) * 100;
                        status  = "Status: " + (torrents.Exists(m => m.State == TorrentState.Downloading && m.GetPeers().Count > 0) ? "Downloading" : "Finding peers");
                        status += "\n" + String.Format("Progress: {0:0.00}%", totalDownloadProgress);
                        status += "\n" + String.Format("D/L Speed: {0:0.00} kB/s", totalDownloadSpeed / 1024.0);
                        break;
                    }
                    if (installer != null)
                    {
                        installer.Status = status;
                    }

                    #region OLDPROGRESS
                    //foreach (TorrentManager manager in torrents)
                    //{
                    //    AppendSeperator(sb);
                    //    AppendFormat(sb, "State:           {0}", manager.State);
                    //    AppendFormat(sb, "Name:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                    //    AppendFormat(sb, "Progress:           {0:0.00}", manager.Progress);
                    //    string status = "";
                    //    switch (manager.State)
                    //    {
                    //        case TorrentState.Hashing:
                    //            status = String.Format("Checking files ({0:0.00}%)", manager.Progress);
                    //            break;
                    //        case TorrentState.Seeding: status = ""; break;
                    //        default:
                    //            status = "Status: " + (manager.GetPeers().Count == 0 ? "Finding Peers" : "Downloading");
                    //            status += "\n" + String.Format("Progress: {0:0.00}%", manager.Progress);
                    //            status += "\n" + String.Format("D/L Speed: {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                    //            break;
                    //    }
                    //    if (installer != null)
                    //        installer.Status = status;
                    //    AppendFormat(sb, "Download Speed:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                    //    AppendFormat(sb, "Upload Speed:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                    //    AppendFormat(sb, "Total Downloaded:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                    //    AppendFormat(sb, "Total Uploaded:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                    //    MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker;
                    //    AppendFormat(sb, "Tracker Status:     {0}", tracker == null ? "<no tracker>" : tracker.Status.ToString());
                    //    AppendFormat(sb, "Warning Message:    {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage);
                    //    AppendFormat(sb, "Failure Message:    {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage);
                    //}
                    ////Console.Clear();
                    //Console.WriteLine(sb.ToString());
                    #endregion
                }

                System.Threading.Thread.Sleep(500);
            }
        }
Exemple #29
0
        private void TestWorker(object obj)
        {
            int qps  = (int)obj;
            int msec = 1000 / qps;

            lock (this)
            {
                Console.WriteLine("-- qps: " + qps + ", sleep milliseconds interval: " + msec);
            }

            TCPClient client = new TCPClient(ip, port);

            ProcessEncrypt(client);
            if (!client.SyncConnect())
            {
                lock (this)
                {
                    Console.WriteLine("Client sync connect remote server " + ip + ":" + port + " failed.");
                }
            }

            while (running)
            {
                Quest quest     = GenQuest();
                Int64 send_time = ClientEngine.GetCurrentMicroseconds();

                client.SendQuest(quest, (Answer answer, int errorCode) =>
                {
                    if (errorCode != ErrorCode.FPNN_EC_OK)
                    {
                        Interlocked.Add(ref recvErrorCount, 1);
                        if (errorCode == ErrorCode.FPNN_EC_CORE_TIMEOUT)
                        {
                            lock (this)
                                Console.WriteLine("Timeouted occurred when recving.");
                        }
                        else
                        {
                            lock (this)
                                Console.WriteLine("Error occurred when recving..");
                        }
                    }
                    else
                    {
                        Interlocked.Add(ref recvCount, 1);

                        Int64 recv_time = ClientEngine.GetCurrentMicroseconds();
                        Int64 diff      = recv_time - send_time;
                        Interlocked.Add(ref timeCost, diff);
                    }
                });

                Interlocked.Add(ref sendCount, 1);

                Int64 sent_time = ClientEngine.GetCurrentMicroseconds();
                Int64 real_usec = msec * 1000 - (sent_time - send_time);
                if (real_usec > 1000)
                {
                    Thread.Sleep((int)(real_usec / 1000));
                }
                else if (real_usec > 500)
                {
                    Thread.Sleep(1);
                }
            }

            client.Close();
        }
        public async Task DownloadAsync(MagnetLink link)
        {
            using var engine = new ClientEngine();
            var manager = await engine.AddStreamingAsync(link, "downloads");

            var times = new List <(string message, TimeSpan time)> ();

            var overall            = Stopwatch.StartNew();
            var firstPeerFound     = Stopwatch.StartNew();
            var firstPeerConnected = Stopwatch.StartNew();

            manager.PeerConnected += (o, e) => {
                if (!firstPeerConnected.IsRunning)
                {
                    return;
                }

                firstPeerConnected.Stop();
                lock (times)
                    times.Add(("First peer connected. Time since torrent started: ", firstPeerConnected.Elapsed));
            };
            manager.PeersFound += (o, e) => {
                if (!firstPeerFound.IsRunning)
                {
                    return;
                }

                firstPeerFound.Stop();
                lock (times)
                    times.Add(($"First peers found via {e.GetType ().Name}. Time since torrent started: ", firstPeerFound.Elapsed));
            };
            manager.PieceHashed += (o, e) => {
                if (manager.State != TorrentState.Downloading)
                {
                    return;
                }

                lock (times)
                    times.Add(($"Piece {e.PieceIndex} hashed. Time since torrent started: ", overall.Elapsed));
            };

            await manager.StartAsync();

            await manager.WaitForMetadataAsync();

            var largestFile = manager.Files.OrderByDescending(t => t.Length).First();
            var stream      = await manager.StreamProvider.CreateStreamAsync(largestFile, false);


            // Read the middle
            await TimedRead(manager, stream, stream.Length / 2, times);

            // Then the start
            await TimedRead(manager, stream, 0, times);

            // Then the last piece
            await TimedRead(manager, stream, stream.Length - 2, times);

            // Then the 3rd last piece
            await TimedRead(manager, stream, stream.Length - manager.PieceLength * 3, times);

            // Then the 5th piece
            await TimedRead(manager, stream, manager.PieceLength * 5, times);

            // Then 1/3 of the way in
            await TimedRead(manager, stream, stream.Length / 3, times);

            // Then 2/3 of the way in
            await TimedRead(manager, stream, stream.Length / 3 * 2, times);

            // Then 1/5 of the way in
            await TimedRead(manager, stream, stream.Length / 5, times);

            // Then 4/5 of the way in
            await TimedRead(manager, stream, stream.Length / 5 * 4, times);

            lock (times) {
                foreach (var p in times)
                {
                    Console.WriteLine($"{p.message} {p.time.TotalSeconds:0.00} seconds");
                }
            }

            await manager.StopAsync();
        }
Exemple #31
0
 internal Steam4NET.IClientApps GetIClientApps(int HSteamUser, int HSteamPipe)
 {
     return(ClientEngine.GetIClientApps <Steam4NET.IClientApps>(HSteamUser, HSteamPipe));
 }
        private bool Login(AuthDelegate callback, string token, Dictionary <string, string> attr, string lang = "", int timeout = 0)
        {
            lock (interLocker)
            {
                if (status == ClientStatus.Connected)
                {
                    ClientEngine.RunTask(() =>
                    {
                        callback(projectId, uid, true, fpnn.ErrorCode.FPNN_EC_OK);
                    });

                    return(true);
                }

                if (status == ClientStatus.Connecting)
                {
                    authStatsInfo.authDelegates.Add(callback);
                    return(true);
                }

                status = ClientStatus.Connecting;
                syncConnectingEvent.Reset();

                requireClose = false;

                if (autoReloginInfo != null)
                {
                    autoReloginInfo.Login();
                }
            }

            authStatsInfo = new AuthStatusInfo
            {
                authDelegates = new HashSet <AuthDelegate>()
                {
                    callback
                },
                remainedTimeout = timeout,
            };

            authStatsInfo.token = token;
            authStatsInfo.attr  = attr;
            authStatsInfo.lang  = lang;
            authStatsInfo.lastActionMsecTimeStamp = ClientEngine.GetCurrentMilliseconds();

            //if (rtmGate.IsConnected())
            //{
            //    if (authStatsInfo.remainedTimeout == 0)
            //        authStatsInfo.remainedTimeout = RTMConfig.globalQuestTimeoutSeconds;

            //    RTMControlCenter.RegisterSession(rtmGateConnectionId, this);
            //    Auth(false);
            //}
            //else
            {
                if (authStatsInfo.remainedTimeout == 0)
                {
                    authStatsInfo.remainedTimeout = ((ConnectTimeout == 0) ? RTMConfig.globalConnectTimeoutSeconds : ConnectTimeout)
                                                    + ((QuestTimeout == 0) ? RTMConfig.globalQuestTimeoutSeconds : QuestTimeout);
                }

                rtmGate.AsyncConnect();
            }

            return(true);
        }
Exemple #33
0
        private void MainForm_Load( object sender, EventArgs e )
        {
            ClassEditControl scout = new ClassEditControl( "Scout" );
            scout.ClassImage = Properties.Resources.scout;

            // heavy
            ClassEditControl heavy = new ClassEditControl( "Heavy" );
            heavy.ClassImage = Properties.Resources.heavy;

            // medic
            ClassEditControl medic = new ClassEditControl( "Medic" );
            medic.ClassImage = Properties.Resources.medic;

            // soldier
            ClassEditControl soldier = new ClassEditControl( "Soldier" );
            soldier.ClassImage = Properties.Resources.soldier;

            // engi
            ClassEditControl engineer = new ClassEditControl( "Engineer" );
            engineer.ClassImage = Properties.Resources.engineer;

            // spy
            ClassEditControl spy = new ClassEditControl( "Spy" );
            spy.ClassImage = Properties.Resources.spy;

            // sniper
            ClassEditControl sniper = new ClassEditControl( "Sniper" );
            sniper.ClassImage = Properties.Resources.sniper;

            // demo
            ClassEditControl demo = new ClassEditControl( "Demoman" );
            demo.ClassImage = Properties.Resources.demoman;

            // pyro
            ClassEditControl pyro = new ClassEditControl( "Pyro" );
            pyro.ClassImage = Properties.Resources.pyro;

            flowLayoutPanel1.Controls.Add( scout );
            flowLayoutPanel1.Controls.Add( heavy );
            flowLayoutPanel1.Controls.Add( medic );
            flowLayoutPanel1.Controls.Add( soldier );
            flowLayoutPanel1.Controls.Add( engineer );
            flowLayoutPanel1.Controls.Add( spy );
            flowLayoutPanel1.Controls.Add( sniper );
            flowLayoutPanel1.Controls.Add( demo );
            flowLayoutPanel1.Controls.Add( pyro );

            toolStripStatusLabel1.Text = "Initializing steamworks...";

            try
            {
                int error;
                client = ( SteamClient008 )Steamworks.CreateInterface( SteamClient008.InterfaceVersion, out error );

                if ( client == null )
                    throw new InvalidOperationException( "Unable to create ISteamClient." );

                pipe = client.CreateSteamPipe();
                if ( pipe == SteamPipeHandle.InvalidHandle )
                    throw new InvalidOperationException( "Unable to create steam pipe." );

                user = client.ConnectToGlobalUser( pipe );

                clientEngine = ( ClientEngine )Steamworks.CreateInterface( ClientEngine.InterfaceVersion, out error );

                if ( clientEngine == null )
                    throw new InvalidOperationException( "Unable to create IClientEngine." );
            }
            catch (Exception ex)
            {
                MessageBox.Show( this, "Unable to initialize steamworks. Please ensure the following:\n\n" +
                    " * steamclient.dll, tier0_s.dll, vstdlib_s.dll, are present in the running directory\n" +
                    " * You are logged into steam and are online.\n\nAdditional Details: " + ex.Message, "TF2 Stats Suite"
                );

                this.Close();
                return;
            }

            toolStripStatusLabel1.Text = "Loading stats...";

            statsAcc = new StatsAccessor( client, pipe, user, 440 );

            steamUser = ( SteamUser012 )client.GetISteamUser( user, pipe, SteamUser012.InterfaceVersion );
            clientUtils = ( ClientUtils )clientEngine.GetIClientUtils( pipe, ClientUtils.InterfaceVersion );

            clientUtils.SetAppIDForCurrentPipe( new AppID( 440 ) );

            foreach ( ClassEditControl cec in flowLayoutPanel1.Controls )
            {
                toolStripStatusLabel1.Text = "Loading stats for '" + cec.Class + "'...";
                cec.LoadStats( statsAcc );
                Application.DoEvents();
            }

            toolStripStatusLabel1.Text = "Stats fully loaded!";
        }
Exemple #34
0
        void Start()
        {
            //Start Torrent Engine
            torrents = new List <TorrentManager>();
            messages = new List <SimpleMessage>();

            //Torrents to remove
            seedingLimitTorrents = new List <Tuple <DateTime, TorrentManager> >();

            Console.WriteLine("simpletorrent: version {0}", VERSION);
            Console.WriteLine("simpletorrent: Reading configuration file (simple.cfg)...");

            config = new SimpleConfiguration("simple.cfg");
            string basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

            Console.WriteLine("simpletorrent: ApplicationPath (derived) {0}", basePath);

            if (config.HasValue("Debug"))
            {
                debugWriter = new DebugWriter(true);
                Console.WriteLine("simpletorrent: Debugging Enabled!");
            }
            else
            {
                debugWriter = new DebugWriter(false);
            }

            PlatformID os = Environment.OSVersion.Platform;

            if (os == PlatformID.MacOSX)
            {
                Console.WriteLine("simpletorrent: We think we're on MacOSX");
                simpleOperatingSystem = SimpleTorrentOperatingMode.MacOSX;
            }
            else if (os == PlatformID.Unix)
            {
                Console.WriteLine("simpletorrent: We think we're on *nix");
                simpleOperatingSystem = SimpleTorrentOperatingMode.StarNix;
            }
            else
            {
                Console.WriteLine("simpletorrent: We think we're on Windows");
                simpleOperatingSystem = SimpleTorrentOperatingMode.Windows;
            }

            torrentsPath       = Path.GetFullPath(config.GetValue("TorrentPath", Path.Combine(basePath, "Torrents")));
            downloadsPath      = Path.GetFullPath(config.GetValue("DownloadPath", Path.Combine(basePath, "Downloads")));
            sslCertificatePath = Path.GetFullPath(config.GetValue("SslCertificatePath", Path.Combine(basePath, "simple.pfx")));
            useECDSA           = config.HasValue("SslCertificateECDSA");
            fastResumeFile     = Path.Combine(torrentsPath, "fastresume.data");
            dhtNodeFile        = Path.Combine(torrentsPath, "dht.data");

            requireProtocolEncryption = config.HasValue("RequireProtocolEncryption");

            sessionLimit = config.GetValueInt("SessionLimit", 20);
            seedingLimit = config.GetValueInt("SeedingLimit");

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(downloadsPath))
            {
                Directory.CreateDirectory(downloadsPath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            downloadsPathDrive = null;
            string myRootPath = Path.GetPathRoot(downloadsPath).ToLower();

            if (simpleOperatingSystem == SimpleTorrentOperatingMode.StarNix)
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents              = false;
                proc.StartInfo.FileName               = "bash";
                proc.StartInfo.Arguments              = "-c \"df -h " + downloadsPath + " | awk '{print $6}' | tail -1\"";
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                string output = proc.StandardOutput.ReadToEnd().Trim().ToLower();
                proc.WaitForExit();

                if (proc.ExitCode == 0)
                {
                    myRootPath = output;
                    debugWriter.WriteLine("*nix override (bash -c 'df -h <path>') - \"" + output + "\"");
                }
            }
            else if (simpleOperatingSystem == SimpleTorrentOperatingMode.MacOSX)
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents              = false;
                proc.StartInfo.FileName               = "bash";
                proc.StartInfo.Arguments              = "-c \"df -h " + downloadsPath + " | awk '{print $9}' | tail -1\"";
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                string output = proc.StandardOutput.ReadToEnd().Trim().ToLower();
                proc.WaitForExit();

                if (proc.ExitCode == 0)
                {
                    myRootPath = output;
                    debugWriter.WriteLine("*nix override (bash -c 'df -h <path>') - \"" + output + "\"");
                }
            }

            foreach (var drive in DriveInfo.GetDrives())
            {
                debugWriter.WriteLine("Enemerating Drives - " + drive.RootDirectory.FullName.ToString());

                if (drive.RootDirectory.FullName.ToLower()
                    == myRootPath)
                {
                    downloadsPathDrive = drive;
                    break;
                }
            }

            Console.WriteLine("simpletorrent: TorrentPath {0}", torrentsPath);
            Console.WriteLine("simpletorrent: DownloadPath {0}", downloadsPath);
            Console.WriteLine("simpletorrent: DownloadRootPath (derived) {0}", downloadsPathDrive);
            Console.WriteLine("simpletorrent: SslCertificatePath {0}", sslCertificatePath);
            Console.WriteLine("simpletorrent: SslCertificateECDSA {0}", useECDSA ? "Yes" : "No");
            Console.WriteLine("simpletorrent: RequireProtocolEncryption {0}", requireProtocolEncryption ? "Yes" : "No");
            Console.WriteLine("simpletorrent: SessionLimit {0}", sessionLimit);
            Console.WriteLine("simpletorrent: SeedingLimit {0}", seedingLimit.HasValue ? seedingLimit.Value.ToString() : "No");

            int?torrentListenPort = config.GetValueInt("TorrentListenPort");

            if (!torrentListenPort.HasValue)
            {
                throw new SimpleTorrentException("Configuration does not have a proper 'TorrentListenPort' value defined", null);
            }

            Console.WriteLine("simpletorrent: TorrentListenPort {0}", torrentListenPort);

            externalBanList  = new List <string>();
            externalBanLists = new Dictionary <string, BanList>();
            foreach (var i in config.GetValues("ExternalBanList"))
            {
                Console.WriteLine("simpletorrent: ExternalBanList {0}", i);
                externalBanList.Add(i);
            }

            externalBanListLimit = config.GetValueInt("ExternalBanListLimit");

            if (externalBanListLimit.HasValue)
            {
                Console.WriteLine("simpletorrent: ExternalBanListLimit {0}", externalBanListLimit.Value);
            }

            EngineSettings engineSettings = new EngineSettings(downloadsPath, torrentListenPort.Value);

            engineSettings.PreferEncryption     = true;
            engineSettings.AllowedEncryption    = requireProtocolEncryption ? EncryptionTypes.RC4Full : EncryptionTypes.All;
            engineSettings.GlobalMaxConnections = 500;

            torrentDefaults = new TorrentSettings(4, 500, 0, 0);
            engine          = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, torrentListenPort.Value));

            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Console.WriteLine("simpletorrent: No existing DHT nodes could be loaded");
            }

            dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, torrentListenPort.Value));
            DhtEngine dht = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            foreach (var torrent in Directory.GetFiles(torrentsPath, "*.torrent"))
            {
                Torrent t = Torrent.Load(torrent);

                if (engine.Torrents.Where(i => i.InfoHash == t.InfoHash).Count() == 0)
                {
                    TorrentManager tm = new TorrentManager(t, downloadsPath, torrentDefaults);
                    engine.Register(tm);
                }
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            if (seedingLimit.HasValue)
            {
                Console.WriteLine("simpletorrent: Starting seeding limits watchdog timer...");
                seedingLimitTimer           = new System.Timers.Timer();
                seedingLimitTimer.AutoReset = true;
                seedingLimitTimer.Interval  = 60 * 1000;
                seedingLimitTimer.Elapsed  += (s, e) =>
                {
                    lock (seedingLimitTorrents)
                    {
                        var torrentsToRemove = seedingLimitTorrents.Where(a => (DateTime.Now - a.Item1).TotalSeconds >= seedingLimit).ToArray();
                        foreach (var i in torrentsToRemove)
                        {
                            try
                            {
                                seedingLimitTorrents.Remove(i);

                                if (i != null && i.Item2.State == TorrentState.Seeding)
                                {
                                    Console.WriteLine("simpletorrent: Automatically removing \"{0}\"...",
                                                      i.Item2.Torrent.Name);
                                    torrentInformation[i.Item2.InfoHash.ToHex()].ToRemove = "delete-torrent";
                                    i.Item2.Stop();
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                };
                seedingLimitTimer.Start();
            }

            //Ban List System
            UpdateBanLists();

            engine.ConnectionManager.BanPeer += (s, e) =>
            {
                bool ban = false;

                lock (externalBanLists)
                {
                    foreach (var i in externalBanLists)
                    {
                        ban |= i.Value.IsBanned(IPAddress.Parse(e.Peer.ConnectionUri.Host));
                    }
                }

                e.BanPeer = ban;

                if (e.BanPeer)
                {
                    debugWriter.WriteLine(string.Format("Connection from {0} denied.", e.Peer.ConnectionUri.Host));
                }
                else
                {
                    debugWriter.WriteLine(string.Format("Connection from {0} allowed.", e.Peer.ConnectionUri.Host));
                }
            };

            if (externalBanListLimit.HasValue)
            {
                Console.WriteLine("simpletorrent: Starting external ban list update timer...");
                externalBanListLimitTimer           = new System.Timers.Timer();
                externalBanListLimitTimer.AutoReset = true;
                externalBanListLimitTimer.Interval  = 1000 * externalBanListLimit.Value;
                externalBanListLimitTimer.Elapsed  += (s, e) =>
                {
                    UpdateBanLists();
                };

                externalBanListLimitTimer.Start();
            }

            using (var httpServer = new HttpServer(new HttpRequestProvider()))
            {
                Console.WriteLine("simpletorrent: Starting HTTP(S) server...");
                bool listeningOne = false;

                Console.WriteLine("simpletorrent: Creating session manager...");
                httpServer.Use(new SessionHandler <SimpleTorrentSession>(() =>
                                                                         new SimpleTorrentSession(), sessionLimit));

                foreach (var ip in config.GetValues("Listen"))
                {
                    try
                    {
                        TcpListener tl = getTcpListener(ip);
                        httpServer.Use(new TcpListenerAdapter(tl));
                        Console.WriteLine("simpletorrent: Listening for HTTP on {0}...", tl.LocalEndpoint);
                        listeningOne = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("simpletorrent: ({0}) " + ex.Message, ip);
                    }
                }


                System.Security.Cryptography.X509Certificates.X509Certificate2 cert = null;
                if (config.HasValue("ListenSsl"))
                {
                    cert = SSLSelfSigned.GetCertOrGenerate(sslCertificatePath, useECDSA);
                }

                foreach (var ip in config.GetValues("ListenSsl"))
                {
                    try
                    {
                        TcpListener tl = getTcpListener(ip);

                        //Mono does not support TLS 1.1 or 1.2 -->
#if MONO
                        httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(tl), cert, System.Security.Authentication.SslProtocols.Ssl3 |
                                                                System.Security.Authentication.SslProtocols.Tls));
#else
                        //Force new systems to use TLS 1.1 or 1.2
                        httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(tl), cert, System.Security.Authentication.SslProtocols.Tls11
                                                                | System.Security.Authentication.SslProtocols.Tls12));
#endif

                        Console.WriteLine("simpletorrent: Listening for HTTPS on {0}...", tl.LocalEndpoint);
                        listeningOne = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("simpletorrent: ({0}) " + ex.Message, ip);
                    }
                }

                if (!listeningOne)
                {
                    throw new SimpleTorrentException("simpletorrent was unable to bind to a single port.");
                }

                Console.WriteLine("simpletorrent: Running...");

                httpServer.Use((context, next) =>
                {
                    context.Response = ProcessRequest(context);

                    return(Task.Factory.GetCompleted());
                });

                foreach (var tm in engine.Torrents)
                {
                    SetupTorrent(tm);
                }

                httpServer.Start();

                Console.ReadLine();
            }
        }
Exemple #35
0
        public async Task RunAsync()
        {
            //LoggerFactory.Creator = className => new TextLogger (Console.Out, className);

            int port   = 37827;
            var seeder = new ClientEngine(
                new EngineSettingsBuilder {
                AllowedEncryption = new[] { EncryptionType.PlainText },
                DiskCacheBytes    = DataSize,
                ListenEndPoint    = new IPEndPoint(IPAddress.Any, port++)
            }.ToSettings(),
                Factories.Default.WithPieceWriterCreator(maxOpenFiles => new NullWriter())
                );

            var downloaders = Enumerable.Range(port, 16).Select(p => {
                return(new ClientEngine(
                           new EngineSettingsBuilder {
                    AllowedEncryption = new[] { EncryptionType.PlainText },
                    DiskCacheBytes = DataSize,
                    ListenEndPoint = new IPEndPoint(IPAddress.Any, p),
                }.ToSettings(),
                           Factories.Default.WithPieceWriterCreator(maxOpenFiles => new NullWriter())
                           ));
            }).ToArray();

            Directory.CreateDirectory(DataDir);
            // Generate some fake data on-disk
            var buffer = Enumerable.Range(0, 16 * 1024).Select(s => (byte)s).ToArray();

            using (var fileStream = File.OpenWrite(Path.Combine(DataDir, "file.data"))) {
                for (int i = 0; i < DataSize / buffer.Length; i++)
                {
                    fileStream.Write(buffer, 0, buffer.Length);
                }
                fileStream.SetLength(DataSize);
            }

            var trackerListener = TrackerListenerFactory.CreateHttp(IPAddress.Parse("127.0.0.1"), 25611);
            var tracker         = new TrackerServer {
                AllowUnregisteredTorrents = true
            };

            tracker.RegisterListener(trackerListener);
            trackerListener.Start();

            // Create the torrent file for the fake data
            var creator = new TorrentCreator();

            creator.Announces.Add(new List <string> ());
            creator.Announces[0].Add("http://127.0.0.1:25611/announce");

            var metadata = await creator.CreateAsync(new TorrentFileSource (DataDir));

            // Set up the seeder
            await seeder.AddAsync(Torrent.Load(metadata), DataDir, new TorrentSettingsBuilder { UploadSlots = 20 }.ToSettings());

            using (var fileStream = File.OpenRead(Path.Combine(DataDir, "file.data"))) {
                while (fileStream.Position < fileStream.Length)
                {
                    var dataRead = new byte[16 * 1024];
                    int offset   = (int)fileStream.Position;
                    int read     = fileStream.Read(dataRead, 0, dataRead.Length);
                    // FIXME: Implement a custom IPieceWriter to handle this.
                    // The internal MemoryWriter is limited and isn't a general purpose read/write API
                    // await seederWriter.WriteAsync (seeder.Torrents[0].Files[0], offset, dataRead, 0, read, false);
                }
            }

            await seeder.StartAllAsync();

            List <Task> tasks = new List <Task> ();

            for (int i = 0; i < downloaders.Length; i++)
            {
                await downloaders[i].AddAsync(
                    Torrent.Load(metadata),
                    Path.Combine(DataDir, "Downloader" + i)
                    );

                tasks.Add(RepeatDownload(downloaders[i]));
            }

            while (true)
            {
                long downTotal        = seeder.TotalDownloadRate;
                long upTotal          = seeder.TotalUploadRate;
                long totalConnections = 0;
                long dataDown         = seeder.Torrents[0].Monitor.DataBytesReceived + seeder.Torrents[0].Monitor.ProtocolBytesReceived;
                long dataUp           = seeder.Torrents[0].Monitor.DataBytesSent + seeder.Torrents[0].Monitor.ProtocolBytesSent;
                foreach (var engine in downloaders)
                {
                    downTotal += engine.TotalDownloadRate;
                    upTotal   += engine.TotalUploadRate;

                    dataDown         += engine.Torrents[0].Monitor.DataBytesReceived + engine.Torrents[0].Monitor.ProtocolBytesReceived;
                    dataUp           += engine.Torrents[0].Monitor.DataBytesSent + engine.Torrents[0].Monitor.ProtocolBytesSent;
                    totalConnections += engine.ConnectionManager.OpenConnections;
                }
                Console.Clear();
                Console.WriteLine($"Speed Down:        {downTotal / 1024 / 1024}MB.");
                Console.WriteLine($"Speed Up:          {upTotal / 1024 / 1024}MB.");
                Console.WriteLine($"Data Down:          {dataDown / 1024 / 1024}MB.");
                Console.WriteLine($"Data Up:            {dataUp / 1024 / 1024}MB.");

                Console.WriteLine($"Total Connections: {totalConnections}");
                await Task.Delay(3000);
            }
        }
Exemple #36
0
            private void TestWorker()
            {
                int act = 0;

                for (int i = 0; i < questCount; i++)
                {
                    long index = (ClientEngine.GetCurrentMicroseconds() + i) % 64;
                    if (i >= 10)
                    {
                        if (index < 6)
                        {
                            act = 2;    //-- close operation
                        }
                        else if (index < 32)
                        {
                            act = 1;    //-- async quest
                        }
                        else
                        {
                            act = 0;    //-- sync quest
                        }
                    }
                    else
                    {
                        act = (int)(index & 0x1);
                    }


                    switch (act)
                    {
                    case 0:
                    {
                        Console.Write("*");
                        Answer answer = client.SendQuest(GenQuest());
                        if (answer != null)
                        {
                            if (answer.IsException())
                            {
                                if (answer.ErrorCode() == ErrorCode.FPNN_EC_CORE_CONNECTION_CLOSED ||
                                    answer.ErrorCode() == ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION)
                                {
                                    Console.Write("|");
                                }
                                else
                                {
                                    Console.Write("?");
                                }
                            }
                            else
                            {
                                Console.Write("^");
                            }
                        }
                        else
                        {
                            Console.Write("?");
                        }

                        break;
                    }

                    case 1:
                    {
                        Console.Write("&");
                        bool status = client.SendQuest(GenQuest(), (Answer answer, int errorCode) => {
                                if (errorCode == 0)
                                {
                                    Console.Write("$");
                                }
                                else if (errorCode == ErrorCode.FPNN_EC_CORE_CONNECTION_CLOSED || errorCode == ErrorCode.FPNN_EC_CORE_INVALID_CONNECTION)
                                {
                                    Console.Write(";");
                                }
                                else
                                {
                                    Console.Write("@");
                                }
                            });
                        if (status == false)
                        {
                            Console.Write("@");
                        }

                        break;
                    }

                    case 2:
                    {
                        Console.Write("!");
                        client.Close();
                        break;
                    }
                    }
                }
            }
        void WebSocket_Error(object sender, ClientEngine.ErrorEventArgs e)
        {
            if (e.Exception != null)
            {
                if (e.Exception is SocketException && ((SocketException)e.Exception).ErrorCode == (int)SocketError.AccessDenied)
                    ErrorMessage = (new SocketException((int)SocketError.ConnectionRefused)).Message;
                else
                    ErrorMessage = e.Exception.StackTrace;

                if (m_WebSocket.State == WebSocketState.None && State == NodeState.Connecting)
                {
                    State = NodeState.Offline;
                    OnDisconnected();
                }
            }
        }
Exemple #38
0
    public MainWindow(string tp, string dp, string ep, StatusIcon si)
        : base(Gtk.WindowType.Toplevel)
    {
        Build ();
        this.tp = tp;
        this.dp = dp;
        this.si = si;
        this.ep = ep;
        dhtpath = ep+ "/dht.data";
        fastResumePath = ep+"/FastResume.Data";
        EngineSettings es = new EngineSettings ();
        es.PreferEncryption = false;
        es.AllowedEncryption = EncryptionTypes.All;

        managers = new List<TorrentManager>();
        engine = new MonoTorrent.Client.ClientEngine (es);

        engine.StatsUpdate += UpdateAll;

        nodeview2.NodeStore = new NodeStore (typeof(TorrentInfoRow));
        nodeview2.AppendColumn ("Status", new Gtk.CellRendererText (), "text", 0);
        nodeview2.AppendColumn ("Progress",  new CellRendererProgressBar(), "value", 4);
        nodeview2.AppendColumn ("Ds" + "(КБ/с)", new Gtk.CellRendererText (), "text", 2);
        nodeview2.AppendColumn ("Us" + "(КБ/с)", new Gtk.CellRendererText (), "text", 3);
        nodeview2.AppendColumn ("Seeds", new Gtk.CellRendererText (), "text", 5);

        jBox = new Gtk.Menu ();
        Gtk.MenuItem MenuItem1 = new MenuItem ("Запустить");
        MenuItem1.ButtonReleaseEvent += HandleMenuItem1ButtonReleaseEvent;
        jBox.Add (MenuItem1);
        Gtk.MenuItem MenuItem4 = new MenuItem ("Пауза");
        MenuItem4.ButtonReleaseEvent += HandleMenuItem4ButtonReleaseEvent;
        Gtk.MenuItem MenuItem2 = new MenuItem ("Остановить");
        MenuItem2.ButtonReleaseEvent += HandleMenuItem2ButtonReleaseEvent;
        jBox.Add (MenuItem2);
        Gtk.MenuItem MenuItem5 = new MenuItem ("Открыть Папку...");
        MenuItem5.ButtonReleaseEvent += HandleMenuItem5ButtonReleaseEvent;
        jBox.Add (MenuItem5);
        MenuItem3 = new MenuItem ("Открыть Файл");
        MenuItem3.Sensitive = false;
        MenuItem3.ButtonReleaseEvent += HandleMenuItem3ButtonReleaseEvent;
        jBox.Add (MenuItem3);
        Gtk.MenuItem MenuItem6 = new MenuItem ("Удалить торрент");
        MenuItem6.ButtonReleaseEvent += HandleMenuItem6ButtonReleaseEvent;;
        jBox.Add (MenuItem6);
        Gtk.MenuItem MenuItem7 = new MenuItem ("Удалить торрент и файлы");
        MenuItem7.ButtonReleaseEvent += HandleMenuItem7ButtonReleaseEvent;;
        jBox.Add (MenuItem7);

        foreach (string file in Directory.GetFiles (tp))
        {
            if (file.EndsWith (".torrent"))
            {
                try
                {
                    LoadTorrent (file);
                } catch (Exception e)
                {
                    File.WriteAllText(ep+"/Error.txt","Couldn't decode: "+file);
                    XenoTorrent.TorrentError ts = new XenoTorrent.TorrentError (e.Message,file);
                    ts.Show ();
                    continue;
                }
            }
        }
        //engine.StopAll();
        LoadFastResume(managers);
        newTorrents = new int[managers.Count];
        StartDht (22334);
        // Working only with Gtk.Window object! (except [GLib.ConnectBeforeAttribute] attribute is defined on callback method)
        nodeview2.ButtonPressEvent += HandleNodeview2ButtonPressEvent;

        nodeview2.ShowAll ();

        engine.LocalPeerSearchEnabled = true;

        engine.StartAll ();
    }