상속: Microsoft.AspNet.SignalR.PersistentConnection
예제 #1
0
        public IObservable <IStreamMessage> DirectAsObservable(string host = null)
        {
            var url        = ToUrl(host, "/api/v1/streaming/direct");
            var connection = new StreamingConnection(Client, url);

            return(connection.Connect());
        }
예제 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StreamingRequestHandler"/> class.
        /// </summary>
        /// <param name="bot">The bot for which we handle requests.</param>
        /// <param name="activityProcessor">The processor for incoming requests.</param>
        /// <param name="connection">Connection used to send requests to the transport.</param>
        /// <param name="audience">The specified recipient of all outgoing activities.</param>
        /// <param name="logger">Logger implementation for tracing and debugging information.</param>
        public StreamingRequestHandler(IBot bot, IStreamingActivityProcessor activityProcessor, StreamingConnection connection, string audience = null, ILogger logger = null)
        {
            _bot = bot ?? throw new ArgumentNullException(nameof(bot));
            _activityProcessor = activityProcessor ?? throw new ArgumentNullException(nameof(activityProcessor));
            _innerConnection   = connection ?? throw new ArgumentNullException(nameof(connection));
            _logger            = logger ?? NullLogger.Instance;

            Audience = audience;
        }
예제 #3
0
        public IObservable <IStreamMessage> LocalHashtagAsObservable(string tag, string host = null)
        {
            var url        = ToUrl(host, "/api/v1/streaming/hashtag/local");
            var parameters = new List <KeyValuePair <string, object> > {
                new KeyValuePair <string, object>("tag", AppClient.UrlEncode(tag))
            };
            var connection = new StreamingConnection(Client, url, parameters);

            return(connection.Connect());
        }
예제 #4
0
        public IObservable <IStreamMessage> LocalPublicAsObservable(bool isOnlyMedia, string host = null)
        {
            var url        = ToUrl(host, "/api/v1/streaming/public/local");
            var parameters = new List <KeyValuePair <string, object> > {
                new KeyValuePair <string, object>("only_media", isOnlyMedia.ToString().ToLower())
            };
            var connection = new StreamingConnection(Client, url, parameters);

            return(connection.Connect());
        }
예제 #5
0
        public IObservable <IStreamMessage> ListAsObservable(long id, string host = null)
        {
            var url        = ToUrl(host, "/api/v1/streaming/list");
            var parameters = new List <KeyValuePair <string, object> > {
                new KeyValuePair <string, object>("list", id)
            };
            var connection = new StreamingConnection(Client, url, parameters);

            return(connection.Connect());
        }
예제 #6
0
        public async Task ConnectAsync(string host = null)
        {
            var url        = $"wss://{(string.IsNullOrWhiteSpace(host) ? Client.Domain : host)}/streaming";
            var parameters = new List <KeyValuePair <string, object> > {
                new KeyValuePair <string, object>("i", Client.EncryptedAccessToken)
            };

            _connection = new StreamingConnection(Client, url, parameters);
            _observable = _connection.Connect();
            _disposable = _observable.Connect(); // start
            await _connection.WaitForConnectionEstablished().Stay();
        }
예제 #7
0
        public IObservable <IStreamMessage> DirectAsObservable(string host = null)
        {
            var url        = ToUrl(host, "/api/v1/streaming");
            var parameters = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("stream", "direct"),
                new KeyValuePair <string, object>("access_token", Client.AccessToken)
            };
            var connection = new StreamingConnection(Client, url, parameters);

            return(connection.Connect());
        }
        public async Task ConnectRecordingDataAsync(Socket socket)
        {
            if (socket == null)
            {
                throw new ArgumentNullException(nameof(socket));
            }

            streamingConnection = new StreamingConnection();
            streamingConnection.SetSocket(socket);
            await Task.Run(() =>
            {
                streamingConnection.SendStartStreamingResponse();
            });
        }
