/// <summary>
        /// Indicates whether is subscribed to a channel.
        /// </summary>
        /// <param name="channel">The channel name.</param>
        /// <returns>
        ///   <c>true</c> if subscribed to the channel; otherwise, <c>false</c>.
        /// </returns>
        public bool IsSubscribed(string channel)
        {
            bool result = false;

            if (!IsConnected)
            {
                DelegateExceptionCallback(new OrtcNotConnectedException("Not connected"));
            }
            else if (String.IsNullOrEmpty(channel))
            {
                DelegateExceptionCallback(new OrtcEmptyFieldException("Channel is null or empty"));
            }
            else if (!channel.OrtcIsValidInput())
            {
                DelegateExceptionCallback(new OrtcInvalidCharactersException("Channel has invalid characters"));
            }
            else
            {
                result = false;

                if (_client._subscribedChannels.ContainsKey(channel))
                {
                    ChannelSubscription channelSubscription = null;
                    _client._subscribedChannels.TryGetValue(channel, out channelSubscription);

                    if (channelSubscription != null && channelSubscription.IsSubscribed)
                    {
                        result = true;
                    }
                }
            }

            return(result);
        }
Beispiel #2
0
        public async Task ItShouldRequestSnapshotAfterUpdate()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                var trackingDatabase = new TrackingConnectionFactory(testDatabase);
                this.target          = new UnsubscribeFromChannelDbStatement(trackingDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                this.requestSnapshot.VerifyConnectionDisposed(trackingDatabase);

                await this.target.ExecuteAsync(UserId, Subscriptions[0].ChannelId);

                this.requestSnapshot.VerifyCalledWith(UserId, SnapshotType.SubscriberChannels);

                var deletion = new ChannelSubscription(
                    Subscriptions[0].ChannelId.Value,
                    null,
                    UserId.Value,
                    null,
                    Subscriptions[0].AcceptedPrice.Value,
                    PriceLastAcceptedDate,
                    SubscriptionStartDate);

                return(new ExpectedSideEffects {
                    Delete = deletion
                });
            });
        }
        public async Task WhenTheSubscriptionExists_ItShouldUpdateTheSubscription()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateChannelSubscriptionDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                await this.target.ExecuteAsync(UserId, Subscriptions[0].ChannelId, NewAcceptedPrice, Now);

                var update = new ChannelSubscription(
                    Subscriptions[0].ChannelId.Value,
                    null,
                    UserId.Value,
                    null,
                    NewAcceptedPrice.Value,
                    Now,
                    SubscriptionStartDate);

                return(new ExpectedSideEffects {
                    Update = update
                });
            });
        }
