コード例 #1
0
ファイル: Tracker.cs プロジェクト: clockworkengineer/dotNET
 /// <summary>
 /// Stop announcing to tracker..
 /// </summary>
 public void StopAnnouncing()
 {
     try
     {
         if (trackerStatus == TrackerStatus.Running)
         {
             if (announceTimer != null)
             {
                 announceTimer.Stop();
                 announceTimer.Dispose();
                 announceTimer = null;
                 CallBack      = null;
                 CallBackData  = null;
             }
             trackerStatus = TrackerStatus.Stopped;
         }
         else
         {
             throw new Exception("Tracker is not running so cannot be stopped.");
         }
     }
     catch (Exception ex)
     {
         Log.Logger.Error(ex);
         trackerStatus = TrackerStatus.Stalled;
         throw new BitTorrentException("" + ex.Message);
     }
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: der-dirk/LyncFellow
        public ApplicationContext()
        {
            if (Properties.Settings.Default.CallUpgrade)
              {
            Properties.Settings.Default.Upgrade();
            Properties.Settings.Default.CallUpgrade = false;
            Properties.Settings.Default.Save();
              }

              _components = new System.ComponentModel.Container();
              _notifyIcon = new NotifyIcon(_components)
              {
            ContextMenuStrip = new ContextMenuStrip(),
            Visible = true
              };
              _notifyIcon.ContextMenuStrip.Items.Add(new ToolStripMenuItem("Settings", null, new EventHandler(MenuSettingsItem_Click)));
              _notifyIcon.ContextMenuStrip.Items.Add(new ToolStripMenuItem("Exit", null, new EventHandler(MenuExitItem_Click)));

              _buddies = new Buddies();

              _housekeepingTimer = new System.Windows.Forms.Timer();
              _housekeepingTimer.Interval = 5000;
              _housekeepingTimer.Tick += HousekeepingTimer_Tick;
              HousekeepingTimer_Tick(null, null);     // tick anyway enables timer when finished

              _trackerStatus = TrackerStatus.OK;

              if (trackersConfigured())
              {
            _trackerStatus = TrackerStatus.UNKNOWN;
            UpdateTrackerSetting();
              }

              _viewModel = new ViewModel(_buddies);
        }
コード例 #3
0
        private void UpdateStatue(TrackerStatus status, string statusMsg)
        {
            Status    = status;
            StatusMsg = statusMsg;

            if (StatusChanged != null)
            {
                StatusChanged(this, new EventArgs());
            }
        }
コード例 #4
0
ファイル: Tracker.cs プロジェクト: clockworkengineer/dotNET
 /// <summary>
 /// Initialise BitTorrent Tracker.
 /// </summary>
 /// <param name="tc"></param>
 public Tracker(TorrentContext tc)
 {
     trackerStatus   = TrackerStatus.Stopped;
     PeerID          = BitTorrentLibrary.PeerID.Get();
     Ip              = Host.GetIP();
     _tc             = tc ?? throw new ArgumentNullException(nameof(tc));
     _tc.MainTracker = this;
     InfoHash        = tc.infoHash;
     TrackerURL      = tc.trackerURL;
     _announcer      = new AnnouncerFactory().Create(TrackerURL);
 }
コード例 #5
0
ファイル: Tracker.cs プロジェクト: clockworkengineer/dotNET
 /// <summary>
 /// Starts the announce requests to tracker.
 /// </summary>
 public void StartAnnouncing()
 {
     try
     {
         //  Swarm queue needs to be initialised
         if (peerSwarmQueue == null)
         {
             throw new Exception("Peer swarm queue has not been set.");
         }
         if (trackerStatus != TrackerStatus.Running)
         {
             // If all of torrent downloaded reset total bytes downloaded
             if (Left == 0)
             {
                 _tc.TotalBytesDownloaded = 0;
                 _tc.TotalBytesToDownload = 0;
                 ChangeStatus(TrackerEvent.None);
             }
             else
             {
                 ChangeStatus(TrackerEvent.started);
             }
             if (lastResponse.failure)
             {
                 trackerStatus = TrackerStatus.Stalled;
                 throw new Exception("Tracker failure: " + lastResponse.statusMessage);
             }
             announceTimer           = new System.Timers.Timer(Interval);
             announceTimer.Elapsed  += (sender, e) => OnAnnounceEvent(this);
             announceTimer.AutoReset = false;
             announceTimer.Enabled   = true;
             announceTimer?.Start();
             trackerStatus = TrackerStatus.Running;
         }
         else
         {
             throw new BitTorrentException("Tracker cannot be started as is already running.");
         }
     }
     catch (BitTorrentException)
     {
         throw;
     }
     catch (Exception ex)
     {
         trackerStatus = TrackerStatus.Stalled;
         Log.Logger.Error(ex);
         throw new BitTorrentException(ex.Message);
     }
 }
コード例 #6
0
        public void Stop()
        {
            if (Status == TrackerStatus.Started)
            {
                t.Stop();

                while (Peers.Count > 0)
                {
                    var peer = Peers.First();
                    peer.Disconnect();
                }
                Connection.StopListening();
                NetworkComms.Shutdown();
                NetworkComms.Logger.Warn("===== Tracker stopped =====");
                Status = TrackerStatus.Stopped;
            }
        }
コード例 #7
0
        public Tracker()
        {
            this.Peers  = new List <Peer>();
            this.Status = TrackerStatus.Stopped;

            t = new Timer(CommonHelpers.CheckAliveInterval);

            NetworkComms.DisableLogging();
            if (File.Exists("BlockChainVotingsTracker_log.txt"))
            {
                File.Delete("BlockChainVotingsTracker_log.txt");
            }
            LiteLogger logger = new LiteLogger(LiteLogger.LogMode.ConsoleAndLogFile, "BlockChainVotingsTracker_log.txt");

            NetworkComms.EnableLogging(logger);

            NetworkComms.AppendGlobalConnectionEstablishHandler(OnConnectPeer);
        }
コード例 #8
0
        public void Start()
        {
            if (Status == TrackerStatus.Stopped)
            {
                try
                {
                    TCPConnection.StartListening(CommonHelpers.GetLocalEndPoint(CommonHelpers.TrackerPort), false);
                    Status = TrackerStatus.Started;
                }
                catch
                {
                    NetworkComms.Logger.Error("Can't start listener on this IP: " + CommonHelpers.GetLocalEndPoint(CommonHelpers.TrackerPort).ToString());
                }

                NetworkComms.Logger.Warn("===== Tracker started =====");

                t.Start();
            }
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: der-dirk/LyncFellow
        private void UpdateTrackerSetting()
        {
            // Remove old watchers
              for (int i = 0; i < _watchers.Count; ++i)
              {
            _watchers[i].EnableRaisingEvents = false;
            _watchers[i] = null;
              }
              _watchers.Clear();

              List<string> trackerPaths = getTrackerPaths();

              // Add new watchers
              if (trackerPaths.Count > 0)
              {
            for (int i = 0; i < trackerPaths.Count; ++i)
            {
              string trackerPath = trackerPaths[i];

              FileSystemWatcher watcher = new FileSystemWatcher();
              _watchers.Add(watcher);

              /* Watch for changes in LastAccess and LastWrite times, and
              the renaming of files or directories. */
              watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

              // Add event handlers.
              watcher.Changed += new FileSystemEventHandler(OnChanged);
              watcher.Created += new FileSystemEventHandler(OnChanged);
              watcher.Deleted += new FileSystemEventHandler(OnChanged);
              watcher.Renamed += new RenamedEventHandler(OnRenamed);

              QueryTrackerFile();

              try
              {
            watcher.Path = Path.GetDirectoryName(trackerPath);
            watcher.Filter = Path.GetFileName(trackerPath);
            watcher.EnableRaisingEvents = true;
              }
              catch (Exception ex)
              {
            Console.WriteLine("{0}", ex.ToString());
            _trackerStatus = TrackerStatus.UNKNOWN;
              }
            }
              }
              else
              {
            _trackerStatus = TrackerStatus.OK;
              }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: der-dirk/LyncFellow
        private void QueryTrackerFile()
        {
            TrackerStatus newStatus = TrackerStatus.UNKNOWN;
              try
              {
            List<string> trackerpaths = getTrackerPaths();
            foreach (string trackerPath in trackerpaths)
            {
              using (var fs = new FileStream(trackerPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
              {
            using (var sr = new StreamReader(fs, Encoding.UTF8, true, 1024))
            {
              string lineOfText;
              while ((lineOfText = sr.ReadLine()) != null)
              {
                newStatus = (lineOfText.IndexOf("Compile OK") != -1) ? TrackerStatus.OK : TrackerStatus.ERROR;
                Console.WriteLine(lineOfText);
              }

              // "ERROR" wins
              if (newStatus == TrackerStatus.ERROR)
                break;
            }
              }
            }

              }
              catch (Exception ex)
              {
            Console.WriteLine("{0}", ex.ToString());
            newStatus = TrackerStatus.UNKNOWN;
              }

              if (_trackerStatus != newStatus)
              {
            _trackerStatus = newStatus;
            _buddies.Heartbeat();
            UpdateBuddiesColor();
              }
        }
コード例 #11
0
		public List<TrackerType> GetTrackerTypesByStatus (TrackerStatus status)
		{ 
			return TrackerTypes.Values.Where(t => t.Status() == status).ToList();
		}
コード例 #12
0
        /// <summary>
        /// Announces to this tracker group.
        /// This should be done in regular intervals.
        /// </summary>
        /// <returns>The announce response.</returns>
        public async Task <AnnounceResponse> Announce(TrackerEvent trackerEvent)
        {
            // If there are no trackers to announce to
            if (trackers.Count == 0)
            {
                return(null);
            }
            // Don't bother announcing if we are not listening for peers
            else if (!PeerListener.IsListening)
            {
                return(null);
            }
            else if (isAnnouncing)
            {
                return(null);
            }

            try
            {
                if (currentIndex > trackers.Count)
                {
                    currentIndex = 0;
                }

                // Select the tracker
                var tracker = trackers[currentIndex];
                isAnnouncing = true;

                // If we haven't sent started event yet, we make sure to send started event first
                if (!hasSentStartedEvent)
                {
                    // If we are sending stopped and haven't sent started, then we don't have to bother
                    if (trackerEvent == TrackerEvent.Stopped)
                    {
                        return(null);
                    }

                    trackerEvent = TrackerEvent.Started;
                }

                // If we stop the tracker, we have to send a started event again on next announce
                if (trackerEvent == TrackerEvent.Stopped)
                {
                    hasSentStartedEvent = false;
                }

                int listenPort = PeerListener.Port;
                announceRequest.Port            = listenPort;
                announceRequest.TrackerEvent    = trackerEvent;
                announceRequest.BytesDownloaded = torrent.SessionDownloadedBytes;
                announceRequest.BytesUploaded   = torrent.SessionUploadedBytes;
                announceRequest.BytesLeft       = torrent.BytesLeftToDownload;

                var announceResponse = await tracker.Announce(announceRequest);

                status         = tracker.Status;
                failureMessage = tracker.FailureMessage;
                warningMessage = tracker.WarningMessage;

                if (status == TrackerStatus.OK)
                {
                    var timeNow = DateTime.UtcNow;
                    nextAnnounceTime        = timeNow.Add(tracker.Interval);
                    nextAnnounceTimeMinimum = timeNow.Add(tracker.MinInterval);

                    if (!hasSentStartedEvent && trackerEvent == TrackerEvent.Started)
                    {
                        hasSentStartedEvent = true;
                    }

                    int trackerIndex = trackers.IndexOf(tracker);
                    if (trackerIndex != -1)
                    {
                        // If we get an OK we put this tracker first in the list
                        if (trackerIndex > 0)
                        {
                            trackers.RemoveAt(trackerIndex);
                            trackers.Insert(0, tracker);
                        }
                        currentIndex = 0;
                    }
                    else
                    {
                        // The tracker has been removed from the group
                        currentIndex = 0;
                    }
                }
                else
                {
                    currentIndex = (currentIndex + 1) % trackers.Count;

                    if (currentIndex == 0)
                    {
                        var timeNow = DateTime.UtcNow;
                        nextAnnounceTime        = timeNow.Add(TimeSpan.FromMinutes(5.0));
                        nextAnnounceTimeMinimum = timeNow.Add(TimeSpan.FromMinutes(1.0));
                    }
                }
                return(announceResponse);
            }
            catch (Exception ex)
            {
                failureMessage = ex.Message;
                currentIndex   = (currentIndex + 1) % trackers.Count;
                Log.LogErrorException(ex);
                return(null);
            }
            finally
            {
                isAnnouncing = false;
            }
        }
コード例 #13
0
        private static void Track(HttpContext context)
        {
            string strDocId    = context.Request["DocId"];
            string strFileName = DBStore.GetDocName(strDocId);
            string strBody     = "";
            string strStatus   = "0";

            try
            {
                using (var receiveStream = context.Request.InputStream)
                {
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        strBody = readStream.ReadToEnd();
                    }
                }

                DBStore.AddStatus(strDocId, "WebEditor.Track", strBody);
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            if (string.IsNullOrEmpty(strBody))
            {
                return;
            }

            JavaScriptSerializer        jss         = new JavaScriptSerializer();
            Dictionary <string, object> dicResponse = jss.Deserialize <Dictionary <string, object> >(strBody);

            string        strDocKey          = "";
            int           intStatusVal       = 0;
            TrackerStatus enumStatus         = TrackerStatus.NotFound;
            string        strFileDownloadUrl = "";
            string        strUser            = "";

            if (dicResponse.ContainsKey("key"))
            {
                strDocKey = dicResponse["key"].ToString();
            }

            if (dicResponse.ContainsKey("status"))
            {
                intStatusVal = Convert.ToInt32(dicResponse["status"]);
                enumStatus   = (TrackerStatus)intStatusVal;
            }

            if (dicResponse.ContainsKey("url"))
            {
                strFileDownloadUrl = dicResponse["url"].ToString();
            }

            if (dicResponse.ContainsKey("users"))
            {
                strUser = (dicResponse["users"] as ArrayList)[0].ToString();
            }

            DBStore.UpdateDocStatus(strDocId, "", "WebEditor.Track: " + enumStatus + " : " + intStatusVal.ToString());
            DBStore.AddStatus(strDocId, "strDocKey", strDocKey);
            DBStore.AddStatus(strDocId, "strUser", strUser);
            DBStore.AddStatus(strDocId, "strFileDownloadUrl", strFileDownloadUrl);

            switch (enumStatus)
            {
            case TrackerStatus.MustSave:
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strFileDownloadUrl);

                try
                {
                    var storagePath = Sample.StoragePath(strFileName);

                    if (DBStore.GetDocStatus(strDocId) == "OkClicked" ||
                        DBStore.GetDocStatus(strDocId) == "EDITOR_CLOSED")
                    {
                        //--- This is the document stream sent from Document Service
                        using (var stream = req.GetResponse().GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new Exception("stream is null");
                            }
                            const int bufferSize = 4096;

                            using (var fs = File.Open(storagePath, FileMode.Create))
                            {
                                var buffer = new byte[bufferSize];
                                int readed;
                                while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                                {
                                    fs.Write(buffer, 0, readed);
                                }
                            }
                        }

                        DBStore.UpdateDocStatus(strDocId, enumStatus.ToString(), "WebEditor.Track: Saved Path: " + storagePath);

                        DBStore.AddStatus(strDocId, "Command Service", "Start");
                        string strRes = ServiceConverter.GetCommandService("drop", strDocKey, "", (new List <string>()
                        {
                            strUser
                        }));
                        DBStore.AddStatus(strDocId, "Command Service", strRes);
                    }
                    else
                    {
                        DBStore.UpdateDocStatus(strDocId, enumStatus.ToString(), "WebEditor.Track: NOT SAVED");
                    }
                }
                catch (Exception ex)
                {
                    DBStore.AddStatus(strDocId, "Exception", ex.ToString());
                }

                break;

            case TrackerStatus.Corrupted:
            case TrackerStatus.ForceSave:
            case TrackerStatus.Closed:
                break;

            case TrackerStatus.Editing:
                //--- Check User and Key combination and set the status of document
                strStatus = "0";
                break;
            }

            context.Response.Write("{\"error\":" + strStatus + "}");
        }
コード例 #14
0
ファイル: UdpTracker.cs プロジェクト: Whinarn/TorrentSwifter
 public TrackerException(TrackerStatus status, string message)
     : base(message)
 {
     this.status = status;
 }