예제 #1
0
        private void WriteErrorOutput(object sender, EventArgs e)
        {
            var eventArgs = e as ScriptHubDataReceivedEventArgs;

            _errors.Add(eventArgs.Data);
            _logger.LogToFile(_currentScript.Name, eventArgs.Data);

            ErrorReceived.Invoke(sender, new ScriptHubDataReceivedEventArgs(eventArgs.Data));
        }
예제 #2
0
        private void ErrorMarshal(object o)
        {
            if (ErrorReceived == null)
            {
                return;
            }

            ErrorReceived.Invoke(this, (ZusiTcpException)o);
        }
        public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
        {
            if (IsConnected)
            {
                return;
            }

            using (var cts = new CancellationTokenSource(_options.ConnectTimeout))
            {
                _socket = await _client.ConnectAsync(uri, cts.Token).ConfigureAwait(false);

                Connected.Invoke(this, EventArgs.Empty);
            }

            var recvTask = Task.Factory.StartNew(async() =>
            {
                try
                {
                    while (_socket.IsConnected && !cancellationToken.IsCancellationRequested)
                    {
                        var readStream = await _socket.ReadMessageAsync(cancellationToken).ConfigureAwait(false);
                        if (readStream == null)
                        {
                            continue; // NOTE does stream need to be consumed?
                        }

                        using (var reader = new StreamReader(readStream, true))
                        {
                            var message = await reader.ReadToEndAsync().ConfigureAwait(false);
                            MessageReceived.Invoke(this, message);
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrorReceived.Invoke(this, e);
                }
                finally
                {
                    Disconnected.Invoke(this, EventArgs.Empty);
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);

            await recvTask.ConfigureAwait(false);
        }
예제 #4
0
 private void ErrorOutput(object sender, DataReceivedEventArgs e)
 {
     if (e.Data == " ")
     {
         if (!string.IsNullOrEmpty(_currentError))
         {
             if (ErrorReceived != null)
             {
                 ErrorReceived.Invoke(sender, new ScriptHubDataReceivedEventArgs(_currentError));
             }
         }
         _currentError = string.Empty;
     }
     else
     {
         _currentError += e.Data;
     }
 }
예제 #5
0
 protected virtual void OnErrorReceived(ProgramOutputReceivedEventArgs e)
 {
     ErrorReceived?.Invoke(this, e);
 }
예제 #6
0
 public void TestErrorReceived(SerialErrorReceivedEventArgs args)
 {
     ErrorReceived?.Invoke(
         this,
         args);
 }
        public void Connect(Uri aURL, bool aIgnoreSSLErrors = false)
        {
            if (_ws != null && (_ws.State == WebSocketState.Connecting || _ws.State == WebSocketState.Open))
            {
                throw new InvalidOperationException("Already connected!");
            }

            _bpLogger.Trace("Opening connection");
            _ws = new WebSocket(aURL.ToString());
            _waitingMsgs.Clear();
            _devices.Clear();
            _counter = 1;

            _connectedOrFailed = new TaskCompletionSource <bool>();
            _disconnected      = new TaskCompletionSource <bool>();

            _ws.Opened += OpenedHandler;
            _ws.Closed += ClosedHandler;
            _ws.Error  += ErrorHandler;

            if (aIgnoreSSLErrors)
            {
                _ws.Security.AllowNameMismatchCertificate = true;
                _ws.Security.AllowUnstrustedCertificate   = true;
                _ws.Security.AllowCertificateChainErrors  = true;
            }

            _ws.Open();

            _connecting = true;
            _connectedOrFailed.Task.Wait();
            _connecting = false;

            if (_ws.State != WebSocketState.Open)
            {
                throw new Exception("Connection failed!");
            }
            _bpLogger.Trace("Connected");

            _ws.MessageReceived += MessageReceivedHandler;

            var res = SendMessage(new RequestServerInfo(_clientName)).Result;

            switch (res)
            {
            case ServerInfo si:
                if (si.MaxPingTime > 0)
                {
                    _pingTimer = new Timer(OnPingTimer, null, 0, Convert.ToInt32(Math.Round(((double)si.MaxPingTime) / 2, 0)));
                }

                if (si.MessageVersion < 1)
                {
                    throw new Exception("B******g Server's schema version (" + si.MessageVersion +
                                        ") is less than the client's (" + 1 +
                                        "). A newer server is required.");
                }

                // Get full device list and populate internal list
                var resp = SendMessage(new RequestDeviceList()).Result;
                if ((resp as DeviceList)?.Devices == null)
                {
                    if (resp is Error)
                    {
                        _owningDispatcher.Send(_ =>
                        {
                            ErrorReceived?.Invoke(this, new ErrorEventArgs(resp as Error));
                        }, null);
                    }

                    return;
                }

                foreach (var d in (resp as DeviceList).Devices)
                {
                    if (_devices.ContainsKey(d.DeviceIndex))
                    {
                        continue;
                    }

                    var device = new ButtplugClientDevice(d);
                    if (_devices.TryAdd(d.DeviceIndex, device))
                    {
                        _owningDispatcher.Send(_ =>
                        {
                            DeviceAdded?.Invoke(this, new DeviceEventArgs(device, DeviceEventArgs.DeviceAction.ADDED));
                        }, null);
                    }
                }

                break;

            case Error e:
                throw new Exception(e.ErrorMessage);

            default:
                throw new Exception("Unexpecte message returned: " + res.GetType());
            }
        }
예제 #8
0
 /// <summary>
 /// Fires when data is received from the chess engine.
 /// </summary>
 /// <param name="sender">Object that raised the event.</param>
 /// <param name="e">Event arguments received from the chess engine.</param>
 protected virtual void OnRaiseErrorReceived(object sender, ChessCommandReceivedEventArgs e)
 {
     ErrorReceived?.Invoke(sender, e);
 }
예제 #9
0
 protected virtual void OnErrorReceived(ErrorEventArgs args)
 {
     Log.Error(args.Exception, "Socket connection");
     ErrorReceived?.Invoke(new BitmextErrorEventArgs(args.Exception));
 }
예제 #10
0
        protected void SorterCallbackHandler(IntPtr buf, int buf_length)
        {
            // Process the data BEFORE we throw to the C# executor, otherwise
            // Rust will clean up the memory and we'll have nothing to read
            // from, meaning a null message at best and a crash at worst.
            Span <byte> byteArray;

            unsafe
            {
                byteArray = new Span <byte>(buf.ToPointer(), buf_length);
            }
            var server_message = ButtplugFFIServerMessage.Parser.ParseFrom(byteArray.ToArray());

            // Run the response in the context of the C# executor, not the Rust
            // thread. This means that if something goes wrong we at least
            // aren't blocking a rust executor thread.
            Task.Run(() =>
            {
                if (server_message.Id > 0)
                {
                    _messageSorter.CheckMessage(server_message);
                }
                else if (server_message.Message.MsgCase == ButtplugFFIServerMessage.Types.FFIMessage.MsgOneofCase.ServerMessage)
                {
                    if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.DeviceAdded)
                    {
                        var device_added_message = server_message.Message.ServerMessage.DeviceAdded;
                        if (_devices.ContainsKey(device_added_message.Index))
                        {
                            ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(new ButtplugDeviceException("A duplicate device index was received. This is most likely a bug, please file at https://github.com/buttplugio/b******g-rs-ffi")));
                            return;
                        }
                        var device_handle  = ButtplugFFI.SendCreateDevice(_clientHandle, device_added_message.Index);
                        var attribute_dict = new Dictionary <ServerMessage.Types.MessageAttributeType, ButtplugMessageAttributes>();
                        for (var i = 0; i < device_added_message.MessageAttributes.Count; ++i)
                        {
                            var attributes = device_added_message.MessageAttributes[i];
                            var device_message_attributes = new ButtplugMessageAttributes(attributes.FeatureCount, attributes.StepCount.ToArray(),
                                                                                          attributes.Endpoints.ToArray(), attributes.MaxDuration.ToArray(), null, null);
                            attribute_dict.Add(attributes.MessageType, device_message_attributes);
                        }
                        var device = new ButtplugClientDevice(_messageSorter, device_handle, device_added_message.Index, device_added_message.Name, attribute_dict, SorterCallbackDelegate, GCHandle.ToIntPtr(_indexHandle));
                        _devices.Add(device_added_message.Index, device);
                        DeviceAdded?.Invoke(this, new DeviceAddedEventArgs(device));
                    }
                    else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.DeviceRemoved)
                    {
                        var device_removed_message = server_message.Message.ServerMessage.DeviceRemoved;
                        if (!_devices.ContainsKey(device_removed_message.Index))
                        {
                            // Device was removed from our dict before we could remove it ourselves.
                            return;
                        }
                        try
                        {
                            var device = _devices[device_removed_message.Index];
                            _devices.Remove(device_removed_message.Index);
                            DeviceRemoved?.Invoke(this, new DeviceRemovedEventArgs(device));
                        }
                        catch (KeyNotFoundException)
                        {
                            ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(new ButtplugDeviceException($"Cannot remove device index {device_removed_message.Index}, device not found.")));
                        }
                    }
                    else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.Disconnect)
                    {
                        Connected = false;
                        _devices.Clear();
                        ServerDisconnect?.Invoke(this, null);
                    }
                    else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.Error)
                    {
                        var errorMsg = server_message.Message.ServerMessage.Error;
                        var error    = ButtplugException.FromError(errorMsg);
                        if (error is ButtplugPingException)
                        {
                            PingTimeout?.Invoke(this, null);
                        }
                        ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(error));
                    }
                    else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.ScanningFinished)
                    {
                        IsScanning = false;
                        ScanningFinished?.Invoke(this, null);
                    }
                    else
                    {
                        // We should probably do something here with unhandled events, but I'm not particularly sure what. I miss pattern matching. :(
                    }
                }
                else
                {
                    // We should probably do something here with unhandled events, but I'm not particularly sure what. I miss pattern matching. :(
                }
            });
        }