Beispiel #4
0
        public async Task WhenTheSubscriptionExists_ItShouldDeleteTheSubscription()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UnsubscribeFromChannelDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                await this.target.ExecuteAsync(UserId, Subscriptions[0].ChannelId);

                var deletion = new ChannelSubscription(
                    Subscriptions[0].ChannelId.Value,
                    null,
                    UserId.Value,
                    null,
                    Subscriptions[0].AcceptedPrice.Value,
                    PriceLastAcceptedDate,
                    SubscriptionStartDate);

                return(new ExpectedSideEffects {
                    Delete = deletion
                });
            });
        }
        public void PubSubWithDedicatedThreadWithFilter()
        {
            using (var fiber = new ThreadFiber())
            {
                fiber.Start();
                var channel = new Channel <int>();

                var          reset = new AutoResetEvent(false);
                Action <int> onMsg = x =>
                {
                    Assert.IsTrue(x % 2 == 0);
                    if (x == 4)
                    {
                        reset.Set();
                    }
                };
                var sub = new ChannelSubscription <int>(fiber, onMsg);
                sub.FilterOnProducerThread = x => x % 2 == 0;
                channel.SubscribeOnProducerThreads(sub);
                channel.Publish(1);
                channel.Publish(2);
                channel.Publish(3);
                channel.Publish(4);

                Assert.IsTrue(reset.WaitOne(5000, false));
            }
        }
        private void OnSubscribe(BitfinexWebSocketWrapper webSocket, ChannelSubscription data)
        {
            try
            {
                lock (_locker)
                {
                    var channel = new Channel(data.Channel, _symbolMapper.GetLeanSymbol(data.Symbol, SecurityType.Crypto, Market.Bitfinex));

                    BitfinexWebSocketChannels channels;
                    if (!_channelsByWebSocket.TryGetValue(webSocket, out channels))
                    {
                        _onSubscribeEvent.Set();
                        return;
                    }

                    channels.TryAdd(data.ChannelId, channel);

                    Log.Trace($"BitfinexSubscriptionManager.OnSubscribe(): Channel subscribed: Id:{data.ChannelId} {channel.Symbol}/{channel.Name}");

                    _onSubscribeEvent.Set();

                    webSocket.ConnectionHandler.EnableMonitoring(true);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
        }
Beispiel #7
0
        public async Task <IActionResult> NewSubscriber()
        {
            ChannelSubscription sub = new ChannelSubscription("{'displayName':'WilliamGates'}");

            await _hubContext.Clients.All.SendAsync("ReceiveNewSubscriber", sub);

            return(RedirectToAction("test"));
        }
        public override void Unsubscribe(string channel)
        {
            #region Sanity Checks

            bool sanityChecked = true;

            if (!IsConnected)
            {
                RaiseOnException(new OrtcException("Not connected"));
                sanityChecked = false;
            }
            else if (String.IsNullOrEmpty(channel))
            {
                RaiseOnException(new OrtcException("Channel is null or empty"));
                sanityChecked = false;
            }
            else if (!channel.OrtcIsValidInput())
            {
                RaiseOnException(new OrtcException("Channel has invalid characters"));
                sanityChecked = false;
            }
            else if (!_subscribedChannels.ContainsKey(channel))
            {
                RaiseOnException(new OrtcException(String.Format("Not subscribed to the channel {0}", channel)));
                sanityChecked = false;
            }
            else if (_subscribedChannels.ContainsKey(channel))
            {
                ChannelSubscription channelSubscription = null;
                _subscribedChannels.TryGetValue(channel, out channelSubscription);

                if (channelSubscription != null && !channelSubscription.IsSubscribed)
                {
                    RaiseOnException(new OrtcException(String.Format("Not subscribed to the channel {0}", channel)));
                    sanityChecked = false;
                }
            }
            else
            {
                byte[] channelBytes = Encoding.UTF8.GetBytes(channel);

                if (channelBytes.Length > MAX_CHANNEL_SIZE)
                {
                    RaiseOnException(new OrtcException(String.Format("Channel size exceeds the limit of {0} characters", MAX_CHANNEL_SIZE)));
                    sanityChecked = false;
                }
            }

            #endregion

            if (sanityChecked)
            {
                Task.RunOnMain(() =>
                {
                    IosOrtcClientFactory.Unsubscribe(_id, channel);
                });
            }
        }
        private void CreateSubscriptions(FifthweekUser user)
        {
            var subscriptionIndicies = this.GenerageUniqueIndexes(this.channels.Count, Random.Next(0, SubscriptionsPerUser + 1));

            foreach (var channelIndex in subscriptionIndicies)
            {
                var subscription = new ChannelSubscription(this.channels[channelIndex].Id, null, user.Id, null, Random.Next(1, 500), DateTime.UtcNow.AddDays(-10 - Random.Next(0, 5)), DateTime.UtcNow.AddDays(Random.Next(1, 5)));
                this.subscriptions.Add(subscription);
            }
        }
Beispiel #10
0
        private async Task AddUsersToChannelAsync(List <int> userIds, int channelId, int workspaceId)
        {
            userIds.ForEach(id =>
            {
                var channelSubscription = new ChannelSubscription(channelId, id);
                _context.ChannelSubscriptions.Add(channelSubscription);
            });
            await _context.SaveChangesAsync();

            await _messageCommandService.PostJoinChannelSystemMessageAsync(channelId, userIds, workspaceId);
        }
Beispiel #11
0
        public async Task ExecuteAsync(UserId userId, BlogId blogId, IReadOnlyList <AcceptedChannelSubscription> channels, DateTime now)
        {
            userId.AssertNotNull("userId");
            blogId.AssertNotNull("blogId");

            if (channels == null || channels.Count == 0)
            {
                channels = new List <AcceptedChannelSubscription>();
            }

            using (var transaction = TransactionScopeBuilder.CreateAsync())
            {
                using (var connection = this.connectionFactory.CreateConnection())
                {
                    await connection.ExecuteAsync(
                        DeleteStatement,
                        new
                    {
                        BlogId         = blogId.Value,
                        SubscriberId   = userId.Value,
                        KeepChannelIds = channels.Select(v => v.ChannelId.Value).ToList()
                    });

                    foreach (var item in channels)
                    {
                        var channelSubscription = new ChannelSubscription(
                            item.ChannelId.Value,
                            null,
                            userId.Value,
                            null,
                            item.AcceptedPrice.Value,
                            now,
                            now);

                        const ChannelSubscription.Fields UpdateFields
                            = ChannelSubscription.Fields.AcceptedPrice
                              | ChannelSubscription.Fields.PriceLastAcceptedDate;

                        await connection.UpsertAsync(
                            channelSubscription,
                            UpdateFields);
                    }
                }

                await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.SubscriberChannels);

                transaction.Complete();
            }
        }
Beispiel #12
0
        public async Task WhenTheSubscriptionHasChangedChanged_ItShouldUpdateTheSubscription()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateBlogSubscriptionsDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase);
                await testDatabase.TakeSnapshotAsync();

                await this.target.ExecuteAsync(UserId, Blog3Id, AcceptedBlog3Subscriptions2, Now);

                var expectedUpdate = new ChannelSubscription(
                    AcceptedBlog3Subscriptions2[0].ChannelId.Value,
                    null,
                    UserId.Value,
                    null,
                    AcceptedBlog3Subscriptions2[0].AcceptedPrice.Value,
                    Now,
                    SubscriptionStartDate);

                var expectedInsert = new ChannelSubscription(
                    AcceptedBlog3Subscriptions2[1].ChannelId.Value,
                    null,
                    UserId.Value,
                    null,
                    AcceptedBlog3Subscriptions2[1].AcceptedPrice.Value,
                    Now,
                    Now);

                var expectedDelete = new ChannelSubscription(
                    AcceptedBlog3Subscriptions1[1].ChannelId.Value,
                    null,
                    UserId.Value,
                    null,
                    AcceptedBlog3Subscriptions1[1].AcceptedPrice.Value,
                    PriceLastAcceptedDate,
                    SubscriptionStartDate);

                return(new ExpectedSideEffects
                {
                    Update = expectedUpdate,
                    Insert = expectedInsert,
                    Delete = expectedDelete
                });
            });
        }
        /// <summary>
        /// Subscribes to a channel.
        /// </summary>
        /// <param name="channel">Channel name.</param>
        /// <param name="subscribeOnReconnected">Subscribe to the specified channel on reconnect.</param>
        /// <param name="onMessage"><see cref="OnMessageDelegate"/> callback.</param>
        /// <example>
        ///   <code>
        /// ortcClient.Subscribe("channelName", true, OnMessageCallback);
        /// private void OnMessageCallback(object sender, string channel, string message)
        /// {
        /// // Do something
        /// }
        ///   </code>
        ///   </example>
        public void Subscribe(string channel, bool subscribeOnReconnected, OnMessageDelegate onMessage)
        {
            if (!IsConnected)
            {
                DelegateExceptionCallback(new OrtcNotConnectedException("Not connected"));
            }
            else if (String.IsNullOrEmpty(channel))
            {
                DelegateExceptionCallback(new OrtcEmptyFieldException("Channel is null or empty"));
            }
            else if (!channel.OrtcIsValidInput())
            {
                DelegateExceptionCallback(new OrtcInvalidCharactersException("Channel has invalid characters"));
            }
            else if (channel.Length > Constants.MAX_CHANNEL_SIZE)
            {
                DelegateExceptionCallback(new OrtcMaxLengthException(String.Format("Channel size exceeds the limit of {0} characters", Constants.MAX_CHANNEL_SIZE)));
            }
            else if (_client._subscribedChannels.ContainsKey(channel))
            {
                ChannelSubscription channelSubscription = null;
                _client._subscribedChannels.TryGetValue(channel, out channelSubscription);

                if (channelSubscription != null)
                {
                    if (channelSubscription.IsSubscribing)
                    {
                        DelegateExceptionCallback(new OrtcSubscribedException(String.Format("Already subscribing to the channel {0}", channel)));
                    }
                    else if (channelSubscription.IsSubscribed)
                    {
                        DelegateExceptionCallback(new OrtcSubscribedException(String.Format("Already subscribed to the channel {0}", channel)));
                    }
                    else
                    {
                        _client.subscribe(channel, subscribeOnReconnected, onMessage);
                    }
                }
            }
            else
            {
                _client.subscribe(channel, subscribeOnReconnected, onMessage);
            }
        }
        public void PubSubFilterTest()
        {
            Channel <int>           channel = new Channel <int>();
            SynchronousCommandQueue queue   = new SynchronousCommandQueue();
            int          received           = 0;
            Action <int> onReceive          = delegate(int data)
            {
                Assert.IsTrue(data % 2 == 0);
                received++;
            };
            ChannelSubscription <int> subber = new ChannelSubscription <int>(queue, onReceive);

            subber.FilterOnProducerThread = delegate(int msg) { return(msg % 2 == 0); };
            channel.SubscribeOnProducerThreads(subber);
            for (int i = 0; i <= 4; i++)
            {
                channel.Publish(i);
            }
            Assert.AreEqual(3, received);
        }
