Ejemplo n.º 1
0
 private void SettingsForm_Load(object sender, EventArgs e)
 {
     ShowInTaskbar = false;
     Hide();
     _sysTray.IsVisible = true;
     _hub.Publish(new ConfigReloadRequestMessage(this));
 }
Ejemplo n.º 2
0
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            switch (indexPath.Row)
            {
            case 0:
                _hub.Publish(new AddTorrentMessage(this, _details.TorrentUrl));
                break;

            case 1:
                if (_details.Comments != null && _details.Comments.Length != 0)
                {
                    _hub.Publish(new CommentsMessage(this, _details));
                }
                break;

            case 2:
                if (_details.Files != null && _details.Files.Length != 0)
                {
                    _hub.Publish(new FilesMessage(this, _details));
                }
                break;

            default:
                break;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// It starts the SocketServer.
        /// </summary>
        public void Start()
        {
            _logger.Debug($"Socket starts listening on port: {_settings.UserSettingsModel.ListeningPort}");
            try
            {
                _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Create the listening socket.
                var ipLocal = new IPEndPoint(IPAddress.Any, Convert.ToInt32(_settings.UserSettingsModel.ListeningPort));

                // Bind to local IP address.
                _mainSocket.Bind(ipLocal);

                // Start Listening.
                _mainSocket.Listen(4);

                // Create the call back for any client connections.
                _mainSocket.BeginAccept(OnClientConnect, null);
                _hub.Publish(new SocketStatusChanged(true));

                _pingTimer          = new Timer(15000);
                _pingTimer.Elapsed += PingTimerOnElapsed;
                _pingTimer.Enabled  = true;
            }
            catch (SocketException se)
            {
                _logger.Error(se, "While starting the socket service");
            }
        }
Ejemplo n.º 4
0
        public void Log(string name, ExecutionStatus status, string clientId)
        {
            var logEntry = new ExecutionLog {
                Client = clientId, Command = name, Status = status
            };

            _logRepository.InsertLog(logEntry);
            _hub.Publish(new ActionLoggedEvent(logEntry));
        }
Ejemplo n.º 5
0
        protected override void ServiceStart()
        {
            _logger.Start();
            _subToStatus = _hub.Subscribe <OnStatusReceivedMessage>(OnStatusReceived);
            _subToConfig = _hub.Subscribe <OnConfigLoadedMessage>(OnConfigLoaded);
            _subToStop   = _hub.Subscribe <StopServiceRequestMessage>(_ => Stop());

            _hub.Publish(new ConfigReloadRequestMessage(this));
            _hub.Publish(new OnStartupMessage(this));
            _logger.Info("LenovoBacklightControl service started.", 50902);
        }
Ejemplo n.º 6
0
        public void Start()
        {
            _coverSubscription  = _hub.Subscribe <CoverDataReadyEvent>(msg => BroadcastCover(msg.Cover));
            _lyricsSubscription = _hub.Subscribe <LyricsDataReadyEvent>(msg => BroadcastLyrics(msg.Lyrics));
            _hub.Subscribe <TrackChangedEvent>(_ => { BroadcastTrackInfo(); });
            _hub.Subscribe <ArtworkReadyEvent>(_ => { _hub.Publish(new CoverAvailable(_apiAdapter.GetCover())); });
            _hub.Subscribe <LyricsReadyEvent>(_ => { _hub.Publish(new LyricsAvailable(_apiAdapter.GetLyrics())); });

            _positionUpdateTimer          = new Timer(20000);
            _positionUpdateTimer.Elapsed += PositionUpdateTimerOnElapsed;
            _positionUpdateTimer.Enabled  = true;
        }
Ejemplo n.º 7
0
 public override void WillBeginSearch(UISearchDisplayController controller)
 {
     if (_controller == null)
     {
         //Has to be stored in a member variable, GC collects and breaks something
         _controller = controller;
         _controller.SearchBar.SearchButtonClicked += (sender, e) =>
         {
             _hub.Publish(new SearchMessage(this, _searchText, _searchScope));
         };
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        ///     Processes the incoming message and answer's sending back the needed data.
        /// </summary>
        /// <param name="incomingMessage">The incoming message.</param>
        /// <param name="connectionId"> The id of the connection that send the incoming message.</param>
        public void ProcessIncomingMessage(string incomingMessage, string connectionId)
        {
            _logger.Debug($"Received by client: {connectionId} message --> {incomingMessage}");

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

            try
            {
                var messageList = GetMessages(incomingMessage, connectionId);
                var connection  = _auth.GetConnection(connectionId);

                foreach (var message in messageList)
                {
                    if (message.IsVerifyConnection())
                    {
                        var socketMessage = new SocketMessage(Constants.VerifyConnection, string.Empty);
                        _hub.Publish(new PluginResponseAvailableEvent(socketMessage, connectionId));
                        return;
                    }

                    if (connection.PacketNumber == 0 && !message.IsPlayer())
                    {
                        _hub.Publish(new ForceClientDisconnect(connectionId));
                        return;
                    }

                    if (connection.PacketNumber == 1 && !message.IsProtocol())
                    {
                        _hub.Publish(new ForceClientDisconnect(connectionId));
                        return;
                    }

                    if (message.IsProtocol() && message.Data is JObject)
                    {
                        HandleProtocolMessage(message, connection);
                    }

                    _hub.Publish(new MessageEvent(message.Context, message.Data, connectionId, connection.ClientId));
                }

                connection.IncreasePacketNumber();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Processing message failed --> {incomingMessage} from {connectionId}");
            }
        }
Ejemplo n.º 9
0
        public void Execute(IEvent @event)
        {
            var connectionId = @event.ConnectionId;

            var clientProtocol = _auth.ClientProtocolVersion(connectionId);

            SendTrackInfo(clientProtocol, connectionId);
            SendTrackRating(connectionId);
            SendLfmRating(connectionId);

            var statusMessage = new SocketMessage(Constants.PlayerStatus, _apiAdapter.GetStatus());

            _hub.Publish(new PluginResponseAvailableEvent(statusMessage, connectionId));


            if (clientProtocol >= Constants.V3)
            {
                var coverPayload  = CoverPayloadGenerator.Create(_model.Cover, true);
                var lyricsPayload = new LyricsPayload(_model.Lyrics);
                var coverMessage  = new SocketMessage(Constants.NowPlayingCover, coverPayload);
                var lyricsMessage = new SocketMessage(Constants.NowPlayingLyrics, lyricsPayload);
                _hub.Publish(new PluginResponseAvailableEvent(coverMessage, connectionId));
                _hub.Publish(new PluginResponseAvailableEvent(lyricsMessage, connectionId));
            }
            else
            {
                var coverMessage  = new SocketMessage(Constants.NowPlayingCover, _model.Cover);
                var lyricsMessage = new SocketMessage(Constants.NowPlayingLyrics, _model.Lyrics);
                _hub.Publish(new PluginResponseAvailableEvent(coverMessage, connectionId));
                _hub.Publish(new PluginResponseAvailableEvent(lyricsMessage, connectionId));
            }
        }
Ejemplo n.º 10
0
 public void Execute(IEvent @event)
 {
     if (_auth.ClientProtocolVersion(@event.ConnectionId) > 2)
     {
         var lyricsPayload = new LyricsPayload(_model.Lyrics);
         var message       = new SocketMessage(Constants.NowPlayingLyrics, lyricsPayload);
         _hub.Publish(new PluginResponseAvailableEvent(message, @event.ConnectionId));
     }
     else
     {
         var message = new SocketMessage(Constants.NowPlayingLyrics, _model.Lyrics);
         _hub.Publish(new PluginResponseAvailableEvent(message, @event.ConnectionId));
     }
 }
Ejemplo n.º 11
0
        public void Execute(IEvent @event)
        {
            var temporalInformation = _apiAdapter.GetTemporalInformation();
            var message             = new SocketMessage(Constants.NowPlayingPosition, temporalInformation);

            _hub.Publish(new PluginResponseAvailableEvent(message, @event.ConnectionId));
        }
Ejemplo n.º 12
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            //IoC setup
            var container = TinyIoCContainer.Current;

            container.Register <UIApplicationDelegate>(this);

            _hub = container.Resolve <ITinyMessengerHub>();

            var busy = container.Resolve <BusyIndicator>();

            busy.Indicator = _indicator;

            //Fire up window
            if (UIDevice.CurrentDevice.CheckSystemVersion(5, 0))
            {
                _window.RootViewController = _tabController;
            }
            else
            {
                _window.AddSubview(_tabController.View);
            }
            _window.BringSubviewToFront(_indicator);
            _window.MakeKeyAndVisible();

            _hub.Publish(new ApplicationMessage(this, ApplicationMessageType.Loaded));
            return(true);
        }
Ejemplo n.º 13
0
        public void Execute(IEvent @event)
        {
            var trackDetails = _apiAdapter.GetPlayingTrackDetails();
            var message      = new SocketMessage(Constants.NowPlayingDetails, trackDetails);

            _hub.Publish(new PluginResponseAvailableEvent(message, @event.ConnectionId));
        }
Ejemplo n.º 14
0
        public override void Execute(IEvent receivedEvent)
        {
            if (receivedEvent == null)
            {
                throw new ArgumentNullException(nameof(receivedEvent));
            }

            var result = false;

            if (receivedEvent.Data is JToken token)
            {
                switch (token.Type)
                {
                case JTokenType.Integer:
                    result = _nowPlayingApiAdapter.PlayIndex((int)token);
                    break;

                case JTokenType.String:
                    result = _nowPlayingApiAdapter.PlayPath((string)token);
                    break;
                }
            }

            var message = new SocketMessage(Constants.NowPlayingListPlay, result);

            _hub.Publish(new PluginResponseAvailableEvent(message));
        }
Ejemplo n.º 15
0
        public override void Execute(IEvent @event)
        {
            var isToggle = false;
            var token    = @event.Data as JToken;

            if (token != null && ((string)token).Equals("toggle"))
            {
                isToggle = true;
            }

            SocketMessage message;

            if (_auth.ClientProtocolMisMatch(@event.ConnectionId))
            {
                if (isToggle)
                {
                    _apiAdapter.ToggleShuffleLegacy();
                }
                message = new SocketMessage(Constants.PlayerShuffle, _apiAdapter.GetShuffleLegacy());
            }
            else
            {
                var shuffleState = isToggle ? _apiAdapter.SwitchShuffle() : _apiAdapter.GetShuffleState();
                message = new SocketMessage(Constants.PlayerShuffle, shuffleState);
            }

            _hub.Publish(new PluginResponseAvailableEvent(message));
        }
Ejemplo n.º 16
0
        public void Execute(IEvent receivedEvent)
        {
            if (receivedEvent == null)
            {
                throw new ArgumentNullException(nameof(receivedEvent));
            }

            SocketMessage message;

            if (_auth.ClientProtocolVersion(receivedEvent.ConnectionId) > 2)
            {
                var coverPayload = CoverPayloadGenerator.Create(_model.Cover, true);
                message = new SocketMessage(Constants.NowPlayingCover, coverPayload)
                {
                    NewLineTerminated = true
                };
            }
            else
            {
                message = new SocketMessage(Constants.NowPlayingCover, _model.Cover)
                {
                    NewLineTerminated = true
                };
            }

            _hub.Publish(new PluginResponseAvailableEvent(message, receivedEvent.ConnectionId));
        }
Ejemplo n.º 17
0
        public override void Execute(IEvent receivedEvent)
        {
            if (receivedEvent == null)
            {
                throw new ArgumentNullException(nameof(receivedEvent));
            }

            var isToggle = receivedEvent.Data is JToken token &&
                           ((string)token).Equals("toggle", StringComparison.InvariantCultureIgnoreCase);

            SocketMessage message;

            if (_auth.ClientProtocolMisMatch(receivedEvent.ConnectionId))
            {
                if (isToggle)
                {
                    _apiAdapter.ToggleShuffleLegacy();
                }

                message = new SocketMessage(Constants.PlayerShuffle, _apiAdapter.GetShuffleLegacy());
            }
            else
            {
                var shuffleState = isToggle ? _apiAdapter.SwitchShuffle() : _apiAdapter.GetShuffleState();
                message = new SocketMessage(Constants.PlayerShuffle, shuffleState);
            }

            _hub.Publish(new PluginResponseAvailableEvent(message));
        }
Ejemplo n.º 18
0
        protected override void ExecuteInternal(CheckPixelDifferenceParameter param, CancellationToken token)
        {
            var stopWatch = new Stopwatch();

            while (true)
            {
                token.ThrowIfCancellationRequested();

                stopWatch.Restart();
                var color = Win32ApiHelper.GetPixelColorFromDesktop(param.Pixel.X, param.Pixel.Y);
                stopWatch.Stop();

                // For some reason, the GetPixel method of the WinAPI is executed every time with different duration (from 15 to 35 ms).
                // The rest of code HAS TO be executed every time after the same duration, so we'll wait up to 100ms
                Thread.Sleep(100 - (int)stopWatch.ElapsedMilliseconds);

                if (!(color.R == param.HookedColor.R && color.G == param.HookedColor.G &&
                      color.B == param.HookedColor.B))
                {
                    continue;
                }

                _messageBus.Publish(new PixelColorChangedMessage(this));
                break;
            }
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> CastVote([FromRoute] string pollId, [FromQuery] string answerId)
        {
            if (!Guid.TryParse(pollId, out var id))
            {
                ModelState.TryAddModelError("ParsingError", $"Poll ID {pollId} is not valid.");
                return(BadRequest(ModelState));
            }

            var poll = await _pollRepository.GetById(id);

            if (poll == null)
            {
                return(NotFound());
            }

            var addressBytes = HttpContext.Connection.RemoteIpAddress.MapToIPv4().GetAddressBytes();

            if (!poll.AllowMultipleVotesPerIp)
            {
                var votes         = poll.Answers.SelectMany(s => s.Votes);
                var sourceIpBytes = addressBytes;
                if (votes.FirstOrDefault(v => v.Source.SequenceEqual(sourceIpBytes)) != null)
                {
                    return(StatusCode(StatusCodes.Status403Forbidden));
                }
            }

            if (!Guid.TryParse(answerId, out var answId))
            {
                ModelState.TryAddModelError("ParsingError", $"Answer ID {answerId} is not valid.");
                return(BadRequest(ModelState));
            }

            var answer = poll.Answers.FirstOrDefault(a => a.Id.Equals(answId));

            if (answer == null)
            {
                return(NotFound());
            }

            if (poll.Duration != null && poll.CreatedOn.Add(poll.Duration.Value) < DateTime.Now)
            {
                // Poll is expired
                return(StatusCode((int)HttpStatusCode.Gone));
            }

            var vote = new Vote
            {
                Id          = Guid.NewGuid(),
                Source      = addressBytes,
                CastedOn    = DateTime.Now,
                OwnerAnswer = answer
            };

            await _voteRepository.Add(vote);

            _messengerHub.Publish(new VoteCastedMessage(poll.Id, answer.Id));

            return(Ok());
        }
Ejemplo n.º 20
0
        public void Execute(IEvent @event)
        {
            var from = -1;
            var to   = -1;

            var success = false;
            var token   = @event.Data as JToken;

            if (token != null && token.Type == JTokenType.Object)
            {
                from    = (int)token["from"];
                to      = (int)token["to"];
                success = _nowPlayingApiAdapter.MoveTrack(from, to);
            }

            var reply = new
            {
                success,
                from,
                to
            };

            var message = new SocketMessage(Constants.NowPlayingListMove, reply);

            _hub.Publish(new PluginResponseAvailableEvent(message, @event.ConnectionId));
        }
Ejemplo n.º 21
0
        private void GetPage(string connectionId, string id = "", int offset = 0, int limit = 800)
        {
            var data    = _libraryApiAdapter.GetEpisodes(id).ToList();
            var message = CreateMessage(offset, limit, data, Constants.PodcastEpisodes);

            _hub.Publish(new PluginResponseAvailableEvent(message, connectionId));
        }
Ejemplo n.º 22
0
        public void Execute(IEvent receivedEvent)
        {
            if (receivedEvent == null)
            {
                throw new ArgumentNullException(nameof(receivedEvent));
            }

            var from = -1;
            var to   = -1;

            var success = false;

            if (receivedEvent.Data is JToken token && token.Type == JTokenType.Object)
            {
                from    = (int)token["from"];
                to      = (int)token["to"];
                success = _nowPlayingApiAdapter.MoveTrack(from, to);
            }

            var reply = new { success, from, to };

            var message = new SocketMessage(Constants.NowPlayingListMove, reply);

            _hub.Publish(new PluginResponseAvailableEvent(message, receivedEvent.ConnectionId));
        }
Ejemplo n.º 23
0
        public void Execute(IEvent @event)
        {
            var data = @event.Data as JToken;

            if (data != null)
            {
                int clientProtocolVersion;
                switch (data.Type)
                {
                case JTokenType.Integer:
                case JTokenType.Float:
                    clientProtocolVersion = (int)data;
                    break;

                case JTokenType.Object:
                    clientProtocolVersion = (int)data["protocol_version"];
                    break;

                default:
                    clientProtocolVersion = Constants.V2;
                    break;
                }

                var socketConnection = _auth.GetConnection(@event.ConnectionId);
                if (socketConnection != null)
                {
                    socketConnection.ClientProtocolVersion = clientProtocolVersion;
                }
            }


            var message = new SocketMessage(Constants.Protocol, Constants.ProtocolVersion);

            _hub.Publish(new PluginResponseAvailableEvent(message, @event.ConnectionId));
        }
Ejemplo n.º 24
0
        private IEnumerator PublishMessageWhenFinished(IEnumerator execution, ICommand command)
        {
            yield return(execution);

            logger.Info("Completed command: {0}", command.GetType().Name);

            messengerHub.Publish(new CommandCompleteMessage(this, command, this));
        }
Ejemplo n.º 25
0
 private void SendApiUseLevelMessage(Object myObject, EventArgs myEventArgs)
 {
     if (_bus != null)
     {
         int counter = _keyHelper.CountRecentKeys();
         _bus.Publish(new MsgUpdateApiUse(this, counter));
     }
 }
Ejemplo n.º 26
0
        public bool Stop()
        {
            //STOP LOGIC
            logger.Info("Stopping signal received ...");
            messenger.Publish(new StopMessage("STOP"));

            return(true);
        }
Ejemplo n.º 27
0
 public HomeModule(ITinyMessengerHub hub)
 {
     Post["/"] = parameters =>
     {
         var notification = this.Bind <Notification>();
         hub.Publish(notification);
         return(HttpStatusCode.OK);
     };
 }
Ejemplo n.º 28
0
        public void Execute(IEvent @event)
        {
            var message = new SocketMessage(Constants.PlayerOutput, _apiAdapter.GetOutputDevices())
            {
                NewLineTerminated = true
            };

            _hub.Publish(new PluginResponseAvailableEvent(message, @event.ConnectionId));
        }
Ejemplo n.º 29
0
        private void OnSave()
        {
            if (SelectedAirport == null)
            {
                return;
            }

            _objectStore.Save(SelectedAirport, Airport.SelectedAirportFilename);

            if (SelectedAirport.Equals(Airport.Nearest))
            {
                _messenger.Publish(new FindNearestAirportMessage(this));
            }
            else
            {
                _messenger.Publish(new AirportSelectedMessage(this, SelectedAirport));
            }
        }
Ejemplo n.º 30
0
        private void OnSpinRequested(SpinCamera360Message message)
        {
            var cmd = new RotateGameObjectCommand(gameObject: camera.gameObject,
                                                  point: Vector3.zero,
                                                  axis: Vector3.up,
                                                  angle: 360f * message.NumberOfSpins,
                                                  durationSeconds: message.DurationSeconds);

            messengerHub.Publish(new EnqueueCommandMessage(this, cmd, transient: true));
        }
Ejemplo n.º 31
0
        protected virtual void Initialize()
        {
            var container = TinyIoCContainer.Current;

            //Messenger
            _hub = container.Resolve<ITinyMessengerHub>();
            _hub.Subscribe<ApplicationMessage>(m =>
            {
                if (m.Content == ApplicationMessageType.Loaded || m.Content == ApplicationMessageType.Foregrounded)
                {
            //					if (!string.IsNullOrEmpty(_settings.Url) && ++_settings.NumberOfRuns == 3)
            //					{
            //						MessageBox.Ask("Would you consider donating a mere $.99?", "Enjoy the App?", yes =>
            //						{
            //							if (yes)
            //							{
            //								_hub.Publish(new DonateMessage(this));
            //							}
            //							else
            //							{
            //								Refresh();
            //							}
            //						});
            //					}
            //					else
                    {
                        Refresh();
                    }
                }
            });
            _hub.Subscribe<AddTorrentMessage>(m =>
            {
                try
                {
                    _server.AddUrl(m.Url.Url);
                }
                catch (Exception exc)
                {
                    Execute.BeginInvoke(() => MessageBox.Show(exc.Message, "Error"));
                }
            });
            _settings = container.Resolve<Settings>();

            //Server
            _server = container.Resolve<Server>();
            _server.TorrentsChanged += (sender, e) => Execute.BeginInvoke(() =>
            {
                if (_tableView != null)
                {
                    _tableView.ReloadData();
                }
            });
            _server.TorrentsError += (sender, e) => Execute.BeginInvoke(() =>
            {
                MessageBox.Show("Could not get list of torrents: " + Environment.NewLine +
                                e.Exception.Message + Environment.NewLine +
                                "Press refresh to try again.", "Error");
            });
            _server.TorrentChanged += (sender, e) => _hub.Publish(new TorrentChangedMessage(this, false, e.Torrent));
            _server.TorrentRemoved += (sender, e) => _hub.Publish(new TorrentChangedMessage(this, true, e.Torrent));
        }