Exemplo n.º 1
0
        public override void handleGETRequest(HttpProcessor p)
        {
            var msgLoopRe = "^(.*)<!--.*MESSAGELOOP_BEGIN[^>]*-->(.*)<!--.*MESSAGELOOP_END[^>]*-->(.*)$";

            var requestUrl = new string( p.http_url.TakeWhile(c => c != '?').ToArray());

            if (requestUrl.Equals("/"))
            {
                requestUrl = "index.htm";
            }

            var contentType = ContentTypes.Where(kvp => requestUrl.ToLower().Contains(kvp.Key)).Select(item => item.Value).FirstOrDefault();

            if (!String.IsNullOrEmpty(contentType))
            {
                var path = webFolder + requestUrl.Replace("/", @"\");
                p.outputStream.AutoFlush = true;
                p.writeSuccess(contentType);
                if (contentType == "text/html")
                {
                    var content = File.ReadAllText(path);
                    if (content.Contains("MESSAGELOOP_BEGIN"))
                    {
                        var header      = Re.GetSubString(content, msgLoopRe, 1);
                        var footer      = Re.GetSubString(content, msgLoopRe, 3);
                        var loopblock   = Re.GetSubString(content, msgLoopRe, 2);
                        var loopcontent = "";
                        foreach (var line in Messages)
                        {
                            loopcontent += line.ParseChatTemplate(loopblock);
                        }
                        p.outputStream.Write(header + loopcontent + footer);
                    }
                    else if (requestUrl.Contains("statusbar.htm"))
                    {
                        content = ParseStatusBarTemplate(content);
                        try
                        {
                            p.outputStream.Write(content);
                        }
                        catch { }
                    }
                    else
                    {
                        using (Stream fs = File.Open(path, FileMode.Open))
                        {
                            fs.CopyTo(p.outputStream.BaseStream);
                        }
                    }
                }
                else
                {
                    using (Stream fs = File.Open(path, FileMode.Open))
                    {
                        fs.CopyTo(p.outputStream.BaseStream);
                    }
                }
            }
            Debug.Print("request: {0}", p.http_url);
        }
Exemplo n.º 2
0
        public void GetTopic()
        {
            if (!Status.IsLoggedIn || !Enabled)
            {
                return;
            }

            Task.Factory.StartNew(() =>
            {
                var content = GoodgameGet("http://goodgame.ru/");
                ownChannel  = Re.GetSubString(content, @"\/channel\/([^\/]+)\/add");

                content      = GoodgameGet(String.Format("http://goodgame.ru/chat/{0}/", ownChannel));
                ownChannelId = Re.GetSubString(content, @"channelId:[^\d]*(\d+)");

                if (!String.IsNullOrWhiteSpace(ownChannel))
                {
                    content = GoodgameGet(String.Format(@"http://goodgame.ru/channel/{0}", ownChannel));
                    if (!String.IsNullOrWhiteSpace(content))
                    {
                        Info.Topic            = Re.GetSubString(content, @"<title>([^<]*)</title>");
                        Info.CurrentGame.Name = this.With(x => Re.GetSubString(content, @"StreamTitleEdit[^,]*,[^,]*,[^,]*,[^,]*,[^']*'([^']*)'"))
                                                .With(x => x.Trim());
                        Info.CurrentGame.Id = this.With(x => Re.GetSubString(content, @"StreamTitleEdit[^,]*,[^,]*,[^,]*,([^,]*),[^']*'[^']*'"))
                                              .With(x => x.Trim());
                    }
                }
            });
        }
Exemplo n.º 3
0
 public void GetStreamId()
 {
     using (WebClientBase webClient = new WebClientBase())
     {
         var channelPage = webClient.Download(String.Format("http://sc2tv.ru/channel/{0}", ChannelName.Replace("#", "")));
         channelId = Re.GetSubString(channelPage, @"channelId=(\d+)");
     }
 }
Exemplo n.º 4
0
        public bool updateSmiles()
        {
            using (CookieAwareWebClient cwc = new CookieAwareWebClient())
            {
                System.IO.Stream stream = cwc.downloadURL(smilesJSUrl);
                using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
                {
                    if (stream == null)
                    {
                        return(false);
                    }
                    var content = reader.ReadToEnd().Replace("private:", "p:");
                    content = Re.GetSubString(content, "^(.*?];).*$", 1);
                    List <object> list = JSEvaluator.EvalArrayObject(content);
                    if (list == null)
                    {
                        return(false);
                    }

                    smiles.Clear();
                    foreach (object obj in list)
                    {
                        Smile smile = new Smile();
                        smile.Code   = JSEvaluator.ReadPropertyValue(obj, "code");
                        smile.Image  = JSEvaluator.ReadPropertyValue(obj, "img");
                        smile.Width  = int.Parse(JSEvaluator.ReadPropertyValue(obj, "width"));
                        smile.Height = int.Parse(JSEvaluator.ReadPropertyValue(obj, "height"));
                        try
                        {
                            Bitmap srcimage = new Bitmap(cwc.downloadURL(String.Format(smilesImagesUrl, smile.Image)));
                            srcimage  = resizeImage(srcimage, new Size(smile.Width, smile.Height));
                            smile.bmp = new Bitmap(smile.Width, smile.Height);
                            using (Graphics g = Graphics.FromImage(smile.bmp))
                            {
                                g.DrawImage(srcimage, 1, 1);
                            }
                        }
                        catch
                        {
                            smile.bmp = new Bitmap(30, 30);
                            using (Graphics g = Graphics.FromImage(smile.bmp))
                            {
                                g.Clear(Color.White);
                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(0, 0, 28, 28));
                                g.DrawString(smile.Code, new Font("Microsoft Sans Serif", 7), Brushes.Black, new RectangleF(0, 0, 28, 28));
                            }
                            Debug.Print("Exception in updateSmiles()");
                        }
                        smiles.Add(smile);
                    }
                }

                return(true);
            }
        }