Beispiel #15
0
        /// <summary>
        /// Creates a client that listens to the newly created channel according to the specified filter
        /// </summary>
        /// <param name="filter">Filter to apply</param>
        /// <returns></returns>
        public static ILogClient CreateReliableClient(FilterBase filter)
        {
            if (Configuration == null || Configuration.endpoint == null ||
                string.IsNullOrEmpty(Configuration.endpoint.basePath))
            {
                throw new InvalidOperationException("Logbus is not configured for default client");
            }

            string mgmEndpoint = FormatScriptPath("LogbusManagement", Configuration.endpoint.basePath,
                                                  Configuration.endpoint.suffix),
                   subEndpoint = FormatScriptPath("LogbusSubscription", Configuration.endpoint.basePath,
                                                  Configuration.endpoint.suffix);

            IChannelManagement mgmObject = new ChannelManagement {
                Url = mgmEndpoint, UserAgent = UserAgent
            };
            IChannelSubscription subObject = new ChannelSubscription {
                Url = subEndpoint, UserAgent = UserAgent
            };

            return(new SyslogTlsClient(filter, mgmObject, subObject));
        }
Beispiel #16
0
        public async Task ExecuteAsync(
            UserId userId,
            ChannelId channelId,
            ValidAcceptedChannelPrice acceptedPrice,
            DateTime now)
        {
            userId.AssertNotNull("userId");
            channelId.AssertNotNull("channelId");
            acceptedPrice.AssertNotNull("acceptedPrice");

            using (var transaction = TransactionScopeBuilder.CreateAsync())
            {
                using (var connection = this.connectionFactory.CreateConnection())
                {
                    var channelSubscription = new ChannelSubscription(
                        channelId.Value,
                        null,
                        userId.Value,
                        null,
                        acceptedPrice.Value,
                        now,
                        now);

                    const ChannelSubscription.Fields UpdateFields
                        = ChannelSubscription.Fields.AcceptedPrice
                          | ChannelSubscription.Fields.PriceLastAcceptedDate;

                    await connection.UpsertAsync(
                        channelSubscription,
                        UpdateFields);
                }

                await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.SubscriberChannels);

                transaction.Complete();
            }
        }
