Пример #1
0
 public ListUsersQueryHandler(DatabaseContext context, IMapper mapper, ConnectionHub connectionHub, IOperationContext operationContext)
 {
     _context          = context;
     _mapper           = mapper;
     _connectionHub    = connectionHub;
     _operationContext = operationContext;
 }
Пример #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseDefaultFiles();
            app.UseFileServer(enableDirectoryBrowsing: true);
            app.UseWebSockets(); // Only for Kestrel

            app.Map("/ws", builder =>
            {
                builder.Use(async(context, next) =>
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                        await ConnectionHub.Echo(webSocket);
                        return;
                    }
                    await next();
                });
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
Пример #3
0
        public HandlerExchange(ConnectionHub connMan, PeerStateCache stateCache)
        {
            _conMan             = connMan;
            _stateCache         = stateCache;
            _uploaderPool       = new BlockingCollection <PeerHandler>();
            _myCancelTokenOwner = new CancellationTokenSource();

            _curPoolUploaders   = new ConcurrentDictionary <string, PeerHandler>();
            _curPoolDownloaders = new ConcurrentDictionary <string, PeerHandler>();

            _acuqireNewHandlerTask = null;

            JobManager.AddJob(OptimisticUnchoke, (s) => s.ToRunEvery(OptimisticUcnhokeInSecs).Seconds());
            JobManager.AddJob(TryRefreshDownloaderPool, (s) => s.ToRunEvery(DownloaderPoolRefreshInSecs).Seconds());
        }
Пример #4
0
        public static void Main(string[] args)
        {
            // Load configuration
            var config = new PeerConnectConfiguration();

            if (File.Exists(ConfigFileName))
            {
                JsonConvert.PopulateObject(File.ReadAllText(ConfigFileName), config);
            }
            // Create and start hub
            var connectionHub = new ConnectionHub();

            connectionHub.Start();
            // Attempt to connect to clients
            connectionHub.PeerConnected += (s, e) =>
            {
                Console.WriteLine($"Connected to {e.Peer.Endpoint}");
            };
            var peerConnectResult = connectionHub.ConnectPeers(config.ConnectionInformation);
        }
Пример #5
0
        private Score UpdateScore(int scoreId, int newValue,
                                  IScoreRepository scoreRepository,
                                  IBracketRepository bracketRepository,
                                  ITeamRepository teamRepository)
        {
            var score   = scoreRepository.GetScoreByID(scoreId);
            var bracket = bracketRepository.GetBracketByID(score.BracketID);

            if (!bracket.Finished && newValue >= 0)
            {
                score.Value = newValue;
                scoreRepository.UpdateScore(score);
            }

            ConnectionHub.SendToAll(UPDATE);

            var scores = (List <Score>)scoreRepository.GetScores(_ => _.BracketID == score.BracketID);
            var score1 = scores[0];
            var score2 = scores[1];
            var team   = teamRepository.GetTeamByID(score.TeamID);
            var team1  = teamRepository.GetTeamByID(score1.TeamID);
            var team2  = teamRepository.GetTeamByID(score2.TeamID);

            var body = string.Format("{0} ({1}) - ({2}) {3}", team1.Name, score1.Value, score2.Value, team2.Name);

            var notification = new Notification()
            {
                Title  = string.Format("{0} scored!", team.Name),
                Body   = body,
                Params = { bracket.TournamentID.ToString() }
            };

            PushHub.Send(notification);

            return(score);
        }
