public static void AddClient(TwitterCredential twitCred)
        {
            lock (Instances)
            {
                CurrentRevision++;

                TwitterClient twitClient;
                if (!Instances.ContainsKey(twitCred.Id))
                {
                    twitClient = new TwitterClient(twitCred);
                    twitClient.ClientUpdated += ClientStatusUpdatedEvent;

                    Instances.Add(twitCred.Id, twitClient);
                }
                else
                {
                    twitClient = Instances[twitCred.Id];
                    twitClient.Credential.ScreenName = twitCred.ScreenName;
                    twitClient.Credential.Cookie     = twitCred.Cookie;
                }

                ClientStatusUpdatedEvent(twitCred.Id, new StateUpdateData {
                    ScreenName = twitCred.ScreenName
                });

                Config.Save();
            }
        }
        public StreamingConnection(WaitableStream item, TwitterClient client)
        {
            this.Stream = item;
            this.Client = client;

            this.m_streamWriter = new StreamWriter(item, Encoding.UTF8, 4096, true);

            this.m_keepAlive = new Timer(this.SendKeepAlive, null, KeepAlivePeriod, KeepAlivePeriod);
            this.m_friends   = new Timer(this.SendFriends, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
        }
Пример #3
0
        /// <summary>
        /// Response 전송 하므로 사용에 주의
        /// 오류 발생 시 false 를 반환함. return 해줘야 함.
        /// </summary>
        private static bool TrySendDirectMessageThenSetContext(ProxyContext ctx, TwitterClient twitClient, string screenName, string text, out HttpStatusCode statusCode)
        {
            statusCode = 0;

            var userId = twitClient.UserCache.GetUserIdByScreenName(screenName);

            if (userId == 0)
            {
                // 유저 정보를 얻지 못하면 User.ID 를 얻지 못하므로 실패처리했다고 보낸다.
                // DM 으로 보낼 것 퍼블릭으로 작성하면 안됨.
                var reqUser = twitClient.Credential.CreateReqeust("GET", $"https://api.twitter.com/1.1/users/show.json?screen_name={Uri.EscapeUriString(screenName)}");
                if (!reqUser.Do <TwitterUser>(out var reqUserStatusCode, out var user) || reqUserStatusCode != HttpStatusCode.OK)
                {
                    ctx.Response.StatusCode = HttpStatusCode.InternalServerError;
                    return(true);
                }

                twitClient.UserCache.IsUpdated(user);
                userId = user.Id;
            }

            var dmData = new DirectMessageNew();

            dmData.Data.Type = "message_create";
            dmData.Data.MessageCreate.Target.RecipientId = userId.ToString();
            dmData.Data.MessageCreate.MessageData.Text   = text;

            var req = twitClient.Credential.CreateReqeust("POST", "https://api.twitter.com/1.1/direct_messages/events/new.json");

            req.ContentType = "application/json; charset=utf-8";

            using (var reqStream = req.GetRequestStream())
                using (var reqStreamWriter = new StreamWriter(reqStream))
                {
                    Program.JsonSerializer.Serialize(reqStreamWriter, dmData);
                    reqStreamWriter.Flush();
                }

            if (!req.Do(out statusCode))
            {
                return(false);
            }

            ctx.Response.StatusCode = statusCode;
            return(true);
        }
Пример #4
0
        private static HttpWebResponse CallAPI(ProxyContext ctx, Stream proxyReqBody, TwitterClient client)
        {
            var reqHttp = ctx.Request.CreateRequest((method, uri) => client?.Credential.CreateReqeust(method, uri), client == null);

            if (proxyReqBody == null)
            {
                proxyReqBody = ctx.Request.RequestBodyReader;
                var v = ctx.Request.Headers.Get("Content-Length");
                if (v != null)
                {
                    ctx.Response.Headers.Set("Content-Length", v);
                }
            }
            else if (proxyReqBody is MemoryStream mem)
            {
                ctx.Response.Headers.Set("Content-Length", mem.Length.ToString());
            }

            proxyReqBody?.CopyTo(reqHttp.GetRequestStream());

            HttpWebResponse resHttp = null;

            try
            {
                resHttp = reqHttp.GetResponse() as HttpWebResponse;
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    resHttp = webEx.Response as HttpWebResponse;
                }
                else
                {
                    SentrySdk.CaptureException(webEx);
                }
            }
            catch (Exception ex)
            {
                SentrySdk.CaptureException(ex);
            }

            return(resHttp);
        }
Пример #5
0
        private static bool TryCallAPIThenSetContext(ProxyContext ctx, Stream proxyReqBody, TwitterClient client, Type type, out HttpStatusCode responseStatusCode, out object response)
        {
            responseStatusCode = 0;
            response           = default;

            var resHttp = CallAPI(ctx, proxyReqBody, client);

            if (resHttp == null)
            {
                return(false);
            }

            using (resHttp)
            {
                responseStatusCode = resHttp.StatusCode;

                using (var stream = resHttp.GetResponseStream())
                {
                    if (type == null)
                    {
                        ctx.Response.FromHttpWebResponse(resHttp, stream);
                    }
                    else
                    {
                        using (var mem = new MemoryStream(Math.Min((int)resHttp.ContentLength, 4096)))
                        {
                            stream.CopyTo(mem);

                            mem.Position = 0;
                            ctx.Response.FromHttpWebResponse(resHttp, mem);

                            using (var reader = new StreamReader(mem, Encoding.UTF8))
                            {
                                mem.Position = 0;
                                response     = Program.JsonSerializer.Deserialize(reader, type);
                            }
                        }
                    }
                }
            }

            return(true);
        }
Пример #6
0
        /// <summary>
        /// Response 전송 하므로 사용에 주의
        /// 오류 발생 시 false 를 반환함. return 해줘야 함.
        /// </summary>
        private static bool TryCallAPIThenSetContext <T>(ProxyContext ctx, Stream proxyReqBody, TwitterClient client, out HttpStatusCode responseStatusCode, out T response)
            where T : class
        {
            var res = TryCallAPIThenSetContext(ctx, proxyReqBody, client, typeof(T), out responseStatusCode, out var obj);

            response = obj as T;
            return(res);
        }
Пример #7
0
 /// <summary>
 /// Response 전송 하므로 사용에 주의
 /// 오류 발생 시 false 를 반환함. return 해줘야 함.
 /// </summary>
 private static bool TryCallAPIThenSetContext(ProxyContext ctx, Stream proxyReqBody, TwitterClient client, out HttpStatusCode responseStatusCode)
 => TryCallAPIThenSetContext(ctx, proxyReqBody, client, null, out responseStatusCode, out _);
Пример #8
0
        private static bool TryGetTwitterClient(ProxyContext ctx, string requestBody, out TwitterClient twitClient)
        {
            twitClient = null;
            if (!TryGetOwnerId(ctx.Request.RequestUri, ctx.Request.Headers, requestBody, out var ownerId))
            {
                return(false);
            }

            twitClient = TwitterClientFactory.GetInsatnce(ownerId);
            if (twitClient == null)
            {
                return(false);
            }

            return(true);
        }