Beispiel #17
0
        /// <summary>
        ///     Wrapper for using all the prebuilt subscriptions. Not recommended for performance but makes the library easier to
        ///     use for some quick testing.
        /// </summary>
        /// <param name="logFile"></param>
        public SubscriptionWrapper(LogFile logFile)
        {
            var tellSubscription = new TellSubscription(logFile);

            tellSubscription.Matched += TellSubscription_Matched;
            Subscriptions.Add(tellSubscription);

            var saySubscription = new SaySubscription(logFile);

            saySubscription.Matched += SaySubscription_Matched;
            Subscriptions.Add(saySubscription);

            var shoutSubscription = new ShoutSubscription(logFile);

            shoutSubscription.Matched += ShoutSubscription_Matched;
            Subscriptions.Add(shoutSubscription);

            var oocSubscription = new OocSubscription(logFile);

            oocSubscription.Matched += OocSubscription_Matched;
            Subscriptions.Add(oocSubscription);

            var groupChatSubscription = new GroupChatSubscription(logFile);

            groupChatSubscription.Matched += GroupChatSubscription_Matched;
            Subscriptions.Add(groupChatSubscription);

            var guildChatSubscription = new GuildChatSubscription(logFile);

            guildChatSubscription.Matched += GuildChatSubscription_Matched;
            Subscriptions.Add(guildChatSubscription);

            var auctionSubscription = new AuctionSubscription(logFile);

            auctionSubscription.Matched += AuctionSubscription_Matched;
            Subscriptions.Add(auctionSubscription);

            var channelSubscription = new ChannelSubscription(logFile);

            channelSubscription.Matched += ChannelSubscription_Matched;
            Subscriptions.Add(channelSubscription);

            var factionSubscription = new FactionSubscription(logFile);

            factionSubscription.Matched += FactionSubscription_Matched;
            Subscriptions.Add(factionSubscription);

            var physicalHitSubscription = new PhysicalHitSubscription(logFile);

            physicalHitSubscription.Matched += PhysicalHitSubscription_Matched;
            Subscriptions.Add(physicalHitSubscription);

            var physicalMissSubscription = new PhysicalMissSubscription(logFile);

            physicalMissSubscription.Matched += PhysicalMissSubscription_Matched;
            Subscriptions.Add(physicalMissSubscription);

            var fizzleSubscription = new FizzleSubscription(logFile);

            fizzleSubscription.Matched += FizzleSubscription_Matched;
            Subscriptions.Add(fizzleSubscription);

            var spellWornSubscription = new WornOffSubscription(logFile);

            spellWornSubscription.Matched += SpellWornSubscription_Matched;
            Subscriptions.Add(spellWornSubscription);

            var dotSubscription = new DotSubscription(logFile);

            dotSubscription.Matched += DotSubscription_Matched;
            Subscriptions.Add(dotSubscription);

            var spellImmunitySubscription = new ImmunitySubscription(logFile);

            spellImmunitySubscription.Matched += SpellImmunitySubscription_Matched;
            Subscriptions.Add(spellImmunitySubscription);

            var spellDamageSubscription = new SpellDamageSubscription(logFile);

            spellDamageSubscription.Matched += SpellDamageSubscription_Matched;
            Subscriptions.Add(spellDamageSubscription);

            //create death sub last to make sure it comes after combat subscriptions for most common use cases
            var deathSubscription = new DeathSubscription(logFile);

            deathSubscription.Matched += DeathSubscription_Matched;
            Subscriptions.Add(deathSubscription);

            var experienceSubscription = new ExperienceSubscription(logFile);

            experienceSubscription.Matched += ExperienceSubscription_Matched;
            Subscriptions.Add(experienceSubscription);

            var levelSubscription = new LevelSubscription(logFile);

            levelSubscription.Matched += LevelSubscription_Matched;
            Subscriptions.Add(levelSubscription);

            var zoneSubscription = new ZoneSubscription(logFile);

            zoneSubscription.Matched += ZoneSubscription_Matched;
            Subscriptions.Add(zoneSubscription);

            var skillUpSubscription = new SkillUpSubscription(logFile);

            skillUpSubscription.Matched += SkillUpSubscription_Matched;
            Subscriptions.Add(skillUpSubscription);
        }