Пример #6
0
        /// <summary>
        /// Creates new BtClient
        /// </summary>
        /// <param name="meta">Torrent metainfo</param>
        /// <param name="clientEndPoint">Client's external network endpoint. Must be accessible by other peers</param>
        /// <param name="defaultEncoding">Message text encoding</param>
        /// <param name="output">Output stream. If torrent contains multiple files </param>
        /// <param name="blockLen">Piece block length in bytes. 10^14 bytes if not specified</param>
        /// <param name="fileName">File name to download. If not specified all files will be downloaded</param>
        /// <param name="dhtEndPoint">Mainline DHT's client endpoint. DHT will not be used if parameter is null</param>
        /// <param name="storage">Storage for caching pieces. If not specified MemCachedPieceStorage will be used</param>
        /// <param name="cancelToken">Requesting cancel on this CancellationToken causes forcefull shutdown of client</param>
        public BtClient(Metainfo meta, IPEndPoint clientEndPoint, Encoding defaultEncoding, Stream output, int blockLen = 16384, string fileName = null, PiecePickStrategy piecePickStrategy = PiecePickStrategy.RarestFirst, IPEndPoint dhtEndPoint = null, IPieceStorage storage = null, CancellationToken?cancelToken = null)
        {
            Metainfo           = meta;
            _endPoint          = clientEndPoint;
            DefaultEncoding    = defaultEncoding;
            _peerId            = GeneratePeerId();
            Handshake          = CalcHandshake();
            BlockLength        = blockLen;
            BlocksInPieceCount = Metainfo.PieceLength / BlockLength;

            AnnounceManager = new AnnounceManager(this, Metainfo.Announces);
            IResourcePool <Peers.Peer> peersPool = AnnounceManager;

            if (dhtEndPoint != null)
            {
                MainlineManager = new MainlineManagerExt(clientEndPoint, dhtEndPoint, meta.InfoHash);

                peersPool = new MergedPool <Peer>(new IResourcePool <Peer>[] {
                    AnnounceManager,
                    MainlineManager
                });
            }

            if (storage == null)
            {
                storage = new FileStorage(Metainfo, BlockLength);
            }

            PieceStorage = storage;
            BitField piecesHave = PieceStorage.GetValidPieces();

            IRequestStrategy rqStrat = null;

            switch (piecePickStrategy)
            {
            case PiecePickStrategy.RarestFirst:
                RarestFirstRqStrategy rarestFirstRqStrategy = new RarestFirstRqStrategy(Metainfo.PiecesCount, piecesHave);
                rqStrat        = rarestFirstRqStrategy;
                PeerStateCache = new PeerStateCache(rarestFirstRqStrategy);
                break;

            case PiecePickStrategy.Random:
                rqStrat = new RandomPieceRqStrategy(Metainfo.PiecesCount, piecesHave);
                break;

            case PiecePickStrategy.Sequential:
                rqStrat = new SequentialPieceRqStrategy(Metainfo.PiecesCount);
                break;

            case PiecePickStrategy.SequentialOneFile:
                if (string.IsNullOrEmpty(fileName))
                {
                    throw new ArgumentException("fileName");
                }

                rqStrat = new SequentialPieceRqStrategyOneFile(Metainfo, fileName);
                break;

            default:
                break;
            }

            if (PeerStateCache == null)
            {
                PeerStateCache = new PeerStateCache();
            }

            ConnectionManager = new ConnectionHub(this, clientEndPoint, peersPool, PeerStateCache);

            HandlerExchange = new HandlerExchange(ConnectionManager, PeerStateCache);

            PiecePicker = new PiecePicker(this, HandlerExchange, rqStrat, BlockLength, cancelToken);
        }
Пример #7
0
        private Bracket UpdateBracket(Bracket bracket, bool finished,
                                      int bracketId,
                                      IBracketRepository bracketRepository,
                                      IScoreRepository scoreRepository,
                                      ITeamRepository teamRepository)
        {
            if (!bracket.Finished)
            {
                bracket.Finished = finished;
                bracketRepository.UpdateBracket(bracket);
            }
            var brackets    = (List <Bracket>)bracketRepository.GetBrackets(_ => _.TournamentID == bracket.TournamentID);
            var notFinished = brackets.Where(b => b.Finished == false).ToList();

            if (brackets.Any() && !notFinished.Any())
            {
                var lowestLevel = brackets.OrderBy(b => b.Level).First().Level;
                if (lowestLevel > 0)
                {
                    var filteredBrackets = brackets.Where(b => b.Level == lowestLevel).ToList();
                    for (var index = 0; index + 1 < filteredBrackets.Count; index += 2)
                    {
                        var newBracket = new Bracket()
                        {
                            Level        = lowestLevel - 1,
                            Finished     = false,
                            TournamentID = bracket.TournamentID
                        };
                        var createdBracket = bracketRepository.InsertBracket(newBracket);

                        var bracketA        = filteredBrackets[index];
                        var bracketB        = filteredBrackets[index + 1];
                        var winnerAID       = FindWinnerID(bracketA.ID, scoreRepository);
                        var winnerBID       = FindWinnerID(bracketB.ID, scoreRepository);
                        var winnerIDs       = new int[] { winnerAID, winnerBID };
                        var teamsPerBracket = 2;
                        for (var x = 0; x < teamsPerBracket; x++)
                        {
                            var newScore = new Score()
                            {
                                BracketID = createdBracket.ID,
                                TeamID    = winnerIDs[x],
                                Value     = 0
                            };
                            scoreRepository.InsertScore(newScore);
                        }
                    }
                }
            }

            ConnectionHub.SendToAll(UPDATE);

            var scores = (List <Score>)scoreRepository.GetScores(_ => _.BracketID == bracketId);
            var score1 = scores[0];
            var score2 = scores[1];
            var team1  = teamRepository.GetTeamByID(score1.TeamID);
            var team2  = teamRepository.GetTeamByID(score2.TeamID);

            var body = string.Format("{0} ({1}) - ({2}) {3}", team1.Name, score1.Value, score2.Value, team2.Name);

            var notification = new Notification()
            {
                Title  = "A bracket was finished!",
                Body   = body,
                Params = { bracket.TournamentID.ToString() }
            };

            PushHub.Send(notification);

            return(bracket);
        }