예제 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StreamingRequestHandler"/> class and
        /// establishes a connection over a WebSocket to a streaming channel.
        /// </summary>
        /// <remarks>
        /// The audience represents the recipient at the other end of the StreamingRequestHandler's
        /// streaming connection. Some acceptable audience values are as follows:
        /// <list>
        /// <item>- For Public Azure channels, use <see cref="Microsoft.Bot.Connector.Authentication.AuthenticationConstants.ToChannelFromBotOAuthScope"/>.</item>
        /// <item>- For Azure Government channels, use <see cref="Microsoft.Bot.Connector.Authentication.GovernmentAuthenticationConstants.ToChannelFromBotOAuthScope"/>.</item>
        /// </list>
        /// </remarks>
        /// <param name="bot">The bot for which we handle requests.</param>
        /// <param name="activityProcessor">The processor for incoming requests.</param>
        /// <param name="socket">The base socket to use when connecting to the channel.</param>
        /// <param name="logger">Logger implementation for tracing and debugging information.</param>
        /// <param name="audience">The specified recipient of all outgoing activities.</param>
        public StreamingRequestHandler(IBot bot, IStreamingActivityProcessor activityProcessor, WebSocket socket, string audience, ILogger logger = null)
        {
            _bot = bot ?? throw new ArgumentNullException(nameof(bot));
            _activityProcessor = activityProcessor ?? throw new ArgumentNullException(nameof(activityProcessor));

            if (socket == null)
            {
                throw new ArgumentNullException(nameof(socket));
            }

            Audience         = audience;
            _logger          = logger ?? NullLogger.Instance;
            _innerConnection = new LegacyStreamingConnection(socket, _logger, ServerDisconnected);
        }
예제 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StreamingRequestHandler"/> class and
        /// establishes a connection over a Named Pipe to a streaming channel.
        /// </summary>
        /// <remarks>
        /// The audience represents the recipient at the other end of the StreamingRequestHandler's
        /// streaming connection. Some acceptable audience values are as follows:
        /// <list>
        /// <item>- For Public Azure channels, use <see cref="Microsoft.Bot.Connector.Authentication.AuthenticationConstants.ToChannelFromBotOAuthScope"/>.</item>
        /// <item>- For Azure Government channels, use <see cref="Microsoft.Bot.Connector.Authentication.GovernmentAuthenticationConstants.ToChannelFromBotOAuthScope"/>.</item>
        /// </list>
        /// </remarks>
        /// <param name="bot">The bot for which we handle requests.</param>
        /// <param name="activityProcessor">The processor for incoming requests.</param>
        /// <param name="pipeName">The name of the Named Pipe to use when connecting to the channel.</param>
        /// <param name="logger">Logger implementation for tracing and debugging information.</param>
        /// <param name="audience">The specified recipient of all outgoing activities.</param>
        public StreamingRequestHandler(IBot bot, IStreamingActivityProcessor activityProcessor, string pipeName, string audience, ILogger logger = null)
        {
            _bot = bot ?? throw new ArgumentNullException(nameof(bot));
            _activityProcessor = activityProcessor ?? throw new ArgumentNullException(nameof(activityProcessor));
            _logger            = logger ?? NullLogger.Instance;

            if (string.IsNullOrWhiteSpace(pipeName))
            {
                throw new ArgumentNullException(nameof(pipeName));
            }

            Audience         = audience;
            _innerConnection = new LegacyStreamingConnection(pipeName, _logger, ServerDisconnected);
        }
예제 #11
0
 private void Dispose(bool disposing)
 {
     System.Diagnostics.Debug.WriteLine("Disposing:" + AccountInfo.ToString());
     if (this.disposed)
     {
         return;
     }
     this.disposed = true;
     if (this.connection != null)
     {
         this.connection.Dispose();
     }
     this.connection = null;
 }
        public async Task SendRecordingDataAsync(ArraySegment <byte> dataToSend, WaveFormat format)
        {
            if (streamingConnection == null)
            {
                return;
            }

            if (streamingConnection.IsConnected)
            {
                await Task.Run(() => streamingConnection?.SendData(dataToSend, format));
            }
            else
            {
                streamingConnection = null;
            }
        }
예제 #13
0
            public StreamingActivityProcessor(AuthenticateRequestResult authenticateRequestResult, StreamingConnection connection, CloudAdapter adapter, IBot bot)
            {
                _authenticateRequestResult = authenticateRequestResult;
                _adapter = adapter;

                // Internal reuse of the existing StreamingRequestHandler class
                _requestHandler = new StreamingRequestHandler(bot, this, connection, authenticateRequestResult.Audience, logger: adapter.Logger);

                // Fix up the connector factory so connector create from it will send over this connection
                _authenticateRequestResult.ConnectorFactory = new StreamingConnectorFactory(_requestHandler);
            }
예제 #14
0
 public StreamingTestCloudAdapter(BotFrameworkAuthentication auth, StreamingConnection connection)
     : base(auth)
 {
     _connection = connection;
 }
예제 #15
0
 /// <summary>
 /// 内包しているStreamingConnectionが渡されたインスタンスと同一であるか確認します。
 /// </summary>
 internal bool CheckUsingConnection(StreamingConnection con)
 {
     return(this.connection == con);
 }