Beispiel #18
0
 public void PubSubFilterTest()
 {
     Channel<int> channel = new Channel<int>();
     SynchronousCommandQueue queue = new SynchronousCommandQueue();
     int received = 0;
     Action<int> onReceive = delegate(int data)
                                 {
                                     Assert.IsTrue(data%2 == 0);
                                     received++;
                                 };
     ChannelSubscription<int> subber = new ChannelSubscription<int>(queue, onReceive);
     subber.FilterOnProducerThread = delegate(int msg) { return msg%2 == 0; };
     channel.SubscribeOnProducerThreads(subber);
     for (int i = 0; i <= 4; i++)
     {
         channel.Publish(i);
     }
     Assert.AreEqual(3, received);
 }
Beispiel #19
0
 /// <summary>
 /// Broadcasts the last subscriber to listening clients
 /// </summary>
 /// <param name="newChannelSubscription">Last subscriber to the stream</param>
 private async Task BroadcastNewSubscriber(ChannelSubscription newChannelSubscription)
 {
     await _alertHubConnection.InvokeAsync("BroadcastNewSubscriber", newChannelSubscription);
 }
        /// <summary>
        /// Selects the best IP address to use for listening
        /// </summary>
        /// <returns></returns>
        protected IPAddress GetIpAddress()
        {
            /*
             * If client is using OUR proxy, ie. no one re-implemented the
             * subscription interface with another mechanism like CORBA or
             * Remoting, we know where the Logbus web listener is located.
             *
             * By creating a fake UDP client, we want C# to activate the
             * system's routing tables (unavailable from language) to find
             * the interface that is used to connect to Logbus. In scenarios
             * in which a machine is connected both to LAN(s) and WAN, Logbus
             * might either be in one of the LANs or in the WAN. If we chose
             * the WAN address (see below) as favourite address, we might
             * do an error, as that address won't work in the case Logbus
             * server has only LAN access.
             *
             * This method to find the local address doesn't work in the
             * following scenario:
             * Logbus HTTP listener and the node that will actually send
             * the Syslog messages are deployed into different machines
             * that run in different subnets, especially if they have WAN
             * access. We will fix this situation too, but it's very rare.
             */
            if (ChannelSubscriber is ChannelSubscription)
            {
                try
                {
                    ChannelSubscription cs = ChannelSubscriber as ChannelSubscription;
                    string hostname        =
                        Regex.Match(cs.Url,
                                    "^(?<protocol>https?)://(?<host>[-A-Z0-9.]+)(?<port>:[0-9]{1,5})?(?<file>/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(?<parameters>\\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?",
                                    RegexOptions.IgnoreCase).Groups["host"].Value;
                    IPAddress hostIp = Dns.GetHostAddresses(hostname)[0];

                    //If we are contacting a local host, tell to use loopback
                    if (hostIp.Equals(IPAddress.Loopback))
                    {
                        return(IPAddress.Loopback);
                    }

                    //Just force a routing table lookup, we don't need more
                    UdpClient fakeClient = new UdpClient();
                    fakeClient.Connect(hostname, 65534);
                    return(((IPEndPoint)fakeClient.Client.LocalEndPoint).Address);
                }
                catch
                {
                } //Never mind...
            }
            //Else try to find the best WAN address to use


            /*
             *  The following mechanism might not work in the following scenario:
             *  -Client node is connected to LAN and WAN with 2 network cards
             *  -Logbus is listening on a computer that can access only LAN
             *
             *  In this case, client tries to use WAN address for listening,
             *  but Logbus won't be able to send datagrams to it.
             *  This is a structural bug in the getIPAddress logic that may be
             *  solved by the above commented code, but...
             *
             *  The above code, that implements a backup choice algorithm
             *  that forces the system's routing table to be activated, works
             *  by assuming that Logbus HTTP endpoint coincides with the host
             *  that actually sends UDP datagrams. While this happens 99% of
             *  times, it's not the only possible scenario.
             */

            return(NetworkUtils.GetMyIPAddress());
        }