Пример #8
0
        private Tournament CreateTournament(
            ITournamentRepository tournamentRepository,
            ITeamRepository teamRepository,
            IBracketRepository bracketRepository,
            IScoreRepository scoreRepository,
            Tournament tournament,
            Team[] teamsNames,
            int categoryId,
            int userId
            )
        {
            tournament.CategoryID      = categoryId;
            tournament.AdministratorID = userId;
            var createdTournament = tournamentRepository.InsertTournament(tournament);

            var initialLevel = (int)Math.Log2(teamsNames.Length) - 1;

            for (int i = 0; i + 1 < teamsNames.Length; i += 2)
            {
                var team1 = new Team
                {
                    Name = teamsNames[i].Name
                };
                var team2 = new Team
                {
                    Name = teamsNames[i + 1].Name
                };
                var createdTeam1 = teamRepository.InsertTeam(team1);
                var createdTeam2 = teamRepository.InsertTeam(team2);
                if (i % 2 == 0)
                {
                    var bracket = new Bracket
                    {
                        Level      = initialLevel,
                        Finished   = false,
                        Tournament = createdTournament
                    };
                    var createdBracket = bracketRepository.InsertBracket(bracket);
                    var score1         = new Score
                    {
                        Value   = 0,
                        Team    = createdTeam1,
                        Bracket = createdBracket
                    };
                    var score2 = new Score
                    {
                        Value   = 0,
                        Team    = createdTeam2,
                        Bracket = createdBracket
                    };
                    scoreRepository.InsertScore(score1);
                    scoreRepository.InsertScore(score2);
                }
            }

            ConnectionHub.SendToAll(UPDATE);

            var notification = new Notification()
            {
                Title  = "New tournament created!",
                Body   = createdTournament.Name,
                Params = { createdTournament.ID.ToString() }
            };

            PushHub.Send(notification);

            return(createdTournament);
        }