예제 #16
0
        /// <summary>
        /// ストリーミングAPIへ接続します。<para />
        /// 接続に失敗した場合、規定アルゴリズムに沿って自動で再接続を試みます。<para />
        /// それでも失敗する場合はfalseを返します。この場合、再接続を試みてはいけません。
        /// </summary>
        /// <param name="track">トラック対象キーワード</param>
        private void ConnectCore(AccountInfo info, string track)
        {
            try
            {
                int failureWaitSec = 0;
                while (true)
                {
                    // 接続
                    try
                    {
                        using (var n = NotifyStorage.NotifyManually("@" + info.ScreenName + ": インターネットへの接続を確認しています..."))
                        {
                            while (!NetworkInterface.GetIsNetworkAvailable())
                            {
                                info.ConnectionState = ConnectionState.WaitNetwork;
                                ConnectionManager.OnConnectionStateChanged(EventArgs.Empty);
                                // ネットワークが利用可能になるまでポーリング
                                Thread.Sleep(10000);
                            }
                        }

                        using (var n = NotifyStorage.NotifyManually("@" + info.ScreenName + ": 接続しています..."))
                        {
                            info.ConnectionState = ConnectionState.TryConnection;
                            ConnectionManager.OnConnectionStateChanged(EventArgs.Empty);
                            System.Diagnostics.Debug.WriteLine(info.ScreenName + " - User Streams Connection with Track: " + track);
                            connection = streamingCore.ConnectNew(
                                info, StreamingDescription.ForUserStreams(TwitterDefine.UserStreamsTimeout,
                                                                          track: track, repliesAll: info.AccountProperty.UserStreamsRepliesAll));
                        }
                    }
                    catch (WebException we)
                    {
                        if ((int)we.Status == 420)
                        {
                            // 多重接続されている
                            throw new WebException("@" + info.ScreenName + ": 多重接続されています。接続できません。");
                        }

                        if (we.Status == WebExceptionStatus.Timeout) // タイムアウト例外なら再試行する
                        {
                            NotifyStorage.Notify("@" + info.ScreenName + ": User Streams接続がタイムアウトしました。再試行します...");
                        }
                        else
                        {
                            string descText = we.Status.ToString();
                            if (we.Status == WebExceptionStatus.UnknownError)
                            {
                                descText = we.Message;
                            }
                            if (we.Status == WebExceptionStatus.ProtocolError)
                            {
                                var hwr = we.Response as HttpWebResponse;
                                if (hwr != null)
                                {
                                    descText += " - " + hwr.StatusCode + " : " + hwr.StatusDescription;
                                }
                            }
                            throw new WebException("接続に失敗しました。(" + descText + ")");
                        }
                    }
                    catch
                    {
                        throw;
                    }

                    if (connection != null)
                    {
                        // Connection successful
                        info.ConnectionState = ConnectionState.Connected;
                        ConnectionManager.OnConnectionStateChanged(EventArgs.Empty);
                        return;
                    }

                    if (failureWaitSec > 0)
                    {
                        if (failureWaitSec > Setting.Instance.ConnectionProperty.UserStreamsConnectionFailedMaxWaitSec)
                        {
                            throw new WebException("User Streamsへの接続に失敗しました。");
                        }
                        else
                        {
                            NotifyStorage.Notify("@" + info.ScreenName + ": User Streamsへの接続に失敗。再試行まで" + failureWaitSec.ToString() + "秒待機...", failureWaitSec / 1000);

                            // ウェイトカウント
                            Thread.Sleep(failureWaitSec * 1000);
                            NotifyStorage.Notify("@" + info.ScreenName + ": User Streamsへの接続を再試行します...");
                        }
                    }
                    else
                    {
                        NotifyStorage.Notify("@" + info.ScreenName + ": User Streamsへの接続に失敗しました。再試行します...");
                    }

                    // 最初に失敗したらすぐに再接続
                    // 2回目以降はその倍に増やしていく
                    // 300を超えたら接続失敗で戻る
                    if (failureWaitSec == 0)
                    {
                        failureWaitSec = Setting.Instance.ConnectionProperty.UserStreamsConnectionFailedInitialWaitSec;
                    }
                    else
                    {
                        failureWaitSec *= 2;
                    }
                }
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                this.AccountInfo.ConnectionState = ConnectionState.Disconnected;
                ConnectionManager.OnConnectionStateChanged(EventArgs.Empty);
                throw new WebException("User Streamsへの接続に失敗しました。", e);
            }
        }
예제 #17
0
 static void streamingCore_OnDisconnected(StreamingConnection con)
 {
     ConnectionManager.NotifyDisconnected(con.Provider as AccountInfo, con);
 }