Beispiel #21
0
        public async Task BroadcastSubscription(ChannelSubscription subscription)
        {
            await UpdateLastSubscriberAsync();

            await Clients.All.SendAsync("ReceiveNewSubscription", _lastSubscriber);
        }
Beispiel #22
0
 public async Task BroadcastNewSubscriber(ChannelSubscription newChannelSubscription)
 {
     await Clients.All.ReceiveNewSubscriber(newChannelSubscription);
 }
Beispiel #23
0
        internal void subscribe(string channel, bool subscribeOnReconnected, OrtcClient.OnMessageDelegate onMessage)
        {
            var domainChannelCharacterIndex = channel.IndexOf(':');
            var channelToValidate           = channel;

            if (domainChannelCharacterIndex > 0)
            {
                channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*";
            }

            string hash = _permissions.Where(c => c.Key == channel || c.Key == channelToValidate).FirstOrDefault().Value;

            if (_permissions != null && _permissions.Count > 0 && String.IsNullOrEmpty(hash))
            {
                context.DelegateExceptionCallback(new OrtcNotConnectedException(String.Format("No permission found to subscribe to the channel '{0}'", channel)));
            }
            else
            {
                if (!_subscribedChannels.ContainsKey(channel))
                {
                    _subscribedChannels.TryAdd(channel,
                                               new ChannelSubscription {
                        IsSubscribing          = true,
                        IsSubscribed           = false,
                        SubscribeOnReconnected = subscribeOnReconnected,
                        OnMessage = onMessage
                    });
                }

                try {
                    if (_subscribedChannels.ContainsKey(channel))
                    {
                        ChannelSubscription channelSubscription = null;
                        _subscribedChannels.TryGetValue(channel, out channelSubscription);

                        channelSubscription.IsSubscribing          = true;
                        channelSubscription.IsSubscribed           = false;
                        channelSubscription.SubscribeOnReconnected = subscribeOnReconnected;
                        channelSubscription.OnMessage = onMessage;
                    }

                    string s = String.Format("subscribe;{0};{1};{2};{3}", context._applicationKey, context._authenticationToken, channel, hash);

                    DoSend(s);
                } catch (Exception ex) {
                    string exName = null;

                    if (ex.InnerException != null)
                    {
                        exName = ex.InnerException.GetType().Name;
                    }

                    switch (exName)
                    {
                    case "OrtcNotConnectedException":
                        // Server went down
                        if (context.IsConnected)
                        {
                            DoDisconnect();
                        }
                        break;

                    default:
                        context.DelegateExceptionCallback(new OrtcGenericException(String.Format("Unable to subscribe: {0}", ex)));
                        break;
                    }
                }
            }
        }
