We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[niconico_dmc] Heartbeat failed with SOCKS5 `HTTPS?_PROXY` env

## Checklist

- [x] I'm reporting a broken site support
- [x] I've verified that I'm running yt-dlp version **2021.09.02**
- [x] I've checked that all provided URLs are alive and playable in a browser
- [x] I've checked that all URLs and arguments with special characters are properly quoted or escaped
- [x] I've searched the bugtracker for similar issues including closed ones


## Verbose log

```
$ HTTP_PROXY=socks5://127.0.0.1:10080 HTTPS_PROXY=socks5://127.0.0.1:10080 yt-dlp --verbose --proxy socks5://127.0.0.1:10080 https://www.nicovideo.jp/watch/sm9
[debug] Command-line config: ['--verbose', '--proxy', 'socks5://127.0.0.1:10080', 'https://www.nicovideo.jp/watch/sm9']
[debug] Encodings: locale UTF-8, fs utf-8, out utf-8, pref UTF-8
[debug] yt-dlp version 2021.09.02 (source)
[debug] Python version 3.10.0rc2 (CPython 32bit) - Linux-3.10.49-armv7l-with-libc
[debug] exe versions: ffmpeg 4.4, ffprobe 4.4
[debug] Optional libraries: mutagen, pycryptodome, sqlite, websockets
[debug] Proxy map: {'http': 'socks5://127.0.0.1:10080', 'https': 'socks5://127.0.0.1:10080'}
[debug] [niconico] Extracting URL: https://www.nicovideo.jp/watch/sm9
[niconico] sm9: Downloading webpage
[niconico] sm9: Downloading video info page
[debug] Formats sorted by: hasvid, ie_pref, lang, quality, res, fps, vcodec:vp9.2(10), acodec, filesize, fs_approx, tbr, vbr, abr, asr, proto, vext, aext, hasaud, source, id
[debug] Default format spec: bestvideo*+bestaudio/best
[info] sm9: Downloading 1 format(s): h264_360p-aac_128kbps
[debug] Invoking downloader on "niconico_dmc:sm9/archive_h264_360p/archive_aac_128kbps"
[niconico_dmc] Downloading from DMC
[niconico] sm9: Downloading JSON metadata for h264_360p-aac_128kbps
[niconico] sm9: Acquiring permission for downloading video
[niconico_dmc] Heartbeat with 40 second interval ...
[niconico_dmc] Heartbeat failed
[download] Destination: 新・豪血寺一族 -煩悩解放 - レッツゴー！陰陽師 [sm9].mp4
[download]  25.4% of 26.95MiB at 174.88KiB/s ETA 01:57[niconico_dmc] Heartbeat failed
[download]  39.8% of 26.95MiB at 137.12KiB/s ETA 02:01[niconico_dmc] Heartbeat failed
[download]  53.6% of 26.95MiB at 124.49KiB/s ETA 01:42[download] Got server HTTP error: Downloaded 15136650 bytes, expected 28261021 bytes. Retrying (attempt 1 of 10) ...
```


## Description

There seem to be two separate issues:
 - niconico_dmc heartbeat connection does not respect the `--proxy` option, and
 - it cannot connect via a SOCKS5 server.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `yt_dlp/downloader/niconico.py`