예제 #11
0
 protected virtual void OnErrorReceived(ErrorEventArgs args)
 {
     ErrorReceived?.Invoke(new BitmextErrorEventArgs(args.Exception));
 }
예제 #12
0
 void ErrorResponse(ErrorResponse status)
 {
     //fire the event
     ErrorReceived?.Invoke(this, new DataEventArg <ErrorResponse>(status));
 }
예제 #13
0
 public void HandleErrorReceived(object sender, ErrorReceivedEventArgs e)
 {
     ErrorReceived?.Invoke(this, e);
 }
예제 #14
0
 private void Port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
 {
     ErrorReceived?.Invoke(sender, e);
 }
예제 #15
0
 private void OnErrorReceived(string errorMessage)
 {
     ErrorReceived?.Invoke(errorMessage);
 }
예제 #16
0
 protected virtual void OnErrorReceived(string data)
 {
     ErrorReceived?.Invoke(this, data);
 }
예제 #17
0
        private void OnMessage(object sender, MessageEventArgs e)
        {
            if (!e.IsText)
            {
                return;
            }

            var container = JsonConvert.DeserializeObject <MessageContainer>(e.Data);

            switch (container.Identifier)
            {
            case nameof(ConnectionResponse):
                var connectionResponse = ((JObject)container.Payload).ToObject(typeof(ConnectionResponse)) as ConnectionResponse;
                if (connectionResponse.Result == ResultCode.Failure)
                {
                    Username = string.Empty;
                    string source = string.Empty;
                    ErrorReceived?.Invoke(this, new ErrorReceivedEventArgs(connectionResponse.Reason, connectionResponse.Date));
                }
                if (!String.IsNullOrEmpty(Username))
                {
                    ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(Username, true, DateTime.Now, connectionResponse.ActiveUsers));
                }
                break;

            case nameof(ConnectionBroadcast):
                var connectionBroadcast = ((JObject)container.Payload).ToObject(typeof(ConnectionBroadcast)) as ConnectionBroadcast;
                if (connectionBroadcast.Username != Username)
                {
                    ConnectionReceived?.Invoke(this, new ConnectionReceivedEventArgs(connectionBroadcast.Username, connectionBroadcast.IsConnected, connectionBroadcast.Date));
                }
                break;

            case nameof(MessageBroadcast):
                var messageBroadcast = ((JObject)container.Payload).ToObject(typeof(MessageBroadcast)) as MessageBroadcast;
                MessageReceived?.Invoke(this, new MessageReceivedEventArgs(messageBroadcast.Source, messageBroadcast.Target, messageBroadcast.Message, messageBroadcast.Groupname, messageBroadcast.Date));
                break;

            case nameof(UserListResponse):
                var userListResponse = ((JObject)container.Payload).ToObject(typeof(UserListResponse)) as UserListResponse;
                UsersReceived?.Invoke(this, new UsersReceivedEventArgs(userListResponse.UserList));
                break;

            case nameof(MessageHistoryResponse):
                var messageHistoryResponse = ((JObject)container.Payload).ToObject(typeof(MessageHistoryResponse)) as MessageHistoryResponse;
                MessageHistoryReceived?.Invoke(this, new MessageHistoryReceivedEventArgs(messageHistoryResponse.GroupMessages));
                break;

            case nameof(FiltrationResponse):
                var filterResponse = ((JObject)container.Payload).ToObject(typeof(FiltrationResponse)) as FiltrationResponse;
                FilteredLogsReceived?.Invoke(this, new FilteredLogsReceivedEventArgs(filterResponse.FilteredLogs));
                break;

            case nameof(GroupListResponse):
                var groupsListResponse = ((JObject)container.Payload).ToObject(typeof(GroupListResponse)) as GroupListResponse;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupsListResponse.Groups));
                break;

            case nameof(GroupBroadcast):
                var groupBroadcast = ((JObject)container.Payload).ToObject(typeof(GroupBroadcast)) as GroupBroadcast;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupBroadcast.Groupname));
                break;
            }
        }