Beispiel #24
0
        public void PubSubWithDedicatedThreadWithFilter()
        {
            using (var fiber = new ThreadFiber())
            {
                fiber.Start();
                var channel = new Channel<int>();

                var reset = new AutoResetEvent(false);
                Action<int> onMsg = x =>
                {
                    Assert.IsTrue(x % 2 == 0);
                    if (x == 4)
                    {
                        reset.Set();
                    }
                };
                var sub = new ChannelSubscription<int>(fiber, onMsg);
                sub.FilterOnProducerThread = x => x % 2 == 0;
                channel.SubscribeOnProducerThreads(sub);
                channel.Publish(1);
                channel.Publish(2);
                channel.Publish(3);
                channel.Publish(4);

                Assert.IsTrue(reset.WaitOne(5000, false));
            }
        }
Beispiel #25
0
        private void parseMessage(string message)
        {
            string type = JObject.Parse(message).SelectToken("type")?.ToString();

            switch (type.ToLower())
            {
            case "response":
                Models.PubSub.Responses.Response resp = new Models.PubSub.Responses.Response(message);
                if (previousRequest != null && previousRequest.Nonce.ToLower() == resp.Nonce.ToLower())
                {
                    OnListenResponse?.Invoke(this, new OnListenResponseArgs {
                        Response = resp, Topic = previousRequest.Topic, Successful = resp.Successful
                    });
                    return;
                }
                break;

            case "message":
                Models.PubSub.Responses.Message msg = new Models.PubSub.Responses.Message(message);
                switch (msg.Topic.Split('.')[0])
                {
                case "channel-subscribe-events-v1":
                    ChannelSubscription subscription = (ChannelSubscription)msg.messageData;
                    OnChannelSubscription?.Invoke(this, new OnChannelSubscriptionArgs {
                        Subscription = subscription
                    });
                    return;

                case "whispers":
                    Whisper whisper = (Whisper)msg.messageData;
                    OnWhisper?.Invoke(this, new OnWhisperArgs {
                        Whisper = whisper
                    });
                    return;

                case "chat_moderator_actions":
                    ChatModeratorActions cMA = (ChatModeratorActions)msg.messageData;
                    string reason            = "";
                    switch (cMA.ModerationAction.ToLower())
                    {
                    case "timeout":
                        if (cMA.Args.Count > 2)
                        {
                            reason = cMA.Args[2];
                        }
                        OnTimeout?.Invoke(this, new OnTimeoutArgs {
                            TimedoutBy      = cMA.CreatedBy, TimedoutUser = cMA.Args[0],
                            TimeoutDuration = TimeSpan.FromSeconds(int.Parse(cMA.Args[1])), TimeoutReason = reason
                        });
                        return;

                    case "ban":
                        if (cMA.Args.Count > 1)
                        {
                            reason = cMA.Args[1];
                        }
                        OnBan?.Invoke(this, new OnBanArgs {
                            BannedBy = cMA.CreatedBy, BannedUser = cMA.Args[0], BanReason = reason
                        });
                        return;

                    case "unban":
                        OnUnban?.Invoke(this, new OnUnbanArgs {
                            UnbannedBy = cMA.CreatedBy, UnbannedUser = cMA.Args[0]
                        });
                        return;

                    case "untimeout":
                        OnUntimeout?.Invoke(this, new OnUntimeoutArgs {
                            UntimeoutedBy = cMA.CreatedBy, UntimeoutedUser = cMA.Args[0]
                        });
                        return;

                    case "host":
                        OnHost?.Invoke(this, new OnHostArgs {
                            HostedChannel = cMA.Args[0], Moderator = cMA.CreatedBy
                        });
                        return;

                    case "subscribers":
                        OnSubscribersOnly?.Invoke(this, new OnSubscribersOnlyArgs {
                            Moderator = cMA.CreatedBy
                        });
                        return;

                    case "subscribersoff":
                        OnSubscribersOnlyOff?.Invoke(this, new OnSubscribersOnlyOffArgs {
                            Moderator = cMA.CreatedBy
                        });
                        return;

                    case "clear":
                        OnClear?.Invoke(this, new OnClearArgs {
                            Moderator = cMA.CreatedBy
                        });
                        return;

                    case "emoteonly":
                        OnEmoteOnly?.Invoke(this, new OnEmoteOnlyArgs {
                            Moderator = cMA.CreatedBy
                        });
                        return;

                    case "emoteonlyoff":
                        OnEmoteOnlyOff?.Invoke(this, new OnEmoteOnlyOffArgs {
                            Moderator = cMA.CreatedBy
                        });
                        return;

                    case "r9kbeta":
                        OnR9kBeta?.Invoke(this, new OnR9kBetaArgs {
                            Moderator = cMA.CreatedBy
                        });
                        return;

                    case "r9kbetaoff":
                        OnR9kBetaOff?.Invoke(this, new OnR9kBetaOffArgs {
                            Moderator = cMA.CreatedBy
                        });
                        return;
                    }
                    break;

                case "channel-bits-events-v1":
                    ChannelBitsEvents cBE = (ChannelBitsEvents)msg.messageData;
                    OnBitsReceived?.Invoke(this, new OnBitsReceivedArgs {
                        BitsUsed    = cBE.BitsUsed, ChannelId = cBE.ChannelId, ChannelName = cBE.ChannelName,
                        ChatMessage = cBE.ChatMessage, Context = cBE.Context, Time = cBE.Time, TotalBitsUsed = cBE.TotalBitsUsed, UserId = cBE.UserId, Username = cBE.Username
                    });
                    return;

                case "video-playback":
                    VideoPlayback vP = (VideoPlayback)msg.messageData;
                    switch (vP.Type)
                    {
                    case Enums.VideoPlaybackType.StreamDown:
                        OnStreamDown?.Invoke(this, new OnStreamDownArgs {
                            PlayDelay = vP.PlayDelay, ServerTime = vP.ServerTime
                        });
                        return;

                    case Enums.VideoPlaybackType.StreamUp:
                        OnStreamUp?.Invoke(this, new OnStreamUpArgs {
                            PlayDelay = vP.PlayDelay, ServerTime = vP.ServerTime
                        });
                        return;

                    case Enums.VideoPlaybackType.ViewCount:
                        OnViewCount?.Invoke(this, new OnViewCountArgs {
                            ServerTime = vP.ServerTime, Viewers = vP.Viewers
                        });
                        return;
                    }
                    break;
                }
                break;
            }
            if (logging)
            {
                unaccountedFor(message);
            }
        }