Пример #9
0
        public override V3Message execute(Request message, RequestContext context)
        {
            object returnValue = null;

            switch (operation)
            {
            case SUBSCRIBE_OPERATION:
            {
                IDestination destObj =
                    ORBConfig.GetInstance().GetDataServices().GetDestinationManager().GetDestination(destination);
                Hashtable headers = new Hashtable();

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (destObj != null)
                {
                    String selectorName = (String)this.headers["DSSelector"];
                    String subtopic     = (String)this.headers["DSSubtopic"];
                    String dsId         = connection == null ? (String)this.headers["DSId"] : connection.GetHashCode().ToString();
                    String channel      = (String)this.headers["DSEndpoint"];

                    Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
                        Subscriber.buildId(dsId, destObj.GetName(), subtopic, selectorName));

                    if (clientId == null || clientId.Equals(""))
                    {
                        clientId = Guid.NewGuid().ToString().ToUpper();
                    }

                    if (subscriber != null)
                    {
                        if (subscriber.addClient(clientId.ToString()))
                        {
                            destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);
                        }

                        return(new AckMessage(messageId, clientId, null, headers));
                    }

                    object wsContext = ThreadContext.getProperties()[ORBConstants.WEB_SOCKET_MODE];

                    if (wsContext != null)
                    {
                        subscriber = new WebSocketSubscriber(selectorName, destObj, (UserContext)wsContext);
                    }
                    else if (connection != null)
                    {
                        subscriber = new DedicatedSubscriber(selectorName, destObj);
                        subscriber.setChannelId(RTMPHandler.getChannelId());
                        subscriber.setConnection(connection);
                    }
                    else
                    {
                        subscriber = SubscriberFactory.CreateSubscriber(channel, selectorName, destObj);
                    }

                    subscriber.setDSId(dsId);
                    subscriber.setSubtopic(subtopic);
                    subscriber.addClient((String)clientId);

                    try
                    {
                        SubscriptionsManager.GetInstance().AddSubscriber(dsId, destObj.GetName(), subscriber);
                    }
                    catch (Exception e)
                    {
                        if (Log.isLogging(LoggingConstants.EXCEPTION))
                        {
                            Log.log(LoggingConstants.EXCEPTION, e);
                        }
                    }

                    destObj.GetServiceHandler().HandleSubscribe(subscriber, clientId.ToString(), this);
                }
                else
                {
                    String error = "Unknown destination " + destination + ". Cannot handle subscription request";

                    if (Log.isLogging(LoggingConstants.ERROR))
                    {
                        Log.log(LoggingConstants.ERROR, error);
                    }

                    return(new ErrMessage(messageId, new Exception(error)));
                }

                return(new AckMessage(messageId, clientId, null, headers));
            }
            break;

            case UNSUBSCRIBE_OPERATION:
            {
                String subtopic     = (String)this.headers["DSSubtopic"];
                String dsId         = (String)this.headers["DSId"];
                String selectorName = (String)this.headers["DSSelector"];

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString();
                }

                Subscriber subscriber = SubscriptionsManager.GetInstance().getSubscriber(
                    Subscriber.buildId(dsId, destination, subtopic, selectorName));

                if (subscriber != null)
                {
                    SubscriptionsManager.GetInstance().unsubscribe(subscriber, clientId.ToString(), this);
                }
            }
            break;

            case DISCONNECT_OPERATION:
            {
                String         dsId       = (String)this.headers["DSId"];
                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString();
                }

                SubscriptionsManager subscriptionsManager = SubscriptionsManager.GetInstance();
                List <Subscriber>    subscribers          = subscriptionsManager.getSubscribersByDsId(dsId);

                if (subscribers != null)
                {
                    foreach (Subscriber subscriber in subscribers)
                    {
                        if (subscriber != null)
                        {
                            subscriptionsManager.unsubscribe(subscriber, this);
                        }
                    }
                }

                subscriptionsManager.removeSubscriber(dsId);
            }
            break;

            case POLL_OPERATION:
            {
                String dsId = (String)this.headers["DSId"];

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();

                if (connection != null)
                {
                    dsId = connection.GetHashCode().ToString() + "";
                }

                try
                {
                    WebORBArray <V3Message> messages =
                        new WebORBArray <V3Message>(SubscriptionsManager.GetInstance().getMessages(dsId));

                    if (messages.Count == 0)
                    {
                        return(new AckMessage(null, null, null, new Hashtable()));
                    }

                    return(new CommandMessage(CLIENT_SYNC_OPERATION, messages));
                }
                catch (Exception e)
                {
                    String error = "Invalid client id " + dsId;

                    if (Log.isLogging(LoggingConstants.ERROR))
                    {
                        Log.log(LoggingConstants.ERROR, error, e);
                    }

                    return(new ErrMessage(messageId, new Exception(error)));
                }
            }
            break;

            case CLIENT_PING_OPERATION:
            {
                Hashtable headers = new Hashtable();

                RTMPConnection connection = (RTMPConnection)ConnectionHub.getConnectionLocal();
                if (connection != null)
                {
                    headers.Add("DSId", connection.GetHashCode().ToString());
                }
                else
                {
                    headers.Add("DSId", Guid.NewGuid().ToString().ToUpper());
                }

                return(new AckMessage(messageId, clientId, null, headers));
            }
            break;

            case LOGOUT_OPERATION:
            {
                ThreadContext.setCallerCredentials(null, null);
                Thread.CurrentPrincipal = null;
            }
            break;

            case LOGIN_OPERATION:
            {
                String credentials = (String)((IAdaptingType)((object[])body.body)[0]).defaultAdapt();
                byte[] bytes       = Convert.FromBase64String(credentials);
                credentials = new String(Encoding.UTF8.GetChars(bytes));
                IAuthenticationHandler authHandler = ORBConfig.GetInstance().getSecurity().GetAuthenticationHandler();

                if (authHandler == null)
                {
                    ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Missing authentication handler"));
                    errorMessage.faultCode = "Client.Authentication";
                    return(errorMessage);
                }

                int    index    = credentials.IndexOf(":");
                string userid   = null;
                string password = null;

                if (index != -1 && index != 0 && index != credentials.Length - 1)
                {
                    userid   = credentials.Substring(0, index);
                    password = credentials.Substring(index + 1);

                    try
                    {
                        IPrincipal principal = authHandler.CheckCredentials(userid, password, message);

                        try
                        {
                            Thread.CurrentPrincipal = principal;
                            ThreadContext.currentHttpContext().User = principal;
                        }
                        catch (Exception exception)
                        {
                            if (Log.isLogging(LoggingConstants.ERROR))
                            {
                                Log.log(LoggingConstants.ERROR,
                                        "Unable to set current principal. Make sure your current permission set allows Principal Control",
                                        exception);
                            }

                            throw exception;
                        }

                        Credentials creds = new Credentials();
                        creds.userid   = userid;
                        creds.password = password;
                        ThreadContext.setCallerCredentials(creds, principal);
                    }
                    catch (Exception exception)
                    {
                        ErrMessage errorMessage = new ErrMessage(messageId, exception);
                        errorMessage.faultCode = "Client.Authentication";
                        return(errorMessage);
                    }
                }
                else
                {
                    ErrMessage errorMessage = new ErrMessage(messageId, new ServiceException("Invalid credentials"));
                    errorMessage.faultCode = "Client.Authentication";
                    return(errorMessage);
                }
            }
            break;
            }

            return(new AckMessage(messageId, clientId, returnValue, new Hashtable()));
        }