Content:
```
1 # coding: utf-8
2 from __future__ import unicode_literals
3 
4 import threading
5 
6 from .common import FileDownloader
7 from ..downloader import get_suitable_downloader
8 from ..extractor.niconico import NiconicoIE
9 from ..compat import compat_urllib_request
10 
11 
12 class NiconicoDmcFD(FileDownloader):
13     """ Downloading niconico douga from DMC with heartbeat """
14 
15     FD_NAME = 'niconico_dmc'
16 
17     def real_download(self, filename, info_dict):
18         self.to_screen('[%s] Downloading from DMC' % self.FD_NAME)
19 
20         ie = NiconicoIE(self.ydl)
21         info_dict, heartbeat_info_dict = ie._get_heartbeat_info(info_dict)
22 
23         fd = get_suitable_downloader(info_dict, params=self.params)(self.ydl, self.params)
24 
25         success = download_complete = False
26         timer = [None]
27         heartbeat_lock = threading.Lock()
28         heartbeat_url = heartbeat_info_dict['url']
29         heartbeat_data = heartbeat_info_dict['data'].encode()
30         heartbeat_interval = heartbeat_info_dict.get('interval', 30)
31 
32         def heartbeat():
33             try:
34                 compat_urllib_request.urlopen(url=heartbeat_url, data=heartbeat_data)
35             except Exception:
36                 self.to_screen('[%s] Heartbeat failed' % self.FD_NAME)
37 
38             with heartbeat_lock:
39                 if not download_complete:
40                     timer[0] = threading.Timer(heartbeat_interval, heartbeat)
41                     timer[0].start()
42 
43         heartbeat_info_dict['ping']()
44         self.to_screen('[%s] Heartbeat with %d second interval ...' % (self.FD_NAME, heartbeat_interval))
45         try:
46             heartbeat()
47             if type(fd).__name__ == 'HlsFD':
48                 info_dict.update(ie._extract_m3u8_formats(info_dict['url'], info_dict['id'])[0])
49             success = fd.real_download(filename, info_dict)
50         finally:
51             if heartbeat_lock:
52                 with heartbeat_lock:
53                     timer[0].cancel()
54                     download_complete = True
55             return success
56
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/yt_dlp/downloader/niconico.py b/yt_dlp/downloader/niconico.py
--- a/yt_dlp/downloader/niconico.py
+++ b/yt_dlp/downloader/niconico.py
@@ -6,7 +6,7 @@
 from .common import FileDownloader
 from ..downloader import get_suitable_downloader
 from ..extractor.niconico import NiconicoIE
-from ..compat import compat_urllib_request
+from ..utils import sanitized_Request
 
 
 class NiconicoDmcFD(FileDownloader):
@@ -29,9 +29,11 @@
         heartbeat_data = heartbeat_info_dict['data'].encode()
         heartbeat_interval = heartbeat_info_dict.get('interval', 30)
 
+        request = sanitized_Request(heartbeat_url, heartbeat_data)
+
         def heartbeat():
             try:
-                compat_urllib_request.urlopen(url=heartbeat_url, data=heartbeat_data)
+                self.ydl.urlopen(request).read()
             except Exception:
                 self.to_screen('[%s] Heartbeat failed' % self.FD_NAME)

{"golden_diff": "diff --git a/yt_dlp/downloader/niconico.py b/yt_dlp/downloader/niconico.py\n--- a/yt_dlp/downloader/niconico.py\n+++ b/yt_dlp/downloader/niconico.py\n@@ -6,7 +6,7 @@\n from .common import FileDownloader\n from ..downloader import get_suitable_downloader\n from ..extractor.niconico import NiconicoIE\n-from ..compat import compat_urllib_request\n+from ..utils import sanitized_Request\n \n \n class NiconicoDmcFD(FileDownloader):\n@@ -29,9 +29,11 @@\n         heartbeat_data = heartbeat_info_dict['data'].encode()\n         heartbeat_interval = heartbeat_info_dict.get('interval', 30)\n \n+        request = sanitized_Request(heartbeat_url, heartbeat_data)\n+\n         def heartbeat():\n             try:\n-                compat_urllib_request.urlopen(url=heartbeat_url, data=heartbeat_data)\n+                self.ydl.urlopen(request).read()\n             except Exception:\n                 self.to_screen('[%s] Heartbeat failed' % self.FD_NAME)\n", "issue": "[niconico_dmc] Heartbeat failed with SOCKS5 `HTTPS?_PROXY` env\n\r\n## Checklist\r\n\r\n- [x] I'm reporting a broken site support\r\n- [x] I've verified that I'm running yt-dlp version **2021.09.02**\r\n- [x] I've checked that all provided URLs are alive and playable in a browser\r\n- [x] I've checked that all URLs and arguments with special characters are properly quoted or escaped\r\n- [x] I've searched the bugtracker for similar issues including closed ones\r\n\r\n\r\n## Verbose log\r\n\r\n```\r\n$ HTTP_PROXY=socks5://127.0.0.1:10080 HTTPS_PROXY=socks5://127.0.0.1:10080 yt-dlp --verbose --proxy socks5://127.0.0.1:10080 https://www.nicovideo.jp/watch/sm9\r\n[debug] Command-line config: ['--verbose', '--proxy', 'socks5://127.0.0.1:10080', 'https://www.nicovideo.jp/watch/sm9']\r\n[debug] Encodings: locale UTF-8, fs utf-8, out utf-8, pref UTF-8\r\n[debug] yt-dlp version 2021.09.02 (source)\r\n[debug] Python version 3.10.0rc2 (CPython 32bit) - Linux-3.10.49-armv7l-with-libc\r\n[debug] exe versions: ffmpeg 4.4, ffprobe 4.4\r\n[debug] Optional libraries: mutagen, pycryptodome, sqlite, websockets\r\n[debug] Proxy map: {'http': 'socks5://127.0.0.1:10080', 'https': 'socks5://127.0.0.1:10080'}\r\n[debug] [niconico] Extracting URL: https://www.nicovideo.jp/watch/sm9\r\n[niconico] sm9: Downloading webpage\r\n[niconico] sm9: Downloading video info page\r\n[debug] Formats sorted by: hasvid, ie_pref, lang, quality, res, fps, vcodec:vp9.2(10), acodec, filesize, fs_approx, tbr, vbr, abr, asr, proto, vext, aext, hasaud, source, id\r\n[debug] Default format spec: bestvideo*+bestaudio/best\r\n[info] sm9: Downloading 1 format(s): h264_360p-aac_128kbps\r\n[debug] Invoking downloader on \"niconico_dmc:sm9/archive_h264_360p/archive_aac_128kbps\"\r\n[niconico_dmc] Downloading from DMC\r\n[niconico] sm9: Downloading JSON metadata for h264_360p-aac_128kbps\r\n[niconico] sm9: Acquiring permission for downloading video\r\n[niconico_dmc] Heartbeat with 40 second interval ...\r\n[niconico_dmc] Heartbeat failed\r\n[download] Destination: \u65b0\u30fb\u8c6a\u8840\u5bfa\u4e00\u65cf -\u7169\u60a9\u89e3\u653e - \u30ec\u30c3\u30c4\u30b4\u30fc\uff01\u9670\u967d\u5e2b [sm9].mp4\r\n[download]  25.4% of 26.95MiB at 174.88KiB/s ETA 01:57[niconico_dmc] Heartbeat failed\r\n[download]  39.8% of 26.95MiB at 137.12KiB/s ETA 02:01[niconico_dmc] Heartbeat failed\r\n[download]  53.6% of 26.95MiB at 124.49KiB/s ETA 01:42[download] Got server HTTP error: Downloaded 15136650 bytes, expected 28261021 bytes. Retrying (attempt 1 of 10) ...\r\n```\r\n\r\n\r\n## Description\r\n\r\nThere seem to be two separate issues:\r\n - niconico_dmc heartbeat connection does not respect the `--proxy` option, and\r\n - it cannot connect via a SOCKS5 server.\r\n\n", "before_files": [{"content": "# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport threading\n\nfrom .common import FileDownloader\nfrom ..downloader import get_suitable_downloader\nfrom ..extractor.niconico import NiconicoIE\nfrom ..compat import compat_urllib_request\n\n\nclass NiconicoDmcFD(FileDownloader):\n    \"\"\" Downloading niconico douga from DMC with heartbeat \"\"\"\n\n    FD_NAME = 'niconico_dmc'\n\n    def real_download(self, filename, info_dict):\n        self.to_screen('[%s] Downloading from DMC' % self.FD_NAME)\n\n        ie = NiconicoIE(self.ydl)\n        info_dict, heartbeat_info_dict = ie._get_heartbeat_info(info_dict)\n\n        fd = get_suitable_downloader(info_dict, params=self.params)(self.ydl, self.params)\n\n        success = download_complete = False\n        timer = [None]\n        heartbeat_lock = threading.Lock()\n        heartbeat_url = heartbeat_info_dict['url']\n        heartbeat_data = heartbeat_info_dict['data'].encode()\n        heartbeat_interval = heartbeat_info_dict.get('interval', 30)\n\n        def heartbeat():\n            try:\n                compat_urllib_request.urlopen(url=heartbeat_url, data=heartbeat_data)\n            except Exception:\n                self.to_screen('[%s] Heartbeat failed' % self.FD_NAME)\n\n            with heartbeat_lock:\n                if not download_complete:\n                    timer[0] = threading.Timer(heartbeat_interval, heartbeat)\n                    timer[0].start()\n\n        heartbeat_info_dict['ping']()\n        self.to_screen('[%s] Heartbeat with %d second interval ...' % (self.FD_NAME, heartbeat_interval))\n        try:\n            heartbeat()\n            if type(fd).__name__ == 'HlsFD':\n                info_dict.update(ie._extract_m3u8_formats(info_dict['url'], info_dict['id'])[0])\n            success = fd.real_download(filename, info_dict)\n        finally:\n            if heartbeat_lock:\n                with heartbeat_lock:\n                    timer[0].cancel()\n                    download_complete = True\n            return success\n", "path": "yt_dlp/downloader/niconico.py"}], "after_files": [{"content": "# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport threading\n\nfrom .common import FileDownloader\nfrom ..downloader import get_suitable_downloader\nfrom ..extractor.niconico import NiconicoIE\nfrom ..utils import sanitized_Request\n\n\nclass NiconicoDmcFD(FileDownloader):\n    \"\"\" Downloading niconico douga from DMC with heartbeat \"\"\"\n\n    FD_NAME = 'niconico_dmc'\n\n    def real_download(self, filename, info_dict):\n        self.to_screen('[%s] Downloading from DMC' % self.FD_NAME)\n\n        ie = NiconicoIE(self.ydl)\n        info_dict, heartbeat_info_dict = ie._get_heartbeat_info(info_dict)\n\n        fd = get_suitable_downloader(info_dict, params=self.params)(self.ydl, self.params)\n\n        success = download_complete = False\n        timer = [None]\n        heartbeat_lock = threading.Lock()\n        heartbeat_url = heartbeat_info_dict['url']\n        heartbeat_data = heartbeat_info_dict['data'].encode()\n        heartbeat_interval = heartbeat_info_dict.get('interval', 30)\n\n        request = sanitized_Request(heartbeat_url, heartbeat_data)\n\n        def heartbeat():\n            try:\n                self.ydl.urlopen(request).read()\n            except Exception:\n                self.to_screen('[%s] Heartbeat failed' % self.FD_NAME)\n\n            with heartbeat_lock:\n                if not download_complete:\n                    timer[0] = threading.Timer(heartbeat_interval, heartbeat)\n                    timer[0].start()\n\n        heartbeat_info_dict['ping']()\n        self.to_screen('[%s] Heartbeat with %d second interval ...' % (self.FD_NAME, heartbeat_interval))\n        try:\n            heartbeat()\n            if type(fd).__name__ == 'HlsFD':\n                info_dict.update(ie._extract_m3u8_formats(info_dict['url'], info_dict['id'])[0])\n            success = fd.real_download(filename, info_dict)\n        finally:\n            if heartbeat_lock:\n                with heartbeat_lock:\n                    timer[0].cancel()\n                    download_complete = True\n            return success\n", "path": "yt_dlp/downloader/niconico.py"}]}