Beispiel #26
0
        public override void Subscribe(string channel, OnMessageDelegate onMessage)
        {
            #region Sanity Checks

            bool sanityChecked = true;

            if (!IsConnected)
            {
                RaiseOnException(new OrtcException("Not connected"));
                sanityChecked = false;
            }
            else if (String.IsNullOrEmpty(channel))
            {
                RaiseOnException(new OrtcException("Channel is null or empty"));
                sanityChecked = false;
            }
            else if (!channel.OrtcIsValidInput())
            {
                RaiseOnException(new OrtcException("Channel has invalid characters"));
                sanityChecked = false;
            }
            else if (_subscribedChannels.ContainsKey(channel))
            {
                ChannelSubscription channelSubscription = null;
                _subscribedChannels.TryGetValue(channel, out channelSubscription);

                if (channelSubscription != null)
                {
                    if (channelSubscription.IsSubscribing)
                    {
                        RaiseOnException(new OrtcException(String.Format("Already subscribing to the channel {0}", channel)));
                        sanityChecked = false;
                    }
                    else if (channelSubscription.IsSubscribed)
                    {
                        RaiseOnException(new OrtcException(String.Format("Already subscribed to the channel {0}", channel)));
                        sanityChecked = false;
                    }
                }
            }
            else
            {
                byte[] channelBytes = Encoding.UTF8.GetBytes(channel);

                if (channelBytes.Length > MAX_CHANNEL_SIZE)
                {
                    if (_subscribedChannels.ContainsKey(channel))
                    {
                        ChannelSubscription channelSubscription = null;
                        _subscribedChannels.TryGetValue(channel, out channelSubscription);

                        if (channelSubscription != null)
                        {
                            channelSubscription.IsSubscribing = false;
                        }
                    }

                    RaiseOnException(new OrtcException(String.Format("Channel size exceeds the limit of {0} characters", MAX_CHANNEL_SIZE)));
                    sanityChecked = false;
                }
            }

            #endregion

            if (sanityChecked)
            {
                if (!_subscribedChannels.ContainsKey(channel))
                {
                    _subscribedChannels.Add(channel,
                                            new ChannelSubscription
                    {
                        IsSubscribing          = true,
                        IsSubscribed           = false,
                        SubscribeOnReconnected = true,
                        OnMessage = onMessage
                    });
                }

                if (_subscribedChannels.ContainsKey(channel))
                {
                    ChannelSubscription channelSubscription = null;

                    _subscribedChannels.TryGetValue(channel, out channelSubscription);

                    channelSubscription.IsSubscribing          = true;
                    channelSubscription.IsSubscribed           = false;
                    channelSubscription.SubscribeOnReconnected = true;
                    channelSubscription.OnMessage = onMessage;
                }

                TaskManager.RunOnMainThread(() =>
                {
                    _javaObject.Call("Subscribe", channel, true);
                });
            }
        }