import re

from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.stream import HLSStream

HLS_URL_FORMAT = "https://hls.goodgame.ru/hls/{0}{1}.m3u8"
QUALITIES = {
    "1080p": "",
    "720p": "_720",
    "480p": "_480",
    "240p": "_240"
}

_url_re = re.compile(r"https?://(?:www\.)?goodgame.ru/channel/(?P<user>[^/]+)")
_stream_re = re.compile(r'var src = "([^"]+)";')
_ddos_re = re.compile(r'document.cookie="(__DDOS_[^;]+)')


class GoodGame(Plugin):
    @classmethod
    def can_handle_url(cls, url):
        return _url_re.match(url)

    def _check_stream(self, url):
        res = http.get(url, acceptable_status=(200, 404))
        if res.status_code == 200:
            return True

    def _get_streams(self):
        headers = {
            "Referer": self.url
        }
        res = http.get(self.url, headers=headers)

        match = _ddos_re.search(res.text)
        if match:
            headers["Cookie"] = match.group(1)
            res = http.get(self.url, headers=headers)

        match = _stream_re.search(res.text)
        if not match:
            return

        stream_id = match.group(1)
        streams = {}
        for name, url_suffix in QUALITIES.items():
            url = HLS_URL_FORMAT.format(stream_id, url_suffix)
            if not self._check_stream(url):
                continue

            streams[name] = HLSStream(self.session, url)

        return streams


__plugin__ = GoodGame

@@ -119,16 +119,56 @@
 LSStream
+%0Afrom streamlink.utils import parse_json
 %0A%0AHLS_UR
@@ -394,22 +394,23 @@
 /%5D+)%22)%0A_
-stream
+apidata
 _re = re
@@ -427,26 +427,51 @@
 'var
- src = %22(%5B%5E%22%5D+)%22;'
+%5Cs+ApiData%5Cs*=%5Cs*(%7B.*?%7D)%5Cs*;', re.MULTILINE
 )%0A_d
@@ -983,32 +983,85 @@
       if match:%0A
+            self.logger.debug(%22Anti-DDOS bypass...%22)%0A
             head
@@ -1163,22 +1163,23 @@
 atch = _
-stream
+apidata
 _re.sear
@@ -1252,26 +1252,121 @@
 eam_
-id = match.group(1
+data = parse_json(match.group(1))%0A        self.logger.debug(%22Found channel info for %7Bchannel_key%7D%22, **stream_data
 )%0A  
@@ -1482,18 +1482,34 @@
 (stream_
-i
 d
+ata%5B%22channel_id%22%5D
 , url_su

update for change in page layout