Skip to content

plugins.vk: add support for WAF cookie #4638

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 7, 2022
Merged

Conversation

mkbloke
Copy link
Member

@mkbloke mkbloke commented Jul 4, 2022

Also corrected the API POST params/data dicts.

closes #4637

@mkbloke mkbloke added the plugin issue A Plugin does not work correctly label Jul 4, 2022
Copy link
Member

@bastimeyer bastimeyer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first URL from the tests is returning this:

$ streamlink 'https://vk.com/video-9944999_456239622' best -l debug
...
[plugins.vk][debug] Saved cookie not found.
[plugins.vk][info] Getting new cookie.
error: Unable to open URL: https://vk.com/429.html?hash429=wMF4IzvUyM5acpz9RUB7S4wasLQWDuHjX7ptYhUSQedbwJd8ViiIDIUF4MapFBvaDBhxzkauoVfsYbzXN5VPlqMwIaoPMD2aWbxtyC4GCp1JMgkjuRc6&redirect429=/&key=87477569783524fc736506c9a64450f4 (429 Client Error: Too Many Requests for url: https://vk.com/)

@back-to
Copy link
Collaborator

back-to commented Jul 5, 2022

might be region based


without PR, plugin works

$ streamlink https://vk.com/video-106042931_456240719 -l info
[cli][info] Found matching plugin vk for URL https://vk.com/video-106042931_456240719
[cli][info] Available streams: 240p (worst), 360p, 480p, 720p (best)
[cli][info] Opening stream: 720p (hls)

with this PR, plugin is broken

$ streamlink https://vk.com/video-106042931_456240719 -l info
[cli][info] Found matching plugin vk for URL https://vk.com/video-106042931_456240719
[plugins.vk][info] Getting new cookie.
[plugins.vk][error] Failed to get expected hash cookie.
error: No playable streams found on this URL: https://vk.com/video-106042931_456240719

Copy link
Member

@bastimeyer bastimeyer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't add hooks to the entire HTTP session. This is bad.

That should do the trick:

diff --git a/src/streamlink/plugins/vk.py b/src/streamlink/plugins/vk.py
index 33a6365c..c72e9458 100644
--- a/src/streamlink/plugins/vk.py
+++ b/src/streamlink/plugins/vk.py
@@ -14,6 +14,7 @@ from streamlink.plugin import Plugin, PluginError, pluginmatcher
 from streamlink.plugin.api import validate
 from streamlink.stream.dash import DASHStream
 from streamlink.stream.hls import HLSStream
+from streamlink.utils.url import update_qsd
 
 log = logging.getLogger(__name__)
 
@@ -29,24 +30,25 @@ class VK(Plugin):
     HASH_COOKIE = "hash429"
     SOLUTION_COOKIE = "solution429"
 
-    def check_for_waf(self, res, **kwargs):
-        if res.headers.get("X-WAF-Backend-Status") == "challenge_success" and hasattr(self, "original_request"):
-            self.session.http.cookies.update(res.cookies)
-            self.session.http.cookies.pop(self.HASH_COOKIE, None)
-            self.original_request.headers.pop("Cookie", None)
-            self.original_request.prepare_cookies(self.session.http.cookies)
-            res = self.session.http.send(self.original_request)
-            del self.original_request
-            self.save_cookies(cookie_filter=lambda c: c.name == self.SOLUTION_COOKIE)
-            return res
-
-        if res.status_code == 302 and res.cookies.get(self.HASH_COOKIE):
-            log.debug("Getting new WAF cookie")
-            cookie = res.cookies.get(self.HASH_COOKIE)
-            key = md5(cookie.encode("utf-8")).hexdigest()
-            res.headers["Location"] = f"{res.headers['Location']}&key={key}"
-            self.original_request = res.request
-            return res
+    def _get_cookies(self):
+        if self.session.http.cookies.get(self.SOLUTION_COOKIE, domain=".vk.com"):
+            log.debug("Using cached WAF cookie")
+            return
+
+        def on_response(res, **kwargs):
+            if res.headers.get("x-waf-redirect") == "1":
+                if not res.headers.get("X-WAF-Backend-Status"):
+                    log.debug("Getting new WAF cookie")
+                    cookie = res.cookies.get(self.HASH_COOKIE)
+                    key = md5(cookie.encode("utf-8")).hexdigest()
+                    res.headers["Location"] = update_qsd(res.headers["Location"], qsd={"key": key})
+                    return res
+                elif res.headers.get("X-WAF-Backend-Status") == "challenge_success":
+                    self.session.http.cookies.update(res.cookies)
+                    self.save_cookies(cookie_filter=lambda c: c.name == self.SOLUTION_COOKIE)
+                    return res
+
+        self.session.http.get("https://vk.com/", hooks={"response": on_response})
 
     def _has_video_id(self):
         return any(m for m in self.matches[:-1])
@@ -78,8 +80,7 @@ class VK(Plugin):
         raise NoStreamsError(self.url)
 
     def _get_streams(self):
-        self.session.http.hooks["response"] = self.check_for_waf
-
+        self._get_cookies()
         self.follow_vk_redirect()
 
         video_id = self.match.group("video_id")

@mkbloke
Copy link
Member Author

mkbloke commented Jul 7, 2022

One of the reasons for some of the logic I put into the original code is that it didn't require an initial probe. Some of the other logic was to handle the case that if you change IP address (or maybe region, who knows, but the latter can happen if you're a VPN user), an existing solution429 cookie becomes invalid and will need replacing. This scenario now fails with the code above. Dropping the return in _get_cookies() will fix that issue, as long as you're OK with running the probe every time.

@bastimeyer
Copy link
Member

Just make the initial request every time, and don't store the cookie, as it's unnecessary.

@bastimeyer
Copy link
Member

bastimeyer commented Jul 7, 2022

The self.session.http.cookies.update(res.cookies) on res.headers.get("X-WAF-Backend-Status") == "challenge_success" should be redundant, as requests will update the session cookies after the hook has been executed anyway. Unfortunately, I don't get the cookie requirement right now, so I can't check. (oops, had the cookie still stored) Doesn't matter though, going to merge.

@bastimeyer bastimeyer merged commit ec9f5a9 into streamlink:master Jul 7, 2022
@mkbloke mkbloke deleted the vk branch July 7, 2022 07:56
Billy2011 added a commit to Billy2011/streamlink-27 that referenced this pull request Jul 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
plugin issue A Plugin does not work correctly
Projects
None yet
Development

Successfully merging this pull request may close these issues.

plugins.vk: fixes required
3 participants