Example #1
0
        internal static void Process(string json)
        {
            // Handle any json parsing errors
            if (json == string.Empty)
            {
                return;
            }

            // Parse the chat info into a json node, making sure it's not null
            JSONNode node = JSON.Parse(json);

            if (node == null || node.IsNull)
            {
                return;
            }

            // If the data has an error node, print out the entire json string for debugging purposes
            if (node.HasKey("error"))
            {
                Plugin.Log(json);
                return;
            }

            // Read in the json data to our data structs
            kind                   = node["kind"].Value;
            etag                   = node["etag"].Value;
            _nextPageToken         = node["nextPageToken"].Value;
            _pollingIntervalMillis = node["pollingIntervalMillis"].AsInt;

            // Iterate through each message, invoking any regstered callbacks along the way
            foreach (JSONObject item in node["items"].AsArray)
            {
                YouTubeMessage newMessage = new YouTubeMessage();
                newMessage.Update(item);

                YouTubeMessageHandlers.InvokeHandler(newMessage, "");
                Thread.Sleep(100);
            }
        }
Example #2
0
        private static void SendMessageLoop()
        {
            while (!Globals.IsApplicationExiting)
            {
                Thread.Sleep(500);
                if (_sendQueue.Count > 0 && _sendQueue.TryPeek(out var messageToSend))
                {
                    try
                    {
                        HttpWebRequest web = (HttpWebRequest)WebRequest.Create($"https://www.googleapis.com/youtube/v3/liveChat/messages?part=snippet");
                        web.Method = "POST";
                        web.Headers.Add("Authorization", $"{YouTubeOAuthToken.tokenType} {YouTubeOAuthToken.accessToken}");
                        web.ContentType = "application/json";

                        JSONObject container = new JSONObject();
                        container["snippet"] = new JSONObject();
                        container["snippet"]["liveChatId"]         = new JSONString(YouTubeLiveBroadcast.currentBroadcast.snippet.liveChatId);
                        container["snippet"]["type"]               = new JSONString("textMessageEvent");
                        container["snippet"]["textMessageDetails"] = new JSONObject();
                        container["snippet"]["textMessageDetails"]["messageText"] = new JSONString(messageToSend.Value);
                        string snippetString = container.ToString();
                        Plugin.Log($"Sending {snippetString}");
                        var postData = Encoding.ASCII.GetBytes(snippetString);
                        web.ContentLength = postData.Length;

                        using (var stream = web.GetRequestStream())
                            stream.Write(postData, 0, postData.Length);

                        using (HttpWebResponse resp = (HttpWebResponse)web.GetResponse())
                        {
                            if (resp.StatusCode != HttpStatusCode.OK)
                            {
                                using (Stream dataStream = resp.GetResponseStream())
                                {
                                    using (StreamReader reader = new StreamReader(dataStream))
                                    {
                                        var response = reader.ReadToEnd();
                                        Plugin.Log($"Status: {resp.StatusCode} ({resp.StatusDescription}), Response: {response}");
                                        continue;
                                    }
                                }
                            }

                            using (Stream dataStream = resp.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(dataStream))
                                {
                                    // Read the response into a JSON objecet
                                    var json = JSON.Parse(reader.ReadToEnd()).AsObject;

                                    // Then create a new YouTubeMessage object from it and send it along to the other StreamCore clients, excluding the assembly that sent the message
                                    var newMessage = new YouTubeMessage();
                                    newMessage.Update(json);

                                    var assemblyHash = messageToSend.Key.ToString();
                                    // Invoke YouTube message received callbacks
                                    YouTubeMessageHandlers.InvokeHandler(newMessage, assemblyHash);

                                    _sendQueue.TryDequeue(out var gone);
                                }
                            }
                        }
                    }
                    catch (ThreadAbortException ex)
                    {
                        return;
                    }
                    catch (Exception ex)
                    {
                        // Failed the send the message for some other reason, it will be retried next iteration
                        Plugin.Log($"Failed to send YouTube message, trying again in a few seconds! {ex.ToString()}");
                        Thread.Sleep(2500);
                    }
                }
            }
        }