예제 #18
0
 public void RaiseErrorReceived(string message)
 {
     ErrorReceived?.Invoke(this, message);
 }
예제 #19
0
        private async void wsReader(CancellationToken aToken)
        {
            var sb = new StringBuilder();

            while (_ws != null && _ws.State == WebSocketState.Open && !aToken.IsCancellationRequested)
            {
                try
                {
                    var buffer  = new byte[5];
                    var segment = new ArraySegment <byte>(buffer);
                    WebSocketReceiveResult result;
                    try
                    {
                        result = await _ws.ReceiveAsync(segment, aToken);
                    }
                    catch (OperationCanceledException)
                    {
                        // If the operation is cancelled, just continue so we fall out of the loop
                        continue;
                    }

                    var input = Encoding.UTF8.GetString(buffer, 0, result.Count);

                    sb.Append(input);
                    if (result.EndOfMessage)
                    {
                        var msgs = Deserialize(sb.ToString());
                        foreach (var msg in msgs)
                        {
                            if (msg.Id > 0 && _waitingMsgs.TryRemove(msg.Id, out TaskCompletionSource <ButtplugMessage> queued))
                            {
                                queued.TrySetResult(msg);
                                continue;
                            }

                            switch (msg)
                            {
                            case Log l:
                                _owningDispatcher.Invoke(() =>
                                {
                                    Log?.Invoke(this, new LogEventArgs(l));
                                });
                                break;

                            case DeviceAdded d:
                                var dev = new ButtplugClientDevice(d);
                                _devices.AddOrUpdate(d.DeviceIndex, dev, (idx, old) => dev);
                                _owningDispatcher.Invoke(() =>
                                {
                                    DeviceAdded?.Invoke(this, new DeviceEventArgs(dev, DeviceAction.ADDED));
                                });
                                break;

                            case DeviceRemoved d:
                                if (_devices.TryRemove(d.DeviceIndex, out ButtplugClientDevice oldDev))
                                {
                                    _owningDispatcher.Invoke(() =>
                                    {
                                        DeviceRemoved?.Invoke(this, new DeviceEventArgs(oldDev, DeviceAction.REMOVED));
                                    });
                                }

                                break;

                            case ScanningFinished sf:
                                _owningDispatcher.Invoke(() =>
                                {
                                    ScanningFinished?.Invoke(this, new ScanningFinishedEventArgs(sf));
                                });
                                break;

                            case Error e:
                                _owningDispatcher.Invoke(() =>
                                {
                                    ErrorReceived?.Invoke(this, new ErrorEventArgs(e));
                                });
                                break;
                            }
                        }

                        sb.Clear();
                    }
                }
                catch (WebSocketException)
                {
                    // Noop - WS probably closed on us during read
                }
            }
        }
