public async Task <IActionResult> Edit(long id, [Bind("ChannelId,SubscriberId")] ChannelSubscriber channelSubscriber)
        {
            if (id != channelSubscriber.SubscriberId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(channelSubscriber);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ChannelSubscriberExists(channelSubscriber.SubscriberId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ChannelId"]    = new SelectList(_context.Channels, "Id", "UUID", channelSubscriber.ChannelId);
            ViewData["SubscriberId"] = new SelectList(_context.Members, "Id", "Id", channelSubscriber.SubscriberId);
            return(View(channelSubscriber));
        }
        public int HandleSubscription(int userId, int channelId)
        {
            ChannelSubscriber subscriber = GetChannelSubscriber(userId, channelId);
            int subscriberId             = -1;

            if (subscriber == null)
            {
                subscriber = new ChannelSubscriber()
                {
                    ChannelId = channelId,
                    UserId    = userId,
                };
                _database.ChannelSubscribers.Add(subscriber);
                _database.SaveChanges();
                subscriberId = subscriber.Id;
            }
            else
            {
                subscriberId = subscriber.Id;
                _database.ChannelSubscribers.Remove(subscriber);
                _database.SaveChanges();
            }

            return(subscriberId);
        }
        public async Task <IActionResult> Create([Bind("ChannelId,SubscriberId")] ChannelSubscriber channelSubscriber)
        {
            if (ModelState.IsValid)
            {
                _context.Add(channelSubscriber);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ChannelId"]    = new SelectList(_context.Channels, "Id", "UUID", channelSubscriber.ChannelId);
            ViewData["SubscriberId"] = new SelectList(_context.Members, "Id", "Id", channelSubscriber.SubscriberId);
            return(View(channelSubscriber));
        }
Ejemplo n.º 4
0
        private void RefreshChannel(Object status)
        {
            string clientId = (string)status;

            try
            {
                ChannelSubscriber.RefreshSubscription(clientId);
            }
            catch (ClientNotSubscribedException)
            {
                Log.Notice("Client {0} on channel {1} expired. Trying to subscribe again", clientId, ChannelId);

                Stop();

                //Might fail in case of network problems
                Start();
            }
            catch (Exception ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, false));

                Log.Warning("Unable to refresh subscription of client {0} on channel {1}", _clientId, ChannelId);
                Log.Debug("Error details: {0}", ex.Message);

                try
                {
                    //Take some rest
                    Thread.Sleep((int)(_channelTtl / 20));

                    ChannelSubscriber.RefreshSubscription(clientId);
                }
                catch (Exception e)
                {
                    OnError(new UnhandledExceptionEventArgs(e, true));

                    Log.Error(
                        "Unable to refresh subscription of client {0} on channel {1} for the second consecutive time",
                        _clientId, ChannelId);
                    Log.Debug("Error details: {0}", e.Message);

                    try
                    {
                        Stop();
                    }
                    catch
                    {
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public override void Stop()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }
            if (!_running)
            {
                throw new NotSupportedException("Client is not running");
            }
            try
            {
                CancelEventArgs arg = new CancelEventArgs();
                OnStopping(arg);
                if (arg.Cancel)
                {
                    return;
                }


                //Stop refreshing
                if (_refreshTimer != null)
                {
                    _refreshTimer.Dispose();
                }

                try
                {
                    ChannelSubscriber.UnsubscribeChannel(_clientId);
                }
                catch (LogbusException)
                {
                }
                _clientId = null;

                try
                {
                    _client.Close(); //Trigger SocketException if thread is blocked into listening
                }
                catch (SocketException)
                {
                } //Really nothing?

                _runningThread.Interrupt();
                _runningThread.Join();
                _runningThread = null;

                _running = false;

                OnStopped(EventArgs.Empty);
            }
            catch (Exception ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, true));

                if (ex is LogbusException)
                {
                    throw;
                }

                throw new LogbusException("Unable to unsubscribe channel", ex);
            }
        }
Ejemplo n.º 6
0
        public override void Start()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }
            if (_running)
            {
                throw new NotSupportedException("Client is already running");
            }
            try
            {
                CancelEventArgs arg = new CancelEventArgs();
                OnStarting(arg);
                if (arg.Cancel)
                {
                    return;
                }

                bool supported = false;
                foreach (string transport in ChannelSubscriber.GetAvailableTransports())
                {
                    if (transport == "udp")
                    {
                        supported = true;
                        break;
                    }
                }
                if (!supported)
                {
                    throw new NotSupportedException(
                              "Remote Logbus-ng node does not support TLS protocol for delivery. You must use a different client");
                }

                int port;
                //Decide on which address to listen
                IPAddress localIp = GetIpAddress();

                /* Workaround to Mono bug 643475, https://bugzilla.novell.com/show_bug.cgi?id=643475
                 * fixed since Mono master 512d3f2 and probably available from release next to 2.6.7
                 * */
#if MONO
                IPEndPoint[] eps = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
#endif
                for (int i = START_PORT; i <= END_PORT; i++)
                {
#if MONO
                    //Workaround to Mono bug 64375
                    bool found = false;
                    for (int c = 0; c < eps.Length; c++)
                    {
                        if (eps[c].Port == i && (eps[c].Address.Equals(IPAddress.Any) || eps[c].Address.Equals(localIp)))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        socket.Bind(new IPEndPoint(localIp, i));
                        _client = new UdpClient {
                            Client = socket
                        };
                        break;
                    }
#else
                    try
                    {
                        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
                        {
                            ExclusiveAddressUse = true
                        };
                        socket.Bind(new IPEndPoint(localIp, i));

                        _client = new UdpClient {
                            Client = socket
                        };
                        break;
                    }
                    catch (SocketException)
                    {
                    }
#endif
                }
                //Unable to bind to one of the default ports.
                //Now pray your firewall is open to all UDP ports
                if (_client == null)
                {
                    _client = new UdpClient(new IPEndPoint(localIp, 0));
                }

                EndPoint ep = _client.Client.LocalEndPoint;
                if (ep is IPEndPoint)
                {
                    IPEndPoint ipe = (IPEndPoint)ep;
                    port = ipe.Port;
                }
                else
                {
                    throw new NotSupportedException("Only IP networks are supported");
                }

                _runningThread = new Thread(RunnerLoop)
                {
                    IsBackground = true
                };
                _runningThread.Start();


                ChannelSubscriptionRequest req = new ChannelSubscriptionRequest
                {
                    channelid = ChannelId,
                    transport = "udp",
                    param     = new[]
                    {
                        new KeyValuePair
                        {
                            name  = "port",
                            value =
                                port.ToString(
                                    CultureInfo.InvariantCulture)
                        },
                        new KeyValuePair
                        {
                            name = "ip", value = localIp.ToString()
                        }
                    }
                };
                ChannelSubscriptionResponse res = ChannelSubscriber.SubscribeChannel(req);
                _clientId   = res.clientid;
                _channelTtl = MAX_REFRESH_TIME;
                foreach (KeyValuePair kvp in res.param)
                {
                    if (kvp.name == "ttl")
                    {
                        if (long.TryParse(kvp.value, out _channelTtl))
                        {
                            break;
                        }
                    }
                }
                long refreshTime = Math.Min(_channelTtl * 4 / 5, MAX_REFRESH_TIME);
                //80% of the max TTL, but not over max TTL

                _refreshTimer = new Timer(RefreshChannel, _clientId, refreshTime, refreshTime);

                _running = true;

                OnStarted(EventArgs.Empty);
            }
            catch (LogbusException ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, true));

                throw;
            }
            catch (Exception ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, true));

                throw new LogbusException("Unable to subscribe channel", ex);
            }
        }