Exemplo n.º 5
0
        private static void DataHandler(ConnectcastChannel channel, dynamic data)
        {
            if (data == null)
            {
                return;
            }

            string type = (string)data[0];

            if (String.IsNullOrWhiteSpace(type))
            {
                return;
            }

            if (type.StartsWith("update-chat", StringComparison.InvariantCultureIgnoreCase))
            {
                dynamic senderInfo = (dynamic)data[2];
                string  room       = (string)senderInfo["room"];

                if (String.IsNullOrWhiteSpace(room) ||
                    !room.Equals(channel.ChannelName.Replace("#", ""), StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                string name = (string)senderInfo["name"];

                string messageHtml = data[1];
                string text        = Re.GetSubString(messageHtml, "<p>(.*)</p>");

                if (String.IsNullOrWhiteSpace(name) ||
                    String.IsNullOrWhiteSpace(text))
                {
                    return;
                }

                channel.ChannelStats.MessagesCount++;
                channel.Chat.UpdateStats();

                if (channel.ReadMessage != null)
                {
                    channel.ReadMessage(new ChatMessage()
                    {
                        Channel         = channel.ChannelName,
                        ChatIconURL     = channel.Chat.IconURL,
                        ChatName        = channel.Chat.ChatName,
                        FromUserName    = name,
                        HighlyImportant = false,
                        IsSentByMe      = false,
                        Text            = text,
                    });
                }
            }
        }
Exemplo n.º 6
0
        private String GetCSRFToken(String content)
        {
            String csrf = Re.GetSubString(content, reAuthToken, 1);

            if (!String.IsNullOrEmpty(csrf))
            {
                csrf_token = csrf;
                loginWC.setCookie("csrf_token", csrf_token, "twitch.tv" + domain);
            }
            return(csrf);
        }
Exemplo n.º 7
0
        public UInt32 GetChannelId(string channelName)
        {
            UInt32 channelId     = 0;
            var    content       = GoodgameGet(String.Format(@"http://goodgame.ru/api/getupcomingbroadcast?id={0}&fmt=json", channelName.Replace("#", "")));
            var    textChannelId = Re.GetSubString(content, @"stream_id.*?(\d+)");

            if (!String.IsNullOrWhiteSpace(textChannelId))
            {
                UInt32.TryParse(textChannelId, out channelId);
            }
            return(channelId);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Restart server if freeze/slowness detected
        /// </summary>
        private void RestartServer(ServerTimer timer)
        {
            if (IsStopping)
            {
                return;
            }

            IsStopping = true;
            if (timer == null || timer.Server == null)
            {
                return;
            }

            Log.WriteInfo("Stopping frozen server {0}...", timer.Server.Name);

            var id = timer.With(x => x.Server).With(x => x.Process).Return(x => x.Id, 0);

            if (id == 0)
            {
                Log.WriteInfo("Unable to restart server {0}. Unknown process id.", timer.Server.Name);
                return;
            }

            Util.Try(() =>
            {
                var process = Process.GetProcessById(id);

                if (process == null)
                {
                    Log.WriteInfo("Unable to restart server {0}. Process not found.", timer.Server.Name);
                    return;
                }

                if (String.IsNullOrWhiteSpace(Server.Process.CommandLine))
                {
                    Log.WriteInfo("Unable to restart a server {0}. Empty command line!", timer.Server.Name);
                    return;
                }

                process.Kill();
            }, false);

            Util.Try(() =>
            {
                Thread.Sleep(1000);
                Log.WriteInfo("Starting server {0}...", timer.Server.Name);
                var exeFile   = Re.GetSubString(Server.Process.CommandLine, @"^(.*exe).*$");
                var arguments = Re.GetSubString(Server.Process.CommandLine, @"^.*?\s(.*)$");
                var directory = Server.Process.Path;
                StartProcess(exeFile, arguments, directory);
            });
        }
Exemplo n.º 9
0
        public void GetDescription()
        {
            String content  = String.Empty;
            String userInfo = String.Empty;

            content = HttpGet(String.Format(urlInfo, userid));


            userInfo = Re.GetSubString(content, reUserInfo, 1);
            if (String.IsNullOrEmpty(userInfo))
            {
                return;
            }

            try
            {
                JToken objInfo = JToken.Parse(userInfo);
                if (objInfo == null)
                {
                    return;
                }

                objInfo          = objInfo["userinfo"];
                PostId           = objInfo["postid"].ToString();
                ShortDescription = objInfo["page_content"].ToString();
                LongDescription  = objInfo["pc_desc"].ToString();
                Game             = objInfo["game"].ToString();

                ChannelFormParams = new List <KeyValuePair <string, string> >();

                ChannelFormParams.Add(new KeyValuePair <string, string>("data[name]", objInfo["name"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[avatar]", objInfo["avatar"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[country]", objInfo["country"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[sex]", objInfo["sex"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[stream_provider]", objInfo["stream_provider"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[stream_id]", objInfo["stream_id"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[chat_twitch]", objInfo["chat_twitch"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[chat_goodgame]", objInfo["chat_goodgame"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[chat_sc2]", objInfo["chat_sc2"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[chat_empire]", objInfo["chat_empire"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("referrer", @"http://www.goha.tv/#!/my/profile"));
                ChannelFormParams.Add(new KeyValuePair <string, string>("format", @"format:[hide][forumhide]stream:|{stream_provider}|{stream_id}|{game}|{pc_desc}|[/forumhide][B]Игра:[/B][br]{game}[br][br][B]Компьютер:[/B][br]{pc_desc}[br][br][B]Описание:[/B][/hide][br]{page_content}"));
                ChannelFormParams.Add(new KeyValuePair <string, string>("title", objInfo["name"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("data[username]", objInfo["username"].ToString()));
                ChannelFormParams.Add(new KeyValuePair <string, string>("save", "1"));
            }
            catch (Exception e)
            {
                Debug.Print("Goha GetDescription error: {0}", e.Message);
            }
        }
Exemplo n.º 10
0
        public void GetStreamId()
        {
            checkTimer = new Timer((obj) =>
            {
                var youtubeChannel = obj as YoutubeChannel;

                if (String.IsNullOrWhiteSpace(ChannelName))
                {
                    return;
                }

                var channelUrl = webClient.GetRedirectUrl(String.Format(@"https://www.youtube.com/user/{0}/live", ChannelName.Replace("#", "")));
                if (channelUrl == null || !channelUrl.Contains("v="))
                {
                    channelUrl = webClient.GetRedirectUrl(String.Format(@"https://www.youtube.com/channel/{0}/live", ChannelName.Replace("#", "")));
                }

                youtubeChannel.checkTimer.Change(15000, 15000);

                if (String.IsNullOrWhiteSpace(channelUrl))
                {
                    return;
                }

                humanReadableChannelName = this.With(x => webClient.Download(channelUrl))
                                           .With(x => Re.GetSubString(x, @"name=""title""\s*content=""(.*?)"""));

                youtubeChannel.checkTimer.Change(60000, 60000);

                var id = Re.GetSubString(channelUrl, @"v=([^&]+)");
                if (!String.IsNullOrWhiteSpace(id) && videoId != id)
                {
                    youtubeChannel.videoId = id;
                    youtubeChannel.checkTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    if (chatPoller != null)
                    {
                        chatPoller.Stop();
                    }
                    if (statsPoller != null)
                    {
                        statsPoller.Stop();
                    }

                    youtubeChannel.SetupPollers();
                }
            }, this, 0, 15000);
        }
Exemplo n.º 11
0
        private Uri GetServerUri()
        {
            var re        = @"this\.server=.*?""(.*?)""";
            var serverUrl = this.With(x => GoodgameGet("http://goodgame.ru/js/minified/chat.js"))
                            .With(x => Re.GetSubString(x, re));

            Uri uri;

            if (Uri.TryCreate(serverUrl, UriKind.Absolute, out uri))
            {
                return(uri);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 12
0
        public bool Login()
        {
            lock (loginLock)
            {
                _opcode = 0;
                List <KeyValuePair <string, string> > cookies = new List <KeyValuePair <string, string> >();

                isLoggedIn = false;
                if (String.IsNullOrEmpty(_login) || String.IsNullOrEmpty(_password))
                {
                    return(false);
                }

                var result = loginWC.DownloadString(loginUrl);
                if (String.IsNullOrEmpty(result))
                {
                    return(false);
                }

                var auth_token = Re.GetSubString(result, reAuthToken, 1);
                if (String.IsNullOrEmpty(result))
                {
                    return(false);
                }

                loginWC.ContentType = ContentType.UrlEncoded;

                result = loginWC.UploadString(loginUrl, String.Format(loginParams, HttpUtility.UrlEncode(_login), HttpUtility.UrlEncode(_password), HttpUtility.UrlEncode(auth_token)));

                var assetsHost = Re.GetSubString(result, reAssetsHost, 1);
                if (String.IsNullOrEmpty(assetsHost))
                {
                    return(false);
                }

                _user = Re.GetSubString(result, reUserName, 1);
                if (String.IsNullOrEmpty(_user))
                {
                    return(false);
                }
                isLoggedIn = true;

                return(true);
            }
        }
Exemplo n.º 13
0
        private string GoodgameGet(string url)
        {
            var content = webClient.Download(url);

            if (content != null && content.Length < 1000 && content.Contains("location.href="))
            {
                var cookieName  = Re.GetSubString(content, @"\.cookie=\""(.*?)=");
                var cookieValue = Re.GetSubString(content, @"\.cookie=\"".*?=(.*?)""");
                var newHref     = Re.GetSubString(content, @"location\.href=""(.*?)""");
                if (!String.IsNullOrWhiteSpace(cookieName) && !String.IsNullOrWhiteSpace(cookieValue) && !String.IsNullOrWhiteSpace(newHref))
                {
                    webClient.Encoding = System.Text.Encoding.UTF8;
                    webClient.SetCookie(cookieName, cookieValue, "goodgame.ru");
                    content = webClient.Download(newHref);
                }
            }
            return(content);
        }
Exemplo n.º 14
0
        private void ReadRawMessage(string rawMessage)
        {
            Log.WriteInfo("Connectcast raw message received {0}", rawMessage);

            var command = Re.GetSubString(rawMessage, @"([^\[]*)");
            var data    = this.With(x => Re.GetSubString(rawMessage, @".*?(\[.*)$"))
                          .With(x => JsonUtil.ParseArray(x));

            if (String.IsNullOrWhiteSpace(command))
            {
                return;
            }

            if (packetHandlers.ContainsKey(command))
            {
                packetHandlers[command](this, data);
            }
        }
Exemplo n.º 15
0
    public bool LoginWithUsername()
    {
        var indexPage = LoginWebClient.Download("http://sc2tv.ru");

        if (String.IsNullOrWhiteSpace(indexPage))
        {
            return(false);
        }

        var username = Config.GetParameterValue("Username") as string;
        var password = Config.GetParameterValue("Password") as string;

        Config.SetParameterValue("Cookies", null);

        if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password))
        {
            IsAnonymous = true;
            return(true);
        }

        var formBuildId = Re.GetSubString(indexPage, @"form_build_id.*?value=""(.*?)""");
        var formId      = Re.GetSubString(indexPage, @"form_id.*?value=""(.*?)""");

        if (String.IsNullOrWhiteSpace(formBuildId) || String.IsNullOrWhiteSpace(formId) ||
            String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password))
        {
            return(false);
        }

        LoginWebClient.ContentType = ContentType.UrlEncodedUTF8;
        LoginWebClient.Upload("http://sc2tv.ru/node",
                              String.Format("name={0}&pass={1}&form_build_id={2}&form_id={3}",
                                            Url.Encode(username), Url.Encode(password), formBuildId, formId));

        if (String.IsNullOrEmpty(LoginWebClient.CookieValue("drupal_uid", "http://sc2tv.ru")))
        {
            return(false);
        }

        Config.SetParameterValue("Cookies", JsonUtil.ToJson(LoginWebClient.CookiesTable));
        Config.SetParameterValue("AuthTokenCredentials", username + password);

        return(LoginWithCookies());
    }
Exemplo n.º 16
0
        public bool SetTopic()
        {
            if (string.IsNullOrWhiteSpace(ownChannelId) || !Status.IsLoggedIn)
            {
                return(false);
            }

            var searchGame = Games.FirstOrDefault(game => game.Name.Equals(Info.CurrentGame.Name, StringComparison.InvariantCultureIgnoreCase));

            if (searchGame == null)
            {
                QueryGameList(Info.CurrentGame.Name, null);
                searchGame = Games.FirstOrDefault(game => game.Name.Equals(Info.CurrentGame.Name, StringComparison.InvariantCultureIgnoreCase));
            }

            if (searchGame != null)
            {
                Info.CurrentGame.Id = searchGame.Id;
            }

            var parameters = String.Format("objType=7&objId={0}&title={1}&gameId={2}", ownChannelId, HttpUtility.UrlEncode(Info.Topic), Info.CurrentGame.Id);

            webClient.ContentType = ContentType.UrlEncoded;
            webClient.Headers["X-Requested-With"] = "XMLHttpRequest";
            webClient.Upload("http://goodgame.ru/ajax/channel/update_title/", parameters);

            //Check if succeed
            var content = GoodgameGet(String.Format(@"http://goodgame.ru/channel/{0}", ownChannel));

            if (!String.IsNullOrWhiteSpace(content))
            {
                if (Info.Topic.Equals(Re.GetSubString(content, @"<title>([^<]*)</title>")) &&
                    Info.CurrentGame.Name.Equals(this.With(x => Re.GetSubString(content, @"StreamTitleEdit[^,]*,[^,]*,[^,]*,[^,]*,[^']*'([^']*)'"))
                                                 .With(x => x.Trim())))
                {
                    return(true);
                }
            }


            return(false);
        }
Exemplo n.º 17
0
        public void GetDescription()
        {
            var result = HttpGet(String.Format(channelUrl, _user.ToLower()));

            if (!String.IsNullOrEmpty(result))
            {
                ShortDescription = Re.GetSubString(result, reTitle, 1);
                Game             = Re.GetSubString(result, reGame, 2);
                if (!String.IsNullOrEmpty(Game))
                {
                    Game = Game.Trim();
                }

                GameId = Re.GetSubString(result, reGame, 1);
                if (!String.IsNullOrEmpty(GameId))
                {
                    GameId = GameId.Trim();
                }
            }
        }
Exemplo n.º 18
0
        public bool LoginWithUsername()
        {
            var userName = Config.GetParameterValue("Username") as string;

            NickName = userName;
            var password = Config.GetParameterValue("Password") as string;

            if (String.IsNullOrWhiteSpace(userName) || String.IsNullOrWhiteSpace(password))
            {
                IsAnonymous = true;
                return(true);
            }


            var authString = String.Format(@"action=login&username={0}&pass={1}&remember_me=1", userName, password);

            loginWebClient.ContentType = ContentType.UrlEncoded;

            var authToken = this.With(x => loginWebClient.Upload("http://cybergame.tv/login.php", authString))
                            .With(x => Re.GetSubString(x, @"khash[^""]+""([^""]+)"""));

            if (authToken == null)
            {
                Log.WriteError("Login to cybergame.tv failed. Joining anonymously");
                IsAnonymous = true;
                return(false);
            }
            else
            {
                IsAnonymous = false;
                Config.SetParameterValue("AuthToken", authToken);
                Config.SetParameterValue("AuthTokenCredentials", userName + password);

                return(true);
            }
        }
Exemplo n.º 19
0
        public void ReadChatIds()
        {
            String content;

            if (String.IsNullOrEmpty(ChannelUrl))
            {
                Debug.Print("GamersTv: empty channel url");
                return;
            }


            lock (lockLoginWC)
            {
                try
                {
                    content = loginWC.DownloadString(ChannelUrl);
                    long.TryParse(Re.GetSubString(content, reChatParams, 1), out RoomId);
                    long.TryParse(Re.GetSubString(content, reChatParams, 2), out UserId);
                }
                catch (Exception e) {
                    Debug.Print(String.Format("GamersTV: read chat ids exception {0} {1}", ChannelUrl, e.Message));
                }
            }
        }
Exemplo n.º 20
0
    public override void DownloadEmoticons(string url)
    {
        var rePattern = @"smiles[\s|=]*(\[.*?\]);";

        if (IsFallbackEmoticons && IsWebEmoticons)
        {
            return;
        }

        lock (iconParseLock)
        {
            var list = new List <Emoticon>();
            if (Emoticons == null)
            {
                Emoticons = new List <Emoticon>();
            }

            var jsonEmoticons = this.With(x => LoginWebClient.Download(url))
                                .With(x => Re.GetSubString(x, rePattern));

            if (jsonEmoticons == null)
            {
                Log.WriteError("Unable to get {0} emoticons!", ChatName);
                return;
            }
            else
            {
                var icons = JsonUtil.ParseArray(jsonEmoticons);
                if (icons == null)
                {
                    return;
                }

                foreach (var icon in icons)
                {
                    var code = (string)icon["code"];
                    var img  = (string)icon["img"];

                    if (String.IsNullOrWhiteSpace(code) || String.IsNullOrWhiteSpace(img))
                    {
                        continue;
                    }

                    var width  = (int?)icon["width"] ?? 30;
                    var height = (int?)icon["height"] ?? 30;

                    var smileUrl = "http://chat.sc2tv.ru/img/" + img;
                    list.Add(new Emoticon(":s" + code, smileUrl, (int)width, (int)height));
                }
                if (list.Count > 0)
                {
                    Emoticons = list.ToList();
                    if (IsFallbackEmoticons)
                    {
                        IsWebEmoticons = true;
                    }

                    IsFallbackEmoticons = true;
                }
            }
        }
    }
Exemplo n.º 21
0
        public bool Login()
        {
            Debug.Print("Goodgame logging in");
            lock (loginLock)
            {
                try
                {
                    isLoggedIn = false;

                    if (String.IsNullOrEmpty(_user) || String.IsNullOrEmpty(_password))
                    {
                        Debug.Print("Goodgame: Username or password is empty");
                        return(false);
                    }

                    String result = loginWC.DownloadString(@"http://" + domain);

                    string loginParams = "login="******"&password="******"&remember=1";
                    loginWC.setCookie("fixed", "1", domain);
                    loginWC.setCookie("auto_login_name", _user, domain);

                    loginWC.ContentType = ContentType.UrlEncoded;
                    loginWC.Headers["X-Requested-With"] = "XMLHttpRequest";

                    result = loginWC.UploadString(loginUrl, loginParams);

                    int.TryParse(loginWC.CookieValue("uid", "http://" + domain), out _userId);

                    result = loginWC.DownloadString(String.Format(userUrl, _userId));

                    URLUser = Re.GetSubString(result, reChannelUrl, 1);

                    result = loginWC.DownloadString(String.Format(chatUrl, URLUser));

                    if (String.IsNullOrEmpty(result))
                    {
                        Debug.Print("Goodgame: Could not fetch " + String.Format(chatUrl, URLUser));
                        return(false);
                    }

                    int.TryParse(Re.GetSubString(result, @"channelId: (\d+?),", 1), out _chatId);
                    _channel   = _chatId.ToString();
                    _userToken = Re.GetSubString(result, @"token: '(.*?)',", 1);

                    var editContent = loginWC.DownloadString(String.Format(editUlr, URLUser));
                    var serviceUrls = new String[] { "twitch.tv", "cybergame.tv", "hashd.tv", "youtube.com" };
                    //<input type="text" name="video_urls[22473]" value="http://twitch.tv/xedoc"

                    ServiceNames = String.Empty;
                    foreach (var service in serviceUrls)
                    {
                        var substr = Re.GetSubString(editContent, @"<input.*?video_urls\[.*?value=.*?(" + service + @")[^\""]*", 1);
                        if (!String.IsNullOrEmpty(substr))
                        {
                            ServiceNames = ServiceNames + substr;
                        }
                    }



                    isLoggedIn = true;
                }
                catch (Exception e) {
                    Debug.Print("Goodgame: login exception " + e.Data + " " + e.StackTrace.ToString());
                }

                return(true);
            }
        }
Exemplo n.º 22
0
        public void Login(string login, string password)
        {
            lock (loginLock)
            {
                LoggedIn = false;

                if (loginWC.gotCookies(cookieForTest, mainDomain))
                {
                    LoggedIn = true;
                    return;
                }
                String content = String.Empty;
                try
                {
                    content = loginWC.DownloadString(loginUrl);
                }
                catch (Exception e)
                {
                    Debug.Print("Sc2tv login error: {0}", e.Message);
                }

                if (String.IsNullOrEmpty(content))
                {
                    return;
                }

                string formBuildId = Re.GetSubString(content, reHiddenFormId, 1);

                if (String.IsNullOrEmpty(formBuildId))
                {
                    Debug.Print("Can't find Form Build ID. Check RE");
                    return;
                }
                else if (formBuildId != null)
                {
                    try
                    {
                        string loginParams = "name=" + HttpUtility.UrlEncode(login) + "&pass="******"&form_build_id=" + formBuildId + "&form_id=user_login_block";

                        loginWC.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=UTF-8";
                        loginWC.UploadString(loginUrl, loginParams);

                        if (loginWC.gotCookies(cookieForTest, mainDomain))
                        {
                            loginWC.setCookie("chat-img", "1", "chat.sc2tv.ru");
                            loginWC.setCookie("chat_channel_id", ChannelId.ToString(), "chat.sc2tv.ru");
                            loginWC.setCookie("chat-on", "1", "chat.sc2tv.ru");
                            loginWC.DownloadString(chatTokenUrl);

                            loginWC.setCookie("chat_token", loginWC.CookieValue("chat_token", chatDomain + "/gate.php"), "chat.sc2tv.ru");
                            LoggedIn           = true;
                            settingsWC.Cookies = loginWC.Cookies;
                            OnLogon(new Sc2Event());
                        }
                    }
                    catch
                    {
                        Debug.Print("Exception in Sc2 Login()");
                    }
                }
            }
        }
Exemplo n.º 23
0
        public string XMLHttpRequest(string url, string data)
        {
            lock (lockRequest)
            {
                var         uri       = new Uri(url);
                IPHostEntry hostEntry = Dns.GetHostEntry(uri.Host);

                Socket socket = null;
                for (int i = 0; i < hostEntry.AddressList.Count(); i++)
                {
                    IPAddress address = hostEntry.AddressList[i];

                    IPEndPoint ipEndpoint = new IPEndPoint(address, uri.Port);

                    socket = new Socket(ipEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    try
                    {
                        socket.Connect(ipEndpoint);
                        if (socket.Connected)
                        {
                            Debug.Print(String.Format("WebClient XMLHttpRequest: Connected to {0}", ipEndpoint.ToString()));
                            break;
                        }
                        else
                        {
                            Debug.Print(String.Format("WebClient XMLHttpRequest: can't connect to {0}", ipEndpoint.ToString()));
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.Print("WebClient XMLHttpRequest: socket exception {0}", ex.Message);
                    }
                }
                var    cookielist = CookiesStrings.Select(a => String.Format("{0}={1}", a.Key, a.Value));
                String cookies    = string.Join("; ", cookielist);

                String requestString = String.Format("POST {0} HTTP/1.1\r\n" +
                                                     "User-Agent: {4}\r\n" +
                                                     "Accept: text/html\r\n" +
                                                     "Host: {1}\r\n" +
                                                     "Origin: http://hashd.tv\r\n" +
                                                     "Accept-Encoding: deflate\r\n" +
                                                     "Referer: http://hashd.tv/xedoc\r\n" +
                                                     "Cache-Control: no-store, no-cache\r\n" +
                                                     "Pragma: no-cache\r\n" +
                                                     "Content-Length: {2}\r\n" +
                                                     "Connection: Keep-Alive\r\n" +
                                                     (Cookies.Count > 0 ? "Cookie: " + cookies + "\r\n": "") +
                                                     "Content-Type: application/xml\r\n\r\n"
                                                     + "{3}", uri.AbsolutePath, uri.Host, Encoding.UTF8.GetBytes(data).Length, data, userAgent);
                Debug.Print(requestString);
                byte[] request = Encoding.ASCII.GetBytes(requestString);

                Byte[] bytesReceived = new Byte[1024];
                try
                {
                    socket.Send(request, request.Length, 0);
                }
                catch (Exception ex)
                {
                    Debug.Print("WebClient XMLHttpRequest: socket exception {0}", ex.Message);
                }

                string result = String.Empty;
                int    bytes  = 0;
                try
                {
                    do
                    {
                        bytes  = socket.Receive(bytesReceived, bytesReceived.Length, 0);
                        result = result + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                    }while (bytes > 0);
                }
                catch (Exception ex)
                {
                    Debug.Print("WebClient XMLHttpRequest: socket exception {0}", ex.Message);
                }
                Debug.Print(result);
                bool found     = true;
                var  tmpResult = result;
                while (found)
                {
                    var pair = Re.GetSubString(tmpResult, @"Set-Cookie:\s([^;]+)?;", 1);
                    if (String.IsNullOrEmpty(pair))
                    {
                        found = false;
                        break;
                    }
                    var re    = @"(.*)?=(.*)";
                    var name  = Re.GetSubString(pair, re, 1);
                    var value = Re.GetSubString(pair, re, 2);
                    setCookie(name, value, uri.DnsSafeHost);
                    tmpResult = tmpResult.Replace(String.Format(@"Set-Cookie: {0}", name), "");
                }

                return(result);
            }
        }
Exemplo n.º 24
0
        public string postFormDataLowLevel(string formActionUrl, string postData)
        {
            var         uri        = new Uri(formActionUrl);
            IPHostEntry hostEntry  = Dns.GetHostEntry(uri.Host);
            IPAddress   address    = hostEntry.AddressList[0];
            IPEndPoint  ipEndpoint = new IPEndPoint(address, 80);
            Socket      socket     = new Socket(ipEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect(ipEndpoint);
                if (socket.Connected)
                {
                    Debug.Print(String.Format("WebClient postFormDataLowLevel: Connected to {0}", ipEndpoint.ToString()));
                }
                else
                {
                    Debug.Print(String.Format("WebClient postFormDataLowLevel: can't connect to {0}", ipEndpoint.ToString()));
                }
            }
            catch (SocketException ex)
            {
                Debug.Print("WebClient postFormDataLowLevel: socket exception {0}", ex.Message);
            }
            var buffer = Encoding.UTF8.GetBytes(postData);

            String requestString = String.Format("POST {0} HTTP/1.1\r\n" +
                                                 "User-Agent: {4}\r\n" +
                                                 "Accept: text/html,application/xhtml+xml,application/xml\r\n" +
                                                 "Accept-Encoding: deflate\r\n" +
                                                 "Host: {1}\r\n" +
                                                 "Origin: http://{1}\r\n" +
                                                 "Referer: http://{1}\r\n" +
                                                 "Cache-Control: no-store, no-cache\r\n" +
                                                 "Pragma: no-cache\r\n" +
                                                 "Content-Length: {2}\r\n" +
                                                 "Connection: Keep-Alive\r\n" +
                                                 "Accept-Language: en-US\r\n" +
                                                 "Cookie: {5}\r\n" +
                                                 "Content-Type: application/x-www-form-urlencoded\r\n\r\n"
                                                 + "{3}", uri.AbsolutePath, uri.Host, Encoding.UTF8.GetBytes(postData).Length, postData, userAgent, CookieParamString);

            byte[] request = Encoding.UTF8.GetBytes(requestString);

            Byte[] bytesReceived = new Byte[1024];
            socket.Send(request, request.Length, 0);
            string result = String.Empty;
            int    bytes  = 0;

            try
            {
                do
                {
                    bytes  = socket.Receive(bytesReceived, bytesReceived.Length, 0);
                    result = result + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                }while (bytes > 0);
            }
            catch {
            }
            bool found     = true;
            var  tmpResult = result;

            while (found)
            {
                var pair = Re.GetSubString(tmpResult, @"Set-Cookie:\s([^;]+)?;", 1);
                if (String.IsNullOrEmpty(pair))
                {
                    found = false;
                    break;
                }
                var re    = @"(.*)?=(.*)";
                var name  = Re.GetSubString(pair, re, 1);
                var value = Re.GetSubString(pair, re, 2);
                setCookie(name, value, uri.DnsSafeHost);
                tmpResult = tmpResult.Replace(String.Format(@"Set-Cookie: {0}", name), "");
            }

            return(result);
        }
Exemplo n.º 25
0
        private async void CheckUpdates()
        {
            using (WebClientBase webClient = new WebClientBase())
            {
                int currentVersion = 0;
                Log.WriteInfo("OBSPlugin: Downloading current version info");

                var content = webClient.Download("http://www.xedocproject.com/apps/ubiquitous2obs/ub2plugin.ver");


                if (content != null)
                {
                    content = Re.GetSubString(content, @"(\d+)");

                    int.TryParse(content, out currentVersion);

                    Log.WriteInfo("OBSPlugin: current version number is {0}", currentVersion);
                    bool   isError      = false;
                    string saveFileName = Path.GetTempPath() + @"Ubiquitous2PluginInstaller.exe";
                    if (currentVersion > VERSION)
                    {
                        try
                        {
                            if (File.Exists(saveFileName))
                            {
                                File.Delete(saveFileName);
                            }
                        }
                        catch (Exception e)
                        {
                            isError = true;
                            Log.WriteError("OBSPlugin: error deleting old installer {0}", e.Message);
                        }

                        await Task.Run(() =>
                        {
                            try
                            {
                                webClient.DownloadFile(@"http://www.xedocproject.com/apps/ubiquitous2obs/Ubiquitous2PluginInstaller.exe",
                                                       Path.GetTempPath() + @"Ubiquitous2PluginInstaller.exe");
                            }
                            catch (Exception e) {
                                isError = true;
                                Log.WriteError("OBSPlugin: Error downloading update {0}", e.Message);
                            }
                        });

                        if (!isError)
                        {
                            var result = MessageBox.Show("New version of Ubiquitous2 plugin is available. Install it now ?", "New Ubiquitous2 plugin", MessageBoxButtons.YesNo);
                            if (result == DialogResult.No)
                            {
                                return;
                            }
                            var installDir = AssemblyDirectory.Replace(@"plugins\CLRHostPlugin", "");

                            ProcessStartInfo startInfo = new ProcessStartInfo(saveFileName, string.Format("\"{0}\"", installDir));
                            Process.Start(startInfo);
                        }
                    }
                }
                else
                {
                    Log.WriteError("OBSPlugin: couldn't get current plugin version");
                }
            }
        }
Exemplo n.º 26
0
        public bool LoginWithUsername()
        {
            var userName = Config.GetParameterValue("Username") as string;
            var password = Config.GetParameterValue("Password") as string;

            if (String.IsNullOrWhiteSpace(userName) || String.IsNullOrWhiteSpace(password) || userName.Equals(AnonymousNickName, StringComparison.InvariantCultureIgnoreCase))
            {
                IsAnonymous = true;
                return(true);
            }

            if (Regex.IsMatch(userName, @"justinfan\d+"))
            {
                AnonymousNickName = userName;
            }

            NickName = userName;

            webClient.SetCookie("api_token", null, "twitch.tv");
            webClient.SetCookie("csrf_token", null, "twitch.tv");

            var csrfToken = this.With(x => webClient.Download("http://www.twitch.tv/login"))
                            .With(x => Re.GetSubString(x, @"^.*authenticity_token.*?value=""(.*?)"""));


            if (csrfToken == null)
            {
                Log.WriteError("Twitch: Can't get CSRF token. Twitch web layout changed ?");
                return(false);
            }
            string csrf_cookie = csrfToken;

            if (csrf_cookie.Substring(csrf_cookie.Length - 1).Equals("="))
            {
                csrf_cookie = csrf_cookie.Substring(0, csrf_cookie.Length - 1) + "%3D";
            }

            webClient.SetCookie("csrf_token", csrf_cookie, "twitch.tv");
            webClient.ContentType = ContentType.UrlEncoded;
            webClient.Headers["X-Requested-With"] = "XMLHttpRequest";
            webClient.Headers["X-CSRF-Token"]     = csrfToken;
            webClient.Headers["Accept"]           = "text/html, application/xhtml+xml, */*";

            var apiToken = this.With(x => webClient.Upload("https://secure.twitch.tv/user/login", String.Format(
                                                               "utf8=%E2%9C%93&authenticity_token={0}%3D&redirect_on_login=&embed_form=false&user%5Blogin%5D={1}&user%5Bpassword%5D={2}",
                                                               csrfToken,
                                                               userName,
                                                               password)))
                           .With(x => webClient.CookieValue("api_token", "http://twitch.tv"));

            if (String.IsNullOrWhiteSpace(apiToken))
            {
                Log.WriteError("Twitch: Can't get API token");
                return(false);
            }
            webClient.Headers["Twitch-Api-Token"] = apiToken;
            webClient.Headers["X-CSRF-Token"]     = csrfToken;
            webClient.Headers["Accept"]           = "*/*";

            if (apiToken == null)
            {
                Log.WriteError("Login to twitch.tv failed. Joining anonymously");
                IsAnonymous = true;
                return(false);
            }
            else
            {
                var oauthToken = this.With(x => webClient.Download("http://api.twitch.tv/api/me?on_site=1"))
                                 .With(x => JToken.Parse(x))
                                 .With(x => x.Value <string>("chat_oauth_token"));

                if (String.IsNullOrWhiteSpace(oauthToken))
                {
                    Log.WriteError("Login to twitch.tv failed. Joining anonymously");
                    IsAnonymous = true;
                    return(false);
                }

                IsAnonymous = false;
                Config.SetParameterValue("OAuthToken", oauthToken);
                Config.SetParameterValue("ApiToken", apiToken);
                Config.SetParameterValue("AuthTokenCredentials", userName + password);

                return(LoginWithToken());
            }
        }
Exemplo n.º 27
0
        public bool Login()
        {
            if (stopped)
            {
                return(false);
            }

            lock (chatLock)
            {
                try
                {
                    if (String.IsNullOrEmpty(_user) || String.IsNullOrEmpty(_password))
                    {
                        return(false);
                    }

                    chatWC = new CookieAwareWebClient();

                    chatWC.Headers["Cache-Control"] = "no-cache";
                    chatWC.DownloadString(loginUrl);
                    chatWC.setCookie("kt_is_visited", "1", ".cybergame.tv");
                    chatWC.setCookie("kt_tcookie", "1", ".cybergame.tv");

                    string loginParams = String.Format("action=login&username={0}&pass={1}&remember_me=1", _user, _password);

                    var res = chatWC.postFormDataLowLevel(loginUrl, loginParams);

                    if (string.IsNullOrEmpty(res))
                    {
                        Debug.Print("Cybergame: couldn't get login URL");
                        return(false);
                    }

                    res = chatWC.DownloadString(loginUrl);
                    if (!res.Contains("logout.php"))
                    {
                        Debug.Print("Cybergame: wrong credentials");
                        return(false);
                    }


                    var result = chatWC.DownloadString(String.Format(chatUrl, String.Empty));

                    kname = Re.GetSubString(result, reKName, 1);
                    khash = Re.GetSubString(result, reKHash, 1);

                    if (String.IsNullOrEmpty(khash))
                    {
                        Debug.Print("Cybergame: couldn't get khash");
                        return(false);
                    }

                    chatWC.setCookie("khame", kname, ".cybergame.tv");
                    chatWC.setCookie("khash", khash, ".cybergame.tv");


                    statsWC.Cookies = chatWC.Cookies;
                    loginWC.Cookies = chatWC.Cookies;

                    Debug.Print("Cybergame: connecting web socket");
                    Domain  = domain;
                    Port    = "9090";
                    Path    = String.Format("/{0}/{1}/websocket", random_number(), random_string());
                    Cookies = statsWC.CookiesStrings;
                    Connect();

                    return(true);
                }
                catch (Exception e)
                {
                    Debug.Print(String.Format("Cybergame: login exception {0} {1} {2}", chatWC.URL, e.Message, e.StackTrace));
                    return(false);
                }
            }
        }
Exemplo n.º 28
0
        private void ReadRawMessage(string rawMessage)
        {
            if (String.IsNullOrWhiteSpace(rawMessage))
            {
                return;
            }

            lock ( lockRawMessage )
            {
                const string jsonArgsRe = @".*args"":\[""(.*?)""\]}$";

                if (rawMessage.Equals("1::"))
                {
                    Chat.Status.IsConnected = true;
                }
                else if (rawMessage.Equals("2::"))
                {
                    Thread.Sleep(random.Next(100, 1000));
                    webSocket.Send("2::");
                    return;
                }

                if (rawMessage.Contains(@":""message"))
                {
                    var json = Re.GetSubString(rawMessage, jsonArgsRe);
                    if (json == null)
                    {
                        return;
                    }

                    dynamic msg = this.With(x => JToken.Parse(json.Replace(@"\""", @"""").Replace(@"\\", @"\")))
                                  .With(x => x.Value <dynamic>("params"));

                    if (msg == null)
                    {
                        return;
                    }

                    if (rawMessage.Contains(@":\""loginMsg"))
                    {
                        timerEveryMinute.Change(500, 60000);

                        var role = (string)msg.role;
                        switch (role.ToLower())
                        {
                        case "guest":
                            if (!Chat.IsAnonymous)
                            {
                                Chat.Status.IsLoggedIn = false;
                                if (!Chat.Status.IsLoginFailed)
                                {
                                    Chat.Status.IsConnected   = false;
                                    Chat.Status.IsLoggedIn    = false;
                                    Chat.Status.IsLoginFailed = true;
                                    Chat.Status.IsStarting    = false;
                                    Chat.Config.SetParameterValue("AuthToken", String.Empty);
                                    Chat.Restart();
                                }
                            }
                            else
                            {
                                Chat.Status.IsLoginFailed = false;
                            }

                            break;

                        case "admin":
                        {
                            Chat.Status.IsLoggedIn    = true;
                            Chat.Status.IsLoginFailed = false;
                        }
                        break;

                        case "anon":
                        {
                            Chat.Status.IsLoggedIn    = true;
                            Chat.Status.IsLoginFailed = false;
                        }
                        break;

                        default:
                            break;
                        }
                        var authToken = Chat.Config.GetParameterValue("AuthToken") as string;
                        SendCredentials(Chat.NickName, ChannelName, authToken);
                    }
                    else if (rawMessage.Contains(@":\""chatMsg"))
                    {
                        var nickName = (string)msg.name;
                        var text     = (string)msg.text;

                        if (String.IsNullOrWhiteSpace(nickName) || String.IsNullOrWhiteSpace(text))
                        {
                            return;
                        }

                        if (ReadMessage != null)
                        {
                            ReadMessage(new ChatMessage()
                            {
                                Channel         = ChannelName,
                                ChatIconURL     = Chat.IconURL,
                                ChatName        = Chat.ChatName,
                                FromUserName    = nickName,
                                HighlyImportant = false,
                                IsSentByMe      = false,
                                Text            = text
                            });
                        }
                    }
                    else if (rawMessage.Contains(@":\""userList"))
                    {
                        var data         = msg.data;
                        var guestsNumber = this.With(x => data.Guests as JArray).With(x => x.ToObject <string[]>());
                        var admins       = this.With(x => data.admin as JArray).With(x => x.ToObject <string[]>());
                        var moderators   = this.With(x => data.user as JArray).With(x => x.ToObject <string[]>());
                        var users        = this.With(x => data.anon as JArray).With(x => x.ToObject <string[]>());
                        var followers    = this.With(x => data.isFollower as JArray).With(x => x.ToObject <string[]>());
                        var subscribers  = this.With(x => data.isSubscriber as JArray).With(x => x.ToObject <string[]>());
                        var staff        = this.With(x => data.isStaff as JArray).With(x => x.ToObject <string[]>());

                        currentUserList.Clear();
                        foreach (var pair in new Dictionary <string, string[]> {
                            { "Staff", staff },
                            { "Admins", admins },
                            { "Moderators", moderators },
                            { "Subscribers", subscribers },
                            { "Followers", followers },
                            { "Users", users }
                        })
                        {
                            if (pair.Value == null)
                            {
                                continue;
                            }

                            foreach (string userNickname in pair.Value)
                            {
                                currentUserList.Add(new ChatUser()
                                {
                                    Channel   = ChannelName,
                                    ChatName  = Chat.ChatName,
                                    GroupName = pair.Key,
                                    NickName  = userNickname,
                                    Badges    = null,
                                });
                            }
                        }
                        var oldUserList = (Chat as IChatUserList).ChatUsers;

                        //Delete disconnected users
                        UI.Dispatch(() => {
                            oldUserList.ToList().Where(item => item.Channel.Equals(ChannelName) && item.ChatName.Equals(Chat.ChatName))
                            .Except(currentUserList, new LambdaComparer <ChatUser>((x, y) => x.NickName.Equals(y.NickName)))
                            .ToList()
                            .ForEach(item => oldUserList.Remove(item));
                        });
                        var newUserList = currentUserList
                                          .Where(item => item.Channel.Equals(ChannelName) && item.ChatName.Equals(Chat.ChatName))
                                          .Except(oldUserList, new LambdaComparer <ChatUser>((x, y) => x.NickName.Equals(y.NickName)))
                                          .ToList();

                        lock (chatUsersLock)
                            (Chat as IChatUserList).ChatUsers.AddRange(newUserList);
                        newUserList = null;
                    }
                }
            }
        }
Exemplo n.º 29
0
        public override void Join(Action <IChatChannel> callback, string channel)
        {
            ChannelName = "#" + channel.Replace("#", "");

            if (ChannelName.Contains("@"))
            {
                return;
            }

            string sid = String.Empty;

            using (WebClientBase webClient = new WebClientBase())
            {
                webClient.Cookies = (Chat as ConnectcastChat).LoginWebClient.Cookies;
                channelToken      = this.With(x => webClient.Download(String.Format("http://connectcast.tv/chat/{0}", ChannelName.Replace("#", ""))))
                                    .With(x => Re.GetSubString(x, "token[^']*'(.*?)'"));

                sid = this.With(x => webClient.Download(
                                    String.Format("https://chat.connectcast.tv:3000/socket.io/?EIO=3&transport=polling&t=", Time.UnixTimestamp())))
                      .With(x => Re.GetSubString(x, @"""sid"":""(.*?)"""));

                if (String.IsNullOrWhiteSpace(channelToken) ||
                    channelToken.Equals("NOTOKEN", StringComparison.InvariantCultureIgnoreCase))
                {
                    channelToken = "NOTOKEN";
                }
                else
                {
                    Chat.Status.IsLoggedIn = true;
                }
            }

            if (String.IsNullOrWhiteSpace(sid) && LeaveCallback != null)
            {
                LeaveCallback(this);
                return;
            }


            webSocket = new WebSocketBase();
            webSocket.PingInterval = 0;

            JoinCallback = callback;

            webSocket.DisconnectHandler = () =>
            {
                if (pingTimer != null)
                {
                    pingTimer.Change(Timeout.Infinite, Timeout.Infinite);
                }

                Leave();
            };

            webSocket.ReceiveMessageHandler = ReadRawMessage;

            webSocket.Path     = String.Format("/socket.io/?EIO=3&transport=websocket&sid={0}", sid);
            webSocket.Port     = "3000";
            webSocket.IsSecure = true;
            webSocket.Origin   = "http://connectcast.tv";
            webSocket.Cookies  = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("io", sid)
            };
            webSocket.Host           = "chat.connectcast.tv";
            webSocket.ConnectHandler = () =>
            {
                if (pingTimer != null)
                {
                    pingTimer.Change(PING_INTERVAL, PING_INTERVAL);
                }

                if (disconnectTimer != null)
                {
                    disconnectTimer.Change(PING_INTERVAL * 2, Timeout.Infinite);
                }

                webSocket.Send("2probe");
            };
            SetupStatsWatcher();
            webSocket.Connect();
        }
Exemplo n.º 30
0
        public bool Login()
        {
            Debug.Print("JetSet.pro logging in");
            lock (loginLock)
            {
                try
                {
                    IsLoggedIn = false;

                    if (String.IsNullOrEmpty(_user) || String.IsNullOrEmpty(_password))
                    {
                        Debug.Print("JetSet.pro: Username or password is empty");
                        return(false);
                    }
                    Debug.Print("Jetset.pro: get home page {0}", homeUrl);
                    var result = loginWC.DownloadString(homeUrl);

                    var loginParams = String.Format("login={0}&pass={1}", _user, _password);
                    loginWC.ContentType = ContentType.UrlEncodedUTF8;

                    Debug.Print("Jetset.pro: send login info to {0}", loginUrl);
                    loginWC.UploadString(loginUrl, loginParams);

                    String remember = loginWC.CookiesStrings.FirstOrDefault(item => item.Key == "remember").Value;

                    if (string.IsNullOrEmpty(remember))
                    {
                        Debug.Print("Jetset.pro: login info cookie 'remember' isn't set");
                        return(false);
                    }

                    remember = HttpUtility.UrlDecode(remember);


                    ArrayList loginObj = (ArrayList)serializer.Deserialize(remember);

                    if (loginObj == null || loginObj.GetType() != typeof(ArrayList) || loginObj.Count != 3)
                    {
                        Debug.Print("Jetset.pro: unable to parse login json object");
                        return(false);
                    }
                    userId = (string)loginObj[0];
                    hash1  = (string)loginObj[1];
                    hash2  = (string)loginObj[2];

                    Debug.Print("Jetset.pro: get home page {0}", homeUrl);
                    result = loginWC.DownloadString(streamsUrl);

                    if (String.IsNullOrEmpty(result))
                    {
                        Debug.Print("Jetset.pro: can't get streams url {0}", streamsUrl);
                        return(false);
                    }

                    _channelUrl = Re.GetSubString(result, reChannelUrl, 1);

                    if (String.IsNullOrEmpty(_channelUrl))
                    {
                        Debug.Print("Jetset.pro: can't get channel url {0}", _channelUrl);
                        return(false);
                    }

                    result = loginWC.DownloadString(String.Format(chatJsUrl, TimeUtils.UnixTimestamp()));

                    var configVer = Re.GetSubString(result, reConfigVer, 1);
                    var config    = String.Format(configTemplate, configVer, TimeUtils.UnixTimestamp());

                    loginWC.setCookie("config", HttpUtility.UrlEncode(config), "jetset.pro");

                    result = loginWC.DownloadString(baseUrl + _channelUrl);

                    roomid   = Re.GetSubString(result, reRoomId, 1);
                    token    = Re.GetSubString(result, reToken, 1);
                    rndtoken = Re.GetSubString(result, reRndToken, 1);

                    loginWC.setCookie("RND_TOKEN", rndtoken, "jetset.pro");

                    loginWC.CookiesStrings.ForEach(pair => { Debug.Print("{0}: {1}", pair.Key, pair.Value); });

                    var sessionid = loginWC.DownloadString("http://" + socketDomain + ":8080/socket.io/1/?t=" + TimeUtils.UnixTimestamp());
                    sessionid = Re.GetSubString(sessionid, reSessId, 1);

                    Domain  = socketDomain;
                    Port    = "8080";
                    Path    = "/socket.io/1/websocket/" + sessionid;
                    Cookies = loginWC.CookiesStrings;
                    Connect();
                    IsLoggedIn = true;
                }
                catch (Exception e)
                {
                    Debug.Print("JetSet: login exception {0} {1} {2} ", loginWC.URL, e.Message, e.StackTrace.ToString());
                }

                return(true);
            }
        }