예제 #20
0
 protected virtual void OnErrorReceived(Exception ex)
 {
     ErrorReceived?.Invoke(this, ex);
 }
예제 #21
0
 private void ConnectorErrorHandler(object aSender, ButtplugExceptionEventArgs aException)
 {
     ErrorReceived?.Invoke(this, aException);
 }
예제 #22
0
        public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
        {
            if (IsConnected)
            {
                return;
            }

            using (var cts = new CancellationTokenSource(_options.ConnectTimeout))
            {
                _socket = await _client.ConnectAsync(uri, cts.Token).ConfigureAwait(false);

                Connected.Invoke(this, EventArgs.Empty);
            }

            var recvTask = Task.Factory.StartNew(async() =>
            {
                try
                {
                    while (_socket.IsConnected && !cancellationToken.IsCancellationRequested)
                    {
                        var readStream = await _socket.ReadMessageAsync(cancellationToken).ConfigureAwait(false);
                        if (readStream == null)
                        {
                            continue; // NOTE does stream need to be consumed?
                        }

                        using (var reader = new StreamReader(readStream, true))
                        {
                            var message = await reader.ReadToEndAsync().ConfigureAwait(false);
                            MessageReceived.Invoke(this, message);
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrorReceived.Invoke(this, e);
                }
                finally
                {
                    Disconnected.Invoke(this, EventArgs.Empty);
                    _sendQueue.CompleteAdding();
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);

            var cts2     = new CancellationTokenSource();
            var sendTask = Task.Factory.StartNew(async() =>
            {
                try
                {
                    foreach (var item in _sendQueue.GetConsumingEnumerable(cts2.Token))
                    {
                        using (var output = _socket.CreateMessageWriter(WebSocketMessageType.Text))
                            using (var writer = new StreamWriter(output))
                            {
                                writer.Write(item);
                            }
                    }
                }
                catch (Exception e)
                {
                    ErrorReceived?.Invoke(this, e);
                }
                finally
                {
                    // Setup a new send queue.
                    _sendQueue = new BlockingCollection <string>(256);
                }
            }, cts2.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

#pragma warning disable 4014
            Task.WhenAll(recvTask, sendTask);
#pragma warning restore 4014
        }
 protected virtual void OnErrorReceived(ErrorEventArgs e) => ErrorReceived?.Invoke(this, e);
예제 #24
0
 private void OnErrorReceived(TLSerialErrorReceivedEventArgs e)
 {
     ErrorReceived?.Invoke(this, e);
 }
예제 #25
0
 /// <summary>
 /// Triggers the <see cref="ErrorReceived"/> event.
 /// </summary>
 /// <param name="e">Passes <see cref="DiscoveryProtocolErrorArgs"/> to the event.</param>
 protected virtual void OnErrorReceived(DiscoveryProtocolErrorArgs e)
 {
     ErrorReceived?.Invoke(this, e);
 }
예제 #26
0
        private void OnMessage(object sender, MessageEventArgs e)
        {
            if (!e.IsText)
            {
                return;
            }

            var container = JsonConvert.DeserializeObject <MessageContainer>(e.Data);

            switch (container.Identifier)
            {
            case nameof(ConnectionResponse):
                var connectionResponse = ((JObject)container.Payload).ToObject(typeof(ConnectionResponse)) as ConnectionResponse;
                if (connectionResponse.Result == ResultCodes.Failure)
                {
                    Login = string.Empty;
                    string source = string.Empty;
                    ErrorReceived?.Invoke(this, new ErrorReceivedEventArgs(connectionResponse.Reason, connectionResponse.Date));
                }
                if (!String.IsNullOrEmpty(Login))
                {
                    ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(Login, DateTime.Now, true, connectionResponse.OnlineClients));
                }
                break;

            case nameof(ConnectionBroadcast):
                var connectionBroadcast = ((JObject)container.Payload).ToObject(typeof(ConnectionBroadcast)) as ConnectionBroadcast;
                if (connectionBroadcast.Login != Login)
                {
                    ConnectionReceived?.Invoke(this, new ConnectionReceivedEventArgs(connectionBroadcast.Login, connectionBroadcast.IsConnected, connectionBroadcast.Date));
                }
                break;

            case nameof(MessageBroadcast):
                var messageBroadcast = ((JObject)container.Payload).ToObject(typeof(MessageBroadcast)) as MessageBroadcast;
                MessageReceived?.Invoke(this, new MessageReceivedEventArgs(messageBroadcast.Source, messageBroadcast.Target, messageBroadcast.Message, messageBroadcast.Date,
                                                                           messageBroadcast.GroupName));
                break;

            case nameof(ClientsListResponse):
                var clientsListResponse = ((JObject)container.Payload).ToObject(typeof(ClientsListResponse)) as ClientsListResponse;
                ClientsListReceived?.Invoke(this, new ClientsListReceivedEventArgs(clientsListResponse.Clients));
                break;

            case nameof(ChatHistoryResponse):
                var chatHistoryResponse = ((JObject)container.Payload).ToObject(typeof(ChatHistoryResponse)) as ChatHistoryResponse;
                ChatHistoryReceived?.Invoke(this, new ChatHistoryReceivedEventArgs(chatHistoryResponse.ClientMessages));
                break;

            case nameof(FilterResponse):
                var filterResponse = ((JObject)container.Payload).ToObject(typeof(FilterResponse)) as FilterResponse;
                FilteredMessagesReceived?.Invoke(this, new FilteredMessagesReceivedEventArgs(filterResponse.FilteredMessages));
                break;

            case nameof(GroupsListResponse):
                var groupsListResponse = ((JObject)container.Payload).ToObject(typeof(GroupsListResponse)) as GroupsListResponse;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupsListResponse.Groups));
                break;

            case nameof(GroupBroadcast):
                var groupBroadcast = ((JObject)container.Payload).ToObject(typeof(GroupBroadcast)) as GroupBroadcast;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupBroadcast.Group));
                break;
            }
        }