Ejemplo n.º 7
0
        public override void Start()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }
            if (Running)
            {
                throw new NotSupportedException("Client is already running");
            }
            try
            {
                Log.Info("TLS client starting");
                CancelEventArgs arg = new CancelEventArgs();
                OnStarting(arg);
                if (arg.Cancel)
                {
                    return;
                }

                bool supported = false;
                foreach (string transport in ChannelSubscriber.GetAvailableTransports())
                {
                    if (transport == "tls")
                    {
                        supported = true;
                        break;
                    }
                }
                if (!supported)
                {
                    throw new NotSupportedException(
                              "Remote Logbus-ng node does not support TLS protocol for delivery. You must use a different client");
                }


                int port;
                //Decide on which address to listen
                IPAddress localIp = GetIpAddress();
                _localhost = (IPAddress.IsLoopback(localIp)) ? "localhost" : Dns.GetHostName();


                for (int i = START_PORT; i <= END_PORT; i++)
                {
                    try
                    {
                        _server = new TcpListener(new IPEndPoint(localIp, i));
                        _server.Start(1);
                        break;
                    }
                    catch (SocketException)
                    {
                    }
                }
                //Unable to bind to one of the default ports.
                //Now pray your firewall is open to all TCP ports
                if (_server == null)
                {
                    _server = new TcpListener(new IPEndPoint(localIp, 0));
                    _server.Start();
                }

                EndPoint ep = _server.Server.LocalEndPoint;
                if (ep is IPEndPoint)
                {
                    IPEndPoint ipe = (IPEndPoint)ep;
                    port = ipe.Port;
                }
                else
                {
                    throw new NotSupportedException("Only IP networks are supported");
                }


                _listenerThread = new Thread(ListenerLoop);
                _listenerThread.Start();
                _processingThread = new Thread(ProcessLoop);
                _processingThread.Start();


                ChannelSubscriptionRequest req = new ChannelSubscriptionRequest
                {
                    channelid = ChannelId,
                    transport = "tls",
                    param     = new[]
                    {
                        new KeyValuePair
                        {
                            name  = "port",
                            value =
                                port.ToString(
                                    CultureInfo.InvariantCulture)
                        },
                        new KeyValuePair
                        {
                            name  = "host",
                            value = _localhost
                        },
                        new KeyValuePair
                        {
                            name  = "ip",
                            value = GetIpAddress().ToString()
                        }
                    }
                };
                ChannelSubscriptionResponse res = ChannelSubscriber.SubscribeChannel(req);
                _clientId = res.clientid;

                Running = true;

                OnStarted(EventArgs.Empty);
                Log.Info("TLS client started");
            }
            catch (LogbusException ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, true));
                Log.Error("Error starting TLS client");
                Log.Debug("Error details: {0}", ex.Message);

                throw;
            }
            catch (Exception ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, true));
                Log.Error("Error starting TLS client");
                Log.Debug("Error details: {0}", ex.Message);

                throw new LogbusException("Unable to subscribe channel", ex);
            }
        }
Ejemplo n.º 8
0
        public override void Stop()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }
            if (!Running)
            {
                throw new NotSupportedException("Client is not running");
            }

            try
            {
                Log.Info("TLS client stopping");

                CancelEventArgs arg = new CancelEventArgs();
                OnStopping(arg);
                if (arg.Cancel)
                {
                    return;
                }

                Running = false;
                try
                {
                    ChannelSubscriber.UnsubscribeChannel(_clientId);
                }
                catch (LogbusException)
                {
                }
                _clientId = null;

                try
                {
                    _server.Stop();
                }
                catch (SocketException)
                {
                } //Really nothing?

                _processingThread.Interrupt();
                if (!_listenerThread.Join(DEFAULT_JOIN_TIMEOUT))
                {
                    _listenerThread.Abort();
                    _listenerThread.Join();
                }
                _listenerThread = null;
                if (_processingThread.Join(DEFAULT_JOIN_TIMEOUT))
                {
                    _processingThread.Abort();
                    _processingThread.Join();
                }
                _processingThread = null;

                OnStopped(EventArgs.Empty);
                Log.Info("TLS client stopped");
            }
            catch (Exception ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, true));
                Log.Error("Error stopping TLS client");
                Log.Debug("Error details: {0}", ex.Message);
                if (ex is LogbusException)
                {
                    throw;
                }
                throw new LogbusException("Unable to unsubscribe channel", ex);
            }
        }
Ejemplo n.º 9
0
        public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action <CreateChannelResponse> done)
        {
            done(new CreateChannelResponse.Builder
            {
                ChannelId = request.ChannelId.ToBuilder().SetHigh(0x604ac77c9aa0d7d).SetLow(0x9be5ecbd0000279f).Build(),
                ObjectId  = 67093
            }.Build());

            client.ListenerId = request.ObjectId;

            var notification = new AddNotification.Builder
            {
                Self = new Member.Builder
                {
                    Identity = new Identity.Builder
                    {
                        AccountId = new EntityId.Builder
                        {
                            High = HighId.Account,
                            Low  = 0
                        }.Build(),
                GameAccountId = new EntityId.Builder
                        {
                            High = HighId.GameAccount,
                            Low  = 5200929,
                        }.Build(),
                ToonId = new EntityId.Builder
                        {
                            High = HighId.Toon,
                            Low  = 2,
                        }.Build()
                    }.Build(),
                State = new MemberState.Builder
                    {
                        Privileges = 64511,
                    }.AddRole(2).Build(),
                }.Build(),

                ChannelState = new ChannelState.Builder
                {
                    MaxMembers     = 8,
                    MinMembers     = 1,
                    MaxInvitations = 12,
                    PrivacyLevel   = ChannelState.Types.PrivacyLevel.PRIVACY_LEVEL_OPEN_INVITATION
                }.Build()
            }.AddMember(new Member.Builder
            {
                Identity = new Identity.Builder
                {
                    ToonId = new EntityId.Builder
                    {
                        High = HighId.Toon,
                        Low  = 2,
                    }.Build()
                }.Build(),
                State = new MemberState.Builder
                {
                    Privileges = 64511,
                }.AddRole(2).Build(),
            }.Build());

            ChannelSubscriber.CreateStub(client).NotifyAdd(controller, notification.Build(), r => { });
        }