예제 #27
0
        /// <summary>
        /// Invokes youtube-dl with the specified parameters and options.
        /// </summary>
        /// <param name="urls">The video URLs to be passed to youtube-dl.</param>
        /// <param name="options">An OptionSet specifying the options to be passed to youtube-dl.</param>
        /// <param name="ct">A CancellationToken used to cancel the download.</param>
        /// <param name="progress">A progress provider used to get download progress information.</param>
        /// <returns>The exit code of the youtube-dl process.</returns>
        public async Task <int> RunAsync(string[] urls, OptionSet options,
                                         CancellationToken ct, IProgress <DownloadProgress> progress = null)
        {
            var tcs       = new TaskCompletionSource <int>();
            var process   = new Process();
            var startInfo = new ProcessStartInfo()
            {
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            if (!String.IsNullOrEmpty(PythonPath))
            {
                startInfo.FileName  = PythonPath;
                startInfo.Arguments = $"\"{ExecutablePath}\" {ConvertToArgs(urls, options)}";
            }
            else
            {
                startInfo.FileName  = ExecutablePath;
                startInfo.Arguments = ConvertToArgs(urls, options);
            }
            process.EnableRaisingEvents = true;
            process.StartInfo           = startInfo;
            var tcsOut = new TaskCompletionSource <bool>();
            // this variable is used for tracking download states
            bool isDownloading = false;

            process.OutputDataReceived += (o, e) =>
            {
                if (e.Data == null)
                {
                    tcsOut.SetResult(true);
                    return;
                }
                Match match;
                if ((match = rgxProgress.Match(e.Data)).Success)
                {
                    if (match.Groups.Count > 1 && match.Groups[1].Length > 0)
                    {
                        float  progValue  = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100.0f;
                        Group  totalGroup = match.Groups["total"];
                        string total      = totalGroup.Success ? totalGroup.Value : null;
                        Group  speedGroup = match.Groups["speed"];
                        string speed      = speedGroup.Success ? speedGroup.Value : null;
                        Group  etaGroup   = match.Groups["eta"];
                        string eta        = etaGroup.Success ? etaGroup.Value : null;
                        progress?.Report(
                            new DownloadProgress(
                                DownloadState.Downloading, progress: progValue, totalDownloadSize: total, downloadSpeed: speed, eta: eta
                                )
                            );
                    }
                    else
                    {
                        progress?.Report(new DownloadProgress(DownloadState.Downloading));
                    }
                    isDownloading = true;
                }
                else if ((match = rgxPlaylist.Match(e.Data)).Success)
                {
                    var index = int.Parse(match.Groups[1].Value);
                    progress?.Report(new DownloadProgress(DownloadState.PreProcessing, index: index));
                    isDownloading = false;
                }
                else if (isDownloading && (match = rgxPost.Match(e.Data)).Success)
                {
                    progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1));
                    isDownloading = false;
                }
                Debug.WriteLine("[youtube-dl] " + e.Data);
                OutputReceived?.Invoke(this, e);
            };
            var tcsError = new TaskCompletionSource <bool>();

            process.ErrorDataReceived += (o, e) =>
            {
                if (e.Data == null)
                {
                    tcsError.SetResult(true);
                    return;
                }
                Debug.WriteLine("[youtube-dl ERROR] " + e.Data);
                progress?.Report(new DownloadProgress(DownloadState.Error, data: e.Data));
                ErrorReceived?.Invoke(this, e);
            };
            process.Exited += async(sender, args) =>
            {
                // Wait for output and error streams to finish
                await tcsOut.Task;
                await tcsError.Task;
                tcs.TrySetResult(process.ExitCode);
                process.Dispose();
            };
            ct.Register(() =>
            {
                if (!tcs.Task.IsCompleted)
                {
                    tcs.TrySetCanceled();
                }
                try { if (!process.HasExited)
                      {
                          process.KillTree();
                      }
                }
                catch { }
            });
            Debug.WriteLine("[youtube-dl] Arguments: " + process.StartInfo.Arguments);
            if (!await Task.Run(() => process.Start()))
            {
                tcs.TrySetException(new InvalidOperationException("Failed to start youtube-dl process."));
            }
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            progress?.Report(new DownloadProgress(DownloadState.PreProcessing));
            return(await tcs.Task);
        }
예제 #28
0
 private void RaiseError(string text)
 {
     ErrorReceived?.Invoke(this, new DriverEventArgs(DriverEventType.Error, text));
 }
예제 #29
0
        public void SorterCallback(UIntPtr buf, int buf_length)
        {
            Span <byte> byteArray;

            unsafe
            {
                byteArray = new Span <byte>(buf.ToPointer(), buf_length);
            }
            var server_message = ButtplugFFIServerMessage.Parser.ParseFrom(byteArray.ToArray());

            if (server_message.Id > 0)
            {
                _messageSorter.CheckMessage(server_message);
            }
            else if (server_message.Message.MsgCase == ButtplugFFIServerMessage.Types.FFIMessage.MsgOneofCase.ServerMessage)
            {
                if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.DeviceAdded)
                {
                    var device_added_message = server_message.Message.ServerMessage.DeviceAdded;
                    if (_devices.ContainsKey(device_added_message.Index))
                    {
                        ErrorReceived.Invoke(this, new ButtplugExceptionEventArgs(new ButtplugDeviceException("A duplicate device index was received. This is most likely a bug, please file at https://github.com/buttplugio/b******g-rs-ffi")));
                        return;
                    }
                    var device_handle  = ButtplugFFI.SendCreateDevice(_clientHandle, device_added_message.Index);
                    var attribute_dict = new Dictionary <ServerMessage.Types.MessageAttributeType, ButtplugMessageAttributes>();
                    for (var i = 0; i < device_added_message.MessageAttributes.Count; ++i)
                    {
                        var attributes = device_added_message.MessageAttributes[i];
                        var device_message_attributes = new ButtplugMessageAttributes(attributes.FeatureCount, attributes.StepCount.ToArray(),
                                                                                      attributes.Endpoints.ToArray(), attributes.MaxDuration.ToArray(), null, null);
                        attribute_dict.Add(attributes.MessageType, device_message_attributes);
                    }
                    var device = new ButtplugClientDevice(_messageSorter, device_handle, device_added_message.Index, device_added_message.Name, attribute_dict);
                    _devices.Add(device_added_message.Index, device);
                    DeviceAdded.Invoke(this, new DeviceAddedEventArgs(device));
                }
                else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.DeviceRemoved)
                {
                    var device_removed_message = server_message.Message.ServerMessage.DeviceRemoved;
                    var device = _devices[device_removed_message.Index];
                    _devices.Remove(device_removed_message.Index);
                    DeviceRemoved.Invoke(this, new DeviceRemovedEventArgs(device));
                }
                else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.Disconnect)
                {
                    Connected = false;
                    _devices.Clear();
                    ServerDisconnect?.Invoke(this, null);
                }
                else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.Error)
                {
                    var errorMsg = server_message.Message.ServerMessage.Error;
                    var error    = ButtplugException.FromError(errorMsg);
                    if (error is ButtplugPingException)
                    {
                        PingTimeout?.Invoke(this, null);
                    }
                    ErrorReceived?.Invoke(this, new ButtplugExceptionEventArgs(error));
                }
                else if (server_message.Message.ServerMessage.MsgCase == ServerMessage.MsgOneofCase.ScanningFinished)
                {
                    ScanningFinished?.Invoke(this, null);
                }
                else
                {
                    // We should probably do something here with unhandled events, but I'm not particularly sure what. I miss pattern matching. :(
                }
            }
            else
            {
                // We should probably do something here with unhandled events, but I'm not particularly sure what. I miss pattern matching. :(
            }
        }
예제 #30
0
 private void ProcessService_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     ConsoleAddText("ERROR! " + e.Data);
     ErrorReceived?.Invoke(this, new DriverEventArgs(DriverEventType.Error, e.Data));
 }