repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
pyodide/pyodide
4,435
pyodide__pyodide-4435
[ "4420" ]
2824ffa52373c7df7547b426b46178c97ab237ef
diff --git a/pyodide-build/pyodide_build/pyzip.py b/pyodide-build/pyodide_build/pyzip.py --- a/pyodide-build/pyodide_build/pyzip.py +++ b/pyodide-build/pyodide_build/pyzip.py @@ -28,7 +28,6 @@ # These files are unvendored from the stdlib and can be loaded with `loadPackage` UNVENDORED_FILES = ( "test/", - "distutils/", "sqlite3", "ssl.py", "lzma.py",
diff --git a/packages/distutils/test_distutils.py b/packages/distutils/test_distutils.py deleted file mode 100644 --- a/packages/distutils/test_distutils.py +++ /dev/null @@ -1,34 +0,0 @@ -from pytest_pyodide import run_in_pyodide - - -@run_in_pyodide(packages=["test", "distutils"], pytest_assert_rewrites=False) -def test_distutils(selenium): - import sys - import unittest - import unittest.mock - from test.libregrtest.main import main - - name = "test_distutils" - - ignore_tests = [ - "test_check_environ_getpwuid", # no pwd - "test_get_platform", # no _osx_support - "test_simple_built", - "test_optional_extension", # thread - "test_customize_compiler_before_get_config_vars", # subprocess - "test_spawn", # subprocess - "test_debug_mode", # no _osx_support - "test_record", # no _osx_support - "test_get_config_h_filename", # /include/python3.10/pyconfig.h not exists - "test_srcdir", # /lib/python3.10/config-3.10-wasm32-emscripten not exists - "test_mkpath_with_custom_mode", - "test_finalize_options", # no executable - ] - match_tests = [[pat, False] for pat in ignore_tests] - - sys.modules["_osx_support"] = unittest.mock.Mock() - try: - main([name], match_tests=match_tests, verbose=True, verbose3=True) - except SystemExit as e: - if e.code != 0: - raise RuntimeError(f"Failed with code: {e.code}") from None diff --git a/packages/test/meta.yaml b/packages/test/meta.yaml --- a/packages/test/meta.yaml +++ b/packages/test/meta.yaml @@ -14,13 +14,49 @@ build: cat $(PYODIDE_ROOT)/cpython/patches/* | patch -p1 export TEST_EXTENSIONS="\ _testinternalcapi.so \ - _testcapi.so \ _testbuffer.so \ _testimportmultiple.so \ _testmultiphase.so \ _ctypes_test.so \ " + export TEST_CAPI_SRCS=( \ + _testcapimodule.c \ + _testcapi/vectorcall.c \ + _testcapi/vectorcall_limited.c \ + _testcapi/heaptype.c \ + _testcapi/abstract.c \ + _testcapi/bytearray.c \ + _testcapi/bytes.c \ + _testcapi/unicode.c \ + _testcapi/dict.c \ + _testcapi/set.c \ + _testcapi/list.c \ + _testcapi/tuple.c \ + _testcapi/getargs.c \ + _testcapi/pytime.c \ + _testcapi/datetime.c \ + _testcapi/docstring.c \ + _testcapi/mem.c \ + _testcapi/watchers.c \ + _testcapi/long.c \ + _testcapi/float.c \ + _testcapi/complex.c \ + _testcapi/numbers.c \ + _testcapi/structmember.c \ + _testcapi/exceptions.c \ + _testcapi/code.c \ + _testcapi/buffer.c \ + _testcapi/pyos.c \ + _testcapi/file.c \ + _testcapi/codec.c \ + _testcapi/immortal.c \ + _testcapi/heaptype_relative.c \ + _testcapi/gc.c \ + _testcapi/sys.c \ + ) + + export TEST_MODULE_CFLAGS="${SIDE_MODULE_CFLAGS} -I Include/ -I Include/internal/ -I ." emcc ${TEST_MODULE_CFLAGS} -c Modules/_testinternalcapi.c -o Modules/_testinternalcapi.o \ @@ -31,11 +67,18 @@ build: emcc ${TEST_MODULE_CFLAGS} -c Modules/_testmultiphase.c -o Modules/_testmultiphase.o emcc ${TEST_MODULE_CFLAGS} -c Modules/_ctypes/_ctypes_test.c -o Modules/_ctypes_test.o + for capi_src in ${TEST_CAPI_SRCS[@]}; do \ + emcc ${TEST_MODULE_CFLAGS} -c Modules/${capi_src} -o Modules/${capi_src/.c/.o} + done + + export TEST_CAPI_OBJECTS=( "${TEST_CAPI_SRCS[@]/#/Modules/}" ) + emcc ${SIDE_MODULE_LDFLAGS} ${TEST_CAPI_OBJECTS[@]//.c/.o} -o ${DISTDIR}/_testcapi.so + for testname in ${TEST_EXTENSIONS}; do \ emcc Modules/${testname/.so/.o} -o ${DISTDIR}/$testname ${SIDE_MODULE_LDFLAGS} done cd Lib && \ tar --exclude=__pycache__ -cf - \ - test distutils/tests sqlite3/test \ + test test/test_sqlite3/ \ | tar -C $DISTDIR -xf - diff --git a/packages/test/patches/0005-gh-93839-Move-Lib-ctypes-test-to-Lib-test-test_ctype.patch b/packages/test/patches/0005-gh-93839-Move-Lib-ctypes-test-to-Lib-test-test_ctype.patch deleted file mode 100644 --- a/packages/test/patches/0005-gh-93839-Move-Lib-ctypes-test-to-Lib-test-test_ctype.patch +++ /dev/null @@ -1,753 +0,0 @@ -From d82e0bfe8b98a122ca443b356d81998c804b686e Mon Sep 17 00:00:00 2001 -From: Victor Stinner <[email protected]> -Date: Tue, 21 Jun 2022 10:24:33 +0200 -Subject: [PATCH 5/9] gh-93839: Move Lib/ctypes/test/ to Lib/test/test_ctypes/ - (#94041) - -* Move Lib/ctypes/test/ to Lib/test/test_ctypes/ -* Remove Lib/test/test_ctypes.py -* Update imports and build system. ---- - Lib/ctypes/test/__main__.py | 4 - - Lib/test/leakers/test_ctypes.py | 2 +- - Lib/test/test_ctypes.py | 10 -- - .../test => test/test_ctypes}/__init__.py | 0 - Lib/test/test_ctypes/__main__.py | 4 + - .../test => test/test_ctypes}/test_anon.py | 0 - .../test_ctypes}/test_array_in_pointer.py | 0 - .../test => test/test_ctypes}/test_arrays.py | 2 +- - .../test_ctypes}/test_as_parameter.py | 2 +- - .../test_ctypes}/test_bitfields.py | 2 +- - .../test => test/test_ctypes}/test_buffers.py | 2 +- - .../test => test/test_ctypes}/test_bytes.py | 0 - .../test_ctypes}/test_byteswap.py | 0 - .../test_ctypes}/test_callbacks.py | 2 +- - .../test => test/test_ctypes}/test_cast.py | 2 +- - .../test => test/test_ctypes}/test_cfuncs.py | 2 +- - .../test_ctypes}/test_checkretval.py | 2 +- - .../test => test/test_ctypes}/test_delattr.py | 0 - .../test => test/test_ctypes}/test_errno.py | 0 - .../test => test/test_ctypes}/test_find.py | 0 - .../test_ctypes}/test_frombuffer.py | 0 - .../test => test/test_ctypes}/test_funcptr.py | 0 - .../test_ctypes}/test_functions.py | 2 +- - .../test_ctypes}/test_incomplete.py | 0 - .../test => test/test_ctypes}/test_init.py | 0 - .../test_ctypes}/test_internals.py | 0 - .../test_ctypes}/test_keeprefs.py | 0 - .../test => test/test_ctypes}/test_libc.py | 0 - .../test => test/test_ctypes}/test_loading.py | 0 - .../test_ctypes}/test_macholib.py | 0 - .../test_ctypes}/test_memfunctions.py | 2 +- - .../test => test/test_ctypes}/test_numbers.py | 0 - .../test => test/test_ctypes}/test_objects.py | 8 +- - .../test_ctypes}/test_parameters.py | 2 +- - .../test => test/test_ctypes}/test_pep3118.py | 0 - .../test_ctypes}/test_pickling.py | 0 - .../test_ctypes}/test_pointers.py | 0 - .../test_ctypes}/test_prototypes.py | 2 +- - .../test_ctypes}/test_python_api.py | 0 - .../test_ctypes}/test_random_things.py | 0 - .../test_ctypes}/test_refcounts.py | 0 - .../test => test/test_ctypes}/test_repr.py | 0 - .../test_ctypes}/test_returnfuncptrs.py | 0 - .../test_ctypes}/test_simplesubclasses.py | 0 - .../test => test/test_ctypes}/test_sizes.py | 0 - .../test => test/test_ctypes}/test_slicing.py | 2 +- - .../test_ctypes}/test_stringptr.py | 0 - .../test => test/test_ctypes}/test_strings.py | 2 +- - .../test_ctypes}/test_struct_fields.py | 0 - .../test_ctypes}/test_structures.py | 2 +- - .../test_ctypes}/test_unaligned_structures.py | 0 - .../test => test/test_ctypes}/test_unicode.py | 2 +- - .../test => test/test_ctypes}/test_values.py | 0 - .../test_ctypes}/test_varsize_struct.py | 0 - .../test => test/test_ctypes}/test_win32.py | 0 - .../test_ctypes}/test_wintypes.py | 0 - Makefile.pre.in | 4 +- - ...2-06-20-23-04-52.gh-issue-93839.OE3Ybk.rst | 2 + - PCbuild/lib.pyproj | 109 +++++++++--------- - Tools/wasm/wasm_assets.py | 1 - - 60 files changed, 83 insertions(+), 93 deletions(-) - delete mode 100644 Lib/ctypes/test/__main__.py - delete mode 100644 Lib/test/test_ctypes.py - rename Lib/{ctypes/test => test/test_ctypes}/__init__.py (100%) - create mode 100644 Lib/test/test_ctypes/__main__.py - rename Lib/{ctypes/test => test/test_ctypes}/test_anon.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_array_in_pointer.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_arrays.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_as_parameter.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_bitfields.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_buffers.py (98%) - rename Lib/{ctypes/test => test/test_ctypes}/test_bytes.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_byteswap.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_callbacks.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_cast.py (98%) - rename Lib/{ctypes/test => test/test_ctypes}/test_cfuncs.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_checkretval.py (95%) - rename Lib/{ctypes/test => test/test_ctypes}/test_delattr.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_errno.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_find.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_frombuffer.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_funcptr.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_functions.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_incomplete.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_init.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_internals.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_keeprefs.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_libc.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_loading.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_macholib.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_memfunctions.py (98%) - rename Lib/{ctypes/test => test/test_ctypes}/test_numbers.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_objects.py (87%) - rename Lib/{ctypes/test => test/test_ctypes}/test_parameters.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_pep3118.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_pickling.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_pointers.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_prototypes.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_python_api.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_random_things.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_refcounts.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_repr.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_returnfuncptrs.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_simplesubclasses.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_sizes.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_slicing.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_stringptr.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_strings.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_struct_fields.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_structures.py (99%) - rename Lib/{ctypes/test => test/test_ctypes}/test_unaligned_structures.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_unicode.py (97%) - rename Lib/{ctypes/test => test/test_ctypes}/test_values.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_varsize_struct.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_win32.py (100%) - rename Lib/{ctypes/test => test/test_ctypes}/test_wintypes.py (100%) - create mode 100644 Misc/NEWS.d/next/Tests/2022-06-20-23-04-52.gh-issue-93839.OE3Ybk.rst - -diff --git a/Lib/ctypes/test/__main__.py b/Lib/ctypes/test/__main__.py -deleted file mode 100644 -index 362a9ec8cf..0000000000 ---- a/Lib/ctypes/test/__main__.py -+++ /dev/null -@@ -1,4 +0,0 @@ --from ctypes.test import load_tests --import unittest -- --unittest.main() -diff --git a/Lib/test/leakers/test_ctypes.py b/Lib/test/leakers/test_ctypes.py -index 7d7e9ff3a1..ec09ac3699 100644 ---- a/Lib/test/leakers/test_ctypes.py -+++ b/Lib/test/leakers/test_ctypes.py -@@ -1,5 +1,5 @@ - --# Taken from Lib/ctypes/test/test_keeprefs.py, PointerToStructure.test(). -+# Taken from Lib/test/test_ctypes/test_keeprefs.py, PointerToStructure.test(). - - from ctypes import Structure, c_int, POINTER - import gc -diff --git a/Lib/test/test_ctypes.py b/Lib/test/test_ctypes.py -deleted file mode 100644 -index b0a12c9734..0000000000 ---- a/Lib/test/test_ctypes.py -+++ /dev/null -@@ -1,10 +0,0 @@ --import unittest --from test.support.import_helper import import_module -- -- --ctypes_test = import_module('ctypes.test') -- --load_tests = ctypes_test.load_tests -- --if __name__ == "__main__": -- unittest.main() -diff --git a/Lib/ctypes/test/__init__.py b/Lib/test/test_ctypes/__init__.py -similarity index 100% -rename from Lib/ctypes/test/__init__.py -rename to Lib/test/test_ctypes/__init__.py -diff --git a/Lib/test/test_ctypes/__main__.py b/Lib/test/test_ctypes/__main__.py -new file mode 100644 -index 0000000000..3003d4db89 ---- /dev/null -+++ b/Lib/test/test_ctypes/__main__.py -@@ -0,0 +1,4 @@ -+from test.test_ctypes import load_tests -+import unittest -+ -+unittest.main() -diff --git a/Lib/ctypes/test/test_anon.py b/Lib/test/test_ctypes/test_anon.py -similarity index 100% -rename from Lib/ctypes/test/test_anon.py -rename to Lib/test/test_ctypes/test_anon.py -diff --git a/Lib/ctypes/test/test_array_in_pointer.py b/Lib/test/test_ctypes/test_array_in_pointer.py -similarity index 100% -rename from Lib/ctypes/test/test_array_in_pointer.py -rename to Lib/test/test_ctypes/test_array_in_pointer.py -diff --git a/Lib/ctypes/test/test_arrays.py b/Lib/test/test_ctypes/test_arrays.py -similarity index 99% -rename from Lib/ctypes/test/test_arrays.py -rename to Lib/test/test_ctypes/test_arrays.py -index 14603b7049..415a5785a9 100644 ---- a/Lib/ctypes/test/test_arrays.py -+++ b/Lib/test/test_ctypes/test_arrays.py -@@ -3,7 +3,7 @@ - import sys - from ctypes import * - --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - - formats = "bBhHiIlLqQfd" - -diff --git a/Lib/ctypes/test/test_as_parameter.py b/Lib/test/test_ctypes/test_as_parameter.py -similarity index 99% -rename from Lib/ctypes/test/test_as_parameter.py -rename to Lib/test/test_ctypes/test_as_parameter.py -index f9d27cb89d..b35defb158 100644 ---- a/Lib/ctypes/test/test_as_parameter.py -+++ b/Lib/test/test_ctypes/test_as_parameter.py -@@ -1,6 +1,6 @@ - import unittest - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - import _ctypes_test - - dll = CDLL(_ctypes_test.__file__) -diff --git a/Lib/ctypes/test/test_bitfields.py b/Lib/test/test_ctypes/test_bitfields.py -similarity index 99% -rename from Lib/ctypes/test/test_bitfields.py -rename to Lib/test/test_ctypes/test_bitfields.py -index 66acd62e68..dad71a0ba7 100644 ---- a/Lib/ctypes/test/test_bitfields.py -+++ b/Lib/test/test_ctypes/test_bitfields.py -@@ -1,5 +1,5 @@ - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - from test import support - import unittest - import os -diff --git a/Lib/ctypes/test/test_buffers.py b/Lib/test/test_ctypes/test_buffers.py -similarity index 98% -rename from Lib/ctypes/test/test_buffers.py -rename to Lib/test/test_ctypes/test_buffers.py -index 15782be757..a9be2023aa 100644 ---- a/Lib/ctypes/test/test_buffers.py -+++ b/Lib/test/test_ctypes/test_buffers.py -@@ -1,5 +1,5 @@ - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - import unittest - - class StringBufferTestCase(unittest.TestCase): -diff --git a/Lib/ctypes/test/test_bytes.py b/Lib/test/test_ctypes/test_bytes.py -similarity index 100% -rename from Lib/ctypes/test/test_bytes.py -rename to Lib/test/test_ctypes/test_bytes.py -diff --git a/Lib/ctypes/test/test_byteswap.py b/Lib/test/test_ctypes/test_byteswap.py -similarity index 100% -rename from Lib/ctypes/test/test_byteswap.py -rename to Lib/test/test_ctypes/test_byteswap.py -diff --git a/Lib/ctypes/test/test_callbacks.py b/Lib/test/test_ctypes/test_callbacks.py -similarity index 99% -rename from Lib/ctypes/test/test_callbacks.py -rename to Lib/test/test_ctypes/test_callbacks.py -index 1099cf9a69..2758720d4a 100644 ---- a/Lib/ctypes/test/test_callbacks.py -+++ b/Lib/test/test_ctypes/test_callbacks.py -@@ -3,7 +3,7 @@ - from test import support - - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - from _ctypes import CTYPES_MAX_ARGCOUNT - import _ctypes_test - -diff --git a/Lib/ctypes/test/test_cast.py b/Lib/test/test_ctypes/test_cast.py -similarity index 98% -rename from Lib/ctypes/test/test_cast.py -rename to Lib/test/test_ctypes/test_cast.py -index 6878f97328..7ee23b16f1 100644 ---- a/Lib/ctypes/test/test_cast.py -+++ b/Lib/test/test_ctypes/test_cast.py -@@ -1,5 +1,5 @@ - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - import unittest - import sys - -diff --git a/Lib/ctypes/test/test_cfuncs.py b/Lib/test/test_ctypes/test_cfuncs.py -similarity index 99% -rename from Lib/ctypes/test/test_cfuncs.py -rename to Lib/test/test_ctypes/test_cfuncs.py -index ac2240fa19..0a9394bf31 100644 ---- a/Lib/ctypes/test/test_cfuncs.py -+++ b/Lib/test/test_ctypes/test_cfuncs.py -@@ -3,7 +3,7 @@ - - import unittest - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - - import _ctypes_test - -diff --git a/Lib/ctypes/test/test_checkretval.py b/Lib/test/test_ctypes/test_checkretval.py -similarity index 95% -rename from Lib/ctypes/test/test_checkretval.py -rename to Lib/test/test_ctypes/test_checkretval.py -index e9567dc391..1492099f4b 100644 ---- a/Lib/ctypes/test/test_checkretval.py -+++ b/Lib/test/test_ctypes/test_checkretval.py -@@ -1,7 +1,7 @@ - import unittest - - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - - class CHECKED(c_int): - def _check_retval_(value): -diff --git a/Lib/ctypes/test/test_delattr.py b/Lib/test/test_ctypes/test_delattr.py -similarity index 100% -rename from Lib/ctypes/test/test_delattr.py -rename to Lib/test/test_ctypes/test_delattr.py -diff --git a/Lib/ctypes/test/test_errno.py b/Lib/test/test_ctypes/test_errno.py -similarity index 100% -rename from Lib/ctypes/test/test_errno.py -rename to Lib/test/test_ctypes/test_errno.py -diff --git a/Lib/ctypes/test/test_find.py b/Lib/test/test_ctypes/test_find.py -similarity index 100% -rename from Lib/ctypes/test/test_find.py -rename to Lib/test/test_ctypes/test_find.py -diff --git a/Lib/ctypes/test/test_frombuffer.py b/Lib/test/test_ctypes/test_frombuffer.py -similarity index 100% -rename from Lib/ctypes/test/test_frombuffer.py -rename to Lib/test/test_ctypes/test_frombuffer.py -diff --git a/Lib/ctypes/test/test_funcptr.py b/Lib/test/test_ctypes/test_funcptr.py -similarity index 100% -rename from Lib/ctypes/test/test_funcptr.py -rename to Lib/test/test_ctypes/test_funcptr.py -diff --git a/Lib/ctypes/test/test_functions.py b/Lib/test/test_ctypes/test_functions.py -similarity index 99% -rename from Lib/ctypes/test/test_functions.py -rename to Lib/test/test_ctypes/test_functions.py -index f9e92e1cc6..4a784c8d79 100644 ---- a/Lib/ctypes/test/test_functions.py -+++ b/Lib/test/test_ctypes/test_functions.py -@@ -6,7 +6,7 @@ - """ - - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - import sys, unittest - - try: -diff --git a/Lib/ctypes/test/test_incomplete.py b/Lib/test/test_ctypes/test_incomplete.py -similarity index 100% -rename from Lib/ctypes/test/test_incomplete.py -rename to Lib/test/test_ctypes/test_incomplete.py -diff --git a/Lib/ctypes/test/test_init.py b/Lib/test/test_ctypes/test_init.py -similarity index 100% -rename from Lib/ctypes/test/test_init.py -rename to Lib/test/test_ctypes/test_init.py -diff --git a/Lib/ctypes/test/test_internals.py b/Lib/test/test_ctypes/test_internals.py -similarity index 100% -rename from Lib/ctypes/test/test_internals.py -rename to Lib/test/test_ctypes/test_internals.py -diff --git a/Lib/ctypes/test/test_keeprefs.py b/Lib/test/test_ctypes/test_keeprefs.py -similarity index 100% -rename from Lib/ctypes/test/test_keeprefs.py -rename to Lib/test/test_ctypes/test_keeprefs.py -diff --git a/Lib/ctypes/test/test_libc.py b/Lib/test/test_ctypes/test_libc.py -similarity index 100% -rename from Lib/ctypes/test/test_libc.py -rename to Lib/test/test_ctypes/test_libc.py -diff --git a/Lib/ctypes/test/test_loading.py b/Lib/test/test_ctypes/test_loading.py -similarity index 100% -rename from Lib/ctypes/test/test_loading.py -rename to Lib/test/test_ctypes/test_loading.py -diff --git a/Lib/ctypes/test/test_macholib.py b/Lib/test/test_ctypes/test_macholib.py -similarity index 100% -rename from Lib/ctypes/test/test_macholib.py -rename to Lib/test/test_ctypes/test_macholib.py -diff --git a/Lib/ctypes/test/test_memfunctions.py b/Lib/test/test_ctypes/test_memfunctions.py -similarity index 98% -rename from Lib/ctypes/test/test_memfunctions.py -rename to Lib/test/test_ctypes/test_memfunctions.py -index e784b9a706..d5c9735211 100644 ---- a/Lib/ctypes/test/test_memfunctions.py -+++ b/Lib/test/test_ctypes/test_memfunctions.py -@@ -2,7 +2,7 @@ - from test import support - import unittest - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - - class MemFunctionsTest(unittest.TestCase): - @unittest.skip('test disabled') -diff --git a/Lib/ctypes/test/test_numbers.py b/Lib/test/test_ctypes/test_numbers.py -similarity index 100% -rename from Lib/ctypes/test/test_numbers.py -rename to Lib/test/test_ctypes/test_numbers.py -diff --git a/Lib/ctypes/test/test_objects.py b/Lib/test/test_ctypes/test_objects.py -similarity index 87% -rename from Lib/ctypes/test/test_objects.py -rename to Lib/test/test_ctypes/test_objects.py -index 19e3dc1f2d..44a3c61ad7 100644 ---- a/Lib/ctypes/test/test_objects.py -+++ b/Lib/test/test_ctypes/test_objects.py -@@ -42,7 +42,7 @@ - of 'x' ('_b_base_' is either None, or the root object owning the memory block): - - >>> print(x.array._b_base_) # doctest: +ELLIPSIS --<ctypes.test.test_objects.X object at 0x...> -+<test.test_ctypes.test_objects.X object at 0x...> - >>> - - >>> x.array[0] = b'spam spam spam' -@@ -56,12 +56,12 @@ - - import unittest, doctest - --import ctypes.test.test_objects -+import test.test_ctypes.test_objects - - class TestCase(unittest.TestCase): - def test(self): -- failures, tests = doctest.testmod(ctypes.test.test_objects) -+ failures, tests = doctest.testmod(test.test_ctypes.test_objects) - self.assertFalse(failures, 'doctests failed, see output above') - - if __name__ == '__main__': -- doctest.testmod(ctypes.test.test_objects) -+ doctest.testmod(test.test_ctypes.test_objects) -diff --git a/Lib/ctypes/test/test_parameters.py b/Lib/test/test_ctypes/test_parameters.py -similarity index 99% -rename from Lib/ctypes/test/test_parameters.py -rename to Lib/test/test_ctypes/test_parameters.py -index 38af7ac13d..2f755a6d09 100644 ---- a/Lib/ctypes/test/test_parameters.py -+++ b/Lib/test/test_ctypes/test_parameters.py -@@ -1,5 +1,5 @@ - import unittest --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - import test.support - - class SimpleTypesTestCase(unittest.TestCase): -diff --git a/Lib/ctypes/test/test_pep3118.py b/Lib/test/test_ctypes/test_pep3118.py -similarity index 100% -rename from Lib/ctypes/test/test_pep3118.py -rename to Lib/test/test_ctypes/test_pep3118.py -diff --git a/Lib/ctypes/test/test_pickling.py b/Lib/test/test_ctypes/test_pickling.py -similarity index 100% -rename from Lib/ctypes/test/test_pickling.py -rename to Lib/test/test_ctypes/test_pickling.py -diff --git a/Lib/ctypes/test/test_pointers.py b/Lib/test/test_ctypes/test_pointers.py -similarity index 100% -rename from Lib/ctypes/test/test_pointers.py -rename to Lib/test/test_ctypes/test_pointers.py -diff --git a/Lib/ctypes/test/test_prototypes.py b/Lib/test/test_ctypes/test_prototypes.py -similarity index 99% -rename from Lib/ctypes/test/test_prototypes.py -rename to Lib/test/test_ctypes/test_prototypes.py -index cd0c649de3..bf27561487 100644 ---- a/Lib/ctypes/test/test_prototypes.py -+++ b/Lib/test/test_ctypes/test_prototypes.py -@@ -1,5 +1,5 @@ - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - import unittest - - # IMPORTANT INFO: -diff --git a/Lib/ctypes/test/test_python_api.py b/Lib/test/test_ctypes/test_python_api.py -similarity index 100% -rename from Lib/ctypes/test/test_python_api.py -rename to Lib/test/test_ctypes/test_python_api.py -diff --git a/Lib/ctypes/test/test_random_things.py b/Lib/test/test_ctypes/test_random_things.py -similarity index 100% -rename from Lib/ctypes/test/test_random_things.py -rename to Lib/test/test_ctypes/test_random_things.py -diff --git a/Lib/ctypes/test/test_refcounts.py b/Lib/test/test_ctypes/test_refcounts.py -similarity index 100% -rename from Lib/ctypes/test/test_refcounts.py -rename to Lib/test/test_ctypes/test_refcounts.py -diff --git a/Lib/ctypes/test/test_repr.py b/Lib/test/test_ctypes/test_repr.py -similarity index 100% -rename from Lib/ctypes/test/test_repr.py -rename to Lib/test/test_ctypes/test_repr.py -diff --git a/Lib/ctypes/test/test_returnfuncptrs.py b/Lib/test/test_ctypes/test_returnfuncptrs.py -similarity index 100% -rename from Lib/ctypes/test/test_returnfuncptrs.py -rename to Lib/test/test_ctypes/test_returnfuncptrs.py -diff --git a/Lib/ctypes/test/test_simplesubclasses.py b/Lib/test/test_ctypes/test_simplesubclasses.py -similarity index 100% -rename from Lib/ctypes/test/test_simplesubclasses.py -rename to Lib/test/test_ctypes/test_simplesubclasses.py -diff --git a/Lib/ctypes/test/test_sizes.py b/Lib/test/test_ctypes/test_sizes.py -similarity index 100% -rename from Lib/ctypes/test/test_sizes.py -rename to Lib/test/test_ctypes/test_sizes.py -diff --git a/Lib/ctypes/test/test_slicing.py b/Lib/test/test_ctypes/test_slicing.py -similarity index 99% -rename from Lib/ctypes/test/test_slicing.py -rename to Lib/test/test_ctypes/test_slicing.py -index a3932f1767..b3e68f9a82 100644 ---- a/Lib/ctypes/test/test_slicing.py -+++ b/Lib/test/test_ctypes/test_slicing.py -@@ -1,6 +1,6 @@ - import unittest - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - - import _ctypes_test - -diff --git a/Lib/ctypes/test/test_stringptr.py b/Lib/test/test_ctypes/test_stringptr.py -similarity index 100% -rename from Lib/ctypes/test/test_stringptr.py -rename to Lib/test/test_ctypes/test_stringptr.py -diff --git a/Lib/ctypes/test/test_strings.py b/Lib/test/test_ctypes/test_strings.py -similarity index 99% -rename from Lib/ctypes/test/test_strings.py -rename to Lib/test/test_ctypes/test_strings.py -index 12e208828a..a9003be3f5 100644 ---- a/Lib/ctypes/test/test_strings.py -+++ b/Lib/test/test_ctypes/test_strings.py -@@ -1,6 +1,6 @@ - import unittest - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - - class StringArrayTestCase(unittest.TestCase): - def test(self): -diff --git a/Lib/ctypes/test/test_struct_fields.py b/Lib/test/test_ctypes/test_struct_fields.py -similarity index 100% -rename from Lib/ctypes/test/test_struct_fields.py -rename to Lib/test/test_ctypes/test_struct_fields.py -diff --git a/Lib/ctypes/test/test_structures.py b/Lib/test/test_ctypes/test_structures.py -similarity index 99% -rename from Lib/ctypes/test/test_structures.py -rename to Lib/test/test_ctypes/test_structures.py -index 97ad2b8ed8..13c0470ba2 100644 ---- a/Lib/ctypes/test/test_structures.py -+++ b/Lib/test/test_ctypes/test_structures.py -@@ -2,7 +2,7 @@ - import sys - import unittest - from ctypes import * --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - from struct import calcsize - import _ctypes_test - from test import support -diff --git a/Lib/ctypes/test/test_unaligned_structures.py b/Lib/test/test_ctypes/test_unaligned_structures.py -similarity index 100% -rename from Lib/ctypes/test/test_unaligned_structures.py -rename to Lib/test/test_ctypes/test_unaligned_structures.py -diff --git a/Lib/ctypes/test/test_unicode.py b/Lib/test/test_ctypes/test_unicode.py -similarity index 97% -rename from Lib/ctypes/test/test_unicode.py -rename to Lib/test/test_ctypes/test_unicode.py -index 60c75424b7..319cb3b1dc 100644 ---- a/Lib/ctypes/test/test_unicode.py -+++ b/Lib/test/test_ctypes/test_unicode.py -@@ -1,6 +1,6 @@ - import unittest - import ctypes --from ctypes.test import need_symbol -+from test.test_ctypes import need_symbol - - import _ctypes_test - -diff --git a/Lib/ctypes/test/test_values.py b/Lib/test/test_ctypes/test_values.py -similarity index 100% -rename from Lib/ctypes/test/test_values.py -rename to Lib/test/test_ctypes/test_values.py -diff --git a/Lib/ctypes/test/test_varsize_struct.py b/Lib/test/test_ctypes/test_varsize_struct.py -similarity index 100% -rename from Lib/ctypes/test/test_varsize_struct.py -rename to Lib/test/test_ctypes/test_varsize_struct.py -diff --git a/Lib/ctypes/test/test_win32.py b/Lib/test/test_ctypes/test_win32.py -similarity index 100% -rename from Lib/ctypes/test/test_win32.py -rename to Lib/test/test_ctypes/test_win32.py -diff --git a/Lib/ctypes/test/test_wintypes.py b/Lib/test/test_ctypes/test_wintypes.py -similarity index 100% -rename from Lib/ctypes/test/test_wintypes.py -rename to Lib/test/test_ctypes/test_wintypes.py -diff --git a/Misc/NEWS.d/next/Tests/2022-06-20-23-04-52.gh-issue-93839.OE3Ybk.rst b/Misc/NEWS.d/next/Tests/2022-06-20-23-04-52.gh-issue-93839.OE3Ybk.rst -new file mode 100644 -index 0000000000..121b64b133 ---- /dev/null -+++ b/Misc/NEWS.d/next/Tests/2022-06-20-23-04-52.gh-issue-93839.OE3Ybk.rst -@@ -0,0 +1,2 @@ -+Move ``Lib/ctypes/test/`` to ``Lib/test/test_ctypes/``. Patch by Victor -+Stinner. -diff --git a/PCbuild/lib.pyproj b/PCbuild/lib.pyproj -index 43c570f1da..692b083349 100644 ---- a/PCbuild/lib.pyproj -+++ b/PCbuild/lib.pyproj -@@ -83,59 +83,6 @@ - <Compile Include="ctypes\macholib\dylib.py" /> - <Compile Include="ctypes\macholib\framework.py" /> - <Compile Include="ctypes\macholib\__init__.py" /> -- <Compile Include="ctypes\test\test_anon.py" /> -- <Compile Include="ctypes\test\test_arrays.py" /> -- <Compile Include="ctypes\test\test_array_in_pointer.py" /> -- <Compile Include="ctypes\test\test_as_parameter.py" /> -- <Compile Include="ctypes\test\test_bitfields.py" /> -- <Compile Include="ctypes\test\test_buffers.py" /> -- <Compile Include="ctypes\test\test_bytes.py" /> -- <Compile Include="ctypes\test\test_byteswap.py" /> -- <Compile Include="ctypes\test\test_callbacks.py" /> -- <Compile Include="ctypes\test\test_cast.py" /> -- <Compile Include="ctypes\test\test_cfuncs.py" /> -- <Compile Include="ctypes\test\test_checkretval.py" /> -- <Compile Include="ctypes\test\test_delattr.py" /> -- <Compile Include="ctypes\test\test_errno.py" /> -- <Compile Include="ctypes\test\test_find.py" /> -- <Compile Include="ctypes\test\test_frombuffer.py" /> -- <Compile Include="ctypes\test\test_funcptr.py" /> -- <Compile Include="ctypes\test\test_functions.py" /> -- <Compile Include="ctypes\test\test_incomplete.py" /> -- <Compile Include="ctypes\test\test_init.py" /> -- <Compile Include="ctypes\test\test_internals.py" /> -- <Compile Include="ctypes\test\test_keeprefs.py" /> -- <Compile Include="ctypes\test\test_libc.py" /> -- <Compile Include="ctypes\test\test_loading.py" /> -- <Compile Include="ctypes\test\test_macholib.py" /> -- <Compile Include="ctypes\test\test_memfunctions.py" /> -- <Compile Include="ctypes\test\test_numbers.py" /> -- <Compile Include="ctypes\test\test_objects.py" /> -- <Compile Include="ctypes\test\test_parameters.py" /> -- <Compile Include="ctypes\test\test_pep3118.py" /> -- <Compile Include="ctypes\test\test_pickling.py" /> -- <Compile Include="ctypes\test\test_pointers.py" /> -- <Compile Include="ctypes\test\test_prototypes.py" /> -- <Compile Include="ctypes\test\test_python_api.py" /> -- <Compile Include="ctypes\test\test_random_things.py" /> -- <Compile Include="ctypes\test\test_refcounts.py" /> -- <Compile Include="ctypes\test\test_repr.py" /> -- <Compile Include="ctypes\test\test_returnfuncptrs.py" /> -- <Compile Include="ctypes\test\test_simplesubclasses.py" /> -- <Compile Include="ctypes\test\test_sizes.py" /> -- <Compile Include="ctypes\test\test_slicing.py" /> -- <Compile Include="ctypes\test\test_stringptr.py" /> -- <Compile Include="ctypes\test\test_strings.py" /> -- <Compile Include="ctypes\test\test_structures.py" /> -- <Compile Include="ctypes\test\test_struct_fields.py" /> -- <Compile Include="ctypes\test\test_unaligned_structures.py" /> -- <Compile Include="ctypes\test\test_unicode.py" /> -- <Compile Include="ctypes\test\test_values.py" /> -- <Compile Include="ctypes\test\test_varsize_struct.py" /> -- <Compile Include="ctypes\test\test_win32.py" /> -- <Compile Include="ctypes\test\test_wintypes.py" /> -- <Compile Include="ctypes\test\__init__.py" /> -- <Compile Include="ctypes\test\__main__.py" /> - <Compile Include="ctypes\util.py" /> - <Compile Include="ctypes\wintypes.py" /> - <Compile Include="ctypes\_endian.py" /> -@@ -944,7 +891,59 @@ - <Compile Include="test\test_crashers.py" /> - <Compile Include="test\test_crypt.py" /> - <Compile Include="test\test_csv.py" /> -- <Compile Include="test\test_ctypes.py" /> -+ <Compile Include="test\test_ctypes\test_anon.py" /> -+ <Compile Include="test\test_ctypes\test_arrays.py" /> -+ <Compile Include="test\test_ctypes\test_array_in_pointer.py" /> -+ <Compile Include="test\test_ctypes\test_as_parameter.py" /> -+ <Compile Include="test\test_ctypes\test_bitfields.py" /> -+ <Compile Include="test\test_ctypes\test_buffers.py" /> -+ <Compile Include="test\test_ctypes\test_bytes.py" /> -+ <Compile Include="test\test_ctypes\test_byteswap.py" /> -+ <Compile Include="test\test_ctypes\test_callbacks.py" /> -+ <Compile Include="test\test_ctypes\test_cast.py" /> -+ <Compile Include="test\test_ctypes\test_cfuncs.py" /> -+ <Compile Include="test\test_ctypes\test_checkretval.py" /> -+ <Compile Include="test\test_ctypes\test_delattr.py" /> -+ <Compile Include="test\test_ctypes\test_errno.py" /> -+ <Compile Include="test\test_ctypes\test_find.py" /> -+ <Compile Include="test\test_ctypes\test_frombuffer.py" /> -+ <Compile Include="test\test_ctypes\test_funcptr.py" /> -+ <Compile Include="test\test_ctypes\test_functions.py" /> -+ <Compile Include="test\test_ctypes\test_incomplete.py" /> -+ <Compile Include="test\test_ctypes\test_init.py" /> -+ <Compile Include="test\test_ctypes\test_internals.py" /> -+ <Compile Include="test\test_ctypes\test_keeprefs.py" /> -+ <Compile Include="test\test_ctypes\test_libc.py" /> -+ <Compile Include="test\test_ctypes\test_loading.py" /> -+ <Compile Include="test\test_ctypes\test_macholib.py" /> -+ <Compile Include="test\test_ctypes\test_memfunctions.py" /> -+ <Compile Include="test\test_ctypes\test_numbers.py" /> -+ <Compile Include="test\test_ctypes\test_objects.py" /> -+ <Compile Include="test\test_ctypes\test_parameters.py" /> -+ <Compile Include="test\test_ctypes\test_pep3118.py" /> -+ <Compile Include="test\test_ctypes\test_pickling.py" /> -+ <Compile Include="test\test_ctypes\test_pointers.py" /> -+ <Compile Include="test\test_ctypes\test_prototypes.py" /> -+ <Compile Include="test\test_ctypes\test_python_api.py" /> -+ <Compile Include="test\test_ctypes\test_random_things.py" /> -+ <Compile Include="test\test_ctypes\test_refcounts.py" /> -+ <Compile Include="test\test_ctypes\test_repr.py" /> -+ <Compile Include="test\test_ctypes\test_returnfuncptrs.py" /> -+ <Compile Include="test\test_ctypes\test_simplesubclasses.py" /> -+ <Compile Include="test\test_ctypes\test_sizes.py" /> -+ <Compile Include="test\test_ctypes\test_slicing.py" /> -+ <Compile Include="test\test_ctypes\test_stringptr.py" /> -+ <Compile Include="test\test_ctypes\test_strings.py" /> -+ <Compile Include="test\test_ctypes\test_structures.py" /> -+ <Compile Include="test\test_ctypes\test_struct_fields.py" /> -+ <Compile Include="test\test_ctypes\test_unaligned_structures.py" /> -+ <Compile Include="test\test_ctypes\test_unicode.py" /> -+ <Compile Include="test\test_ctypes\test_values.py" /> -+ <Compile Include="test\test_ctypes\test_varsize_struct.py" /> -+ <Compile Include="test\test_ctypes\test_win32.py" /> -+ <Compile Include="test\test_ctypes\test_wintypes.py" /> -+ <Compile Include="test\test_ctypes\__init__.py" /> -+ <Compile Include="test\test_ctypes\__main__.py" /> - <Compile Include="test\test_curses.py" /> - <Compile Include="test\test_datetime.py" /> - <Compile Include="test\test_dbm.py" /> -@@ -1725,7 +1724,6 @@ - <Folder Include="concurrent\futures" /> - <Folder Include="ctypes" /> - <Folder Include="ctypes\macholib" /> -- <Folder Include="ctypes\test" /> - <Folder Include="curses" /> - <Folder Include="dbm" /> - <Folder Include="distutils" /> -@@ -1769,6 +1767,7 @@ - <Folder Include="test\subprocessdata" /> - <Folder Include="test\support" /> - <Folder Include="test\test_asyncio" /> -+ <Folder Include="test\test_ctypes" /> - <Folder Include="test\test_email" /> - <Folder Include="test\test_email\data" /> - <Folder Include="test\test_import" /> -diff --git a/Tools/wasm/wasm_assets.py b/Tools/wasm/wasm_assets.py -index b7e83517ca..d0a0570840 100755 ---- a/Tools/wasm/wasm_assets.py -+++ b/Tools/wasm/wasm_assets.py -@@ -111,7 +111,6 @@ - - # regression test sub directories - OMIT_SUBDIRS = ( -- "ctypes/test/", - "tkinter/test/", - "unittest/test/", - ) --- -2.29.2.windows.2 - diff --git a/packages/test/patches/0006-gh-93839-Move-Lib-unttest-test-to-Lib-test-test_unit.patch b/packages/test/patches/0006-gh-93839-Move-Lib-unttest-test-to-Lib-test-test_unit.patch deleted file mode 100644 --- a/packages/test/patches/0006-gh-93839-Move-Lib-unttest-test-to-Lib-test-test_unit.patch +++ /dev/null @@ -1,724 +0,0 @@ -From c735d545343c3ab002c62596b2fb2cfa4488b0af Mon Sep 17 00:00:00 2001 -From: Victor Stinner <[email protected]> -Date: Tue, 21 Jun 2022 10:27:59 +0200 -Subject: [PATCH 6/9] gh-93839: Move Lib/unttest/test/ to Lib/test/test_unittest/ - (#94043) - -* Move Lib/unittest/test/ to Lib/test/test_unittest/ -* Remove Lib/test/test_unittest.py -* Replace unittest.test with test.test_unittest -* Remove unittest.load_tests() -* Rewrite unittest __init__.py and __main__.py -* Update build system, CODEOWNERS, and wasm_assets.py ---- - .github/CODEOWNERS | 2 +- - Lib/test/test_unittest.py | 16 ----- - Lib/test/test_unittest/__init__.py | 6 ++ - Lib/test/test_unittest/__main__.py | 4 ++ - .../test_unittest}/_test_warnings.py | 0 - .../test => test/test_unittest}/dummy.py | 0 - .../test => test/test_unittest}/support.py | 0 - .../test_unittest}/test_assertions.py | 0 - .../test_unittest}/test_async_case.py | 0 - .../test => test/test_unittest}/test_break.py | 0 - .../test => test/test_unittest}/test_case.py | 2 +- - .../test_unittest}/test_discovery.py | 6 +- - .../test_unittest}/test_functiontestcase.py | 2 +- - .../test_unittest}/test_loader.py | 6 +- - .../test_unittest}/test_program.py | 16 ++--- - .../test_unittest}/test_result.py | 0 - .../test_unittest}/test_runner.py | 2 +- - .../test_unittest}/test_setups.py | 0 - .../test_unittest}/test_skipping.py | 2 +- - .../test => test/test_unittest}/test_suite.py | 2 +- - .../test_unittest}/testmock/__init__.py | 2 +- - .../test_unittest}/testmock/__main__.py | 2 +- - .../test_unittest}/testmock/support.py | 0 - .../test_unittest}/testmock/testasync.py | 0 - .../test_unittest}/testmock/testcallable.py | 2 +- - .../test_unittest}/testmock/testhelpers.py | 0 - .../testmock/testmagicmethods.py | 0 - .../test_unittest}/testmock/testmock.py | 2 +- - .../test_unittest}/testmock/testpatch.py | 22 +++---- - .../test_unittest}/testmock/testsealable.py | 0 - .../test_unittest}/testmock/testsentinel.py | 0 - .../test_unittest}/testmock/testwith.py | 2 +- - Lib/unittest/__init__.py | 10 ---- - Lib/unittest/test/__init__.py | 25 -------- - Lib/unittest/test/__main__.py | 18 ------ - Makefile.pre.in | 4 +- - PCbuild/lib.pyproj | 58 +++++++++---------- - Tools/wasm/wasm_assets.py | 1 - - 38 files changed, 77 insertions(+), 137 deletions(-) - delete mode 100644 Lib/test/test_unittest.py - create mode 100644 Lib/test/test_unittest/__init__.py - create mode 100644 Lib/test/test_unittest/__main__.py - rename Lib/{unittest/test => test/test_unittest}/_test_warnings.py (100%) - rename Lib/{unittest/test => test/test_unittest}/dummy.py (100%) - rename Lib/{unittest/test => test/test_unittest}/support.py (100%) - rename Lib/{unittest/test => test/test_unittest}/test_assertions.py (100%) - rename Lib/{unittest/test => test/test_unittest}/test_async_case.py (100%) - rename Lib/{unittest/test => test/test_unittest}/test_break.py (100%) - rename Lib/{unittest/test => test/test_unittest}/test_case.py (99%) - rename Lib/{unittest/test => test/test_unittest}/test_discovery.py (99%) - rename Lib/{unittest/test => test/test_unittest}/test_functiontestcase.py (99%) - rename Lib/{unittest/test => test/test_unittest}/test_loader.py (99%) - rename Lib/{unittest/test => test/test_unittest}/test_program.py (96%) - rename Lib/{unittest/test => test/test_unittest}/test_result.py (100%) - rename Lib/{unittest/test => test/test_unittest}/test_runner.py (99%) - rename Lib/{unittest/test => test/test_unittest}/test_setups.py (100%) - rename Lib/{unittest/test => test/test_unittest}/test_skipping.py (99%) - rename Lib/{unittest/test => test/test_unittest}/test_suite.py (99%) - rename Lib/{unittest/test => test/test_unittest}/testmock/__init__.py (86%) - rename Lib/{unittest/test => test/test_unittest}/testmock/__main__.py (86%) - rename Lib/{unittest/test => test/test_unittest}/testmock/support.py (100%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testasync.py (100%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testcallable.py (98%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testhelpers.py (100%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testmagicmethods.py (100%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testmock.py (99%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testpatch.py (98%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testsealable.py (100%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testsentinel.py (100%) - rename Lib/{unittest/test => test/test_unittest}/testmock/testwith.py (99%) - delete mode 100644 Lib/unittest/test/__init__.py - delete mode 100644 Lib/unittest/test/__main__.py - -diff --git a/Lib/test/test_unittest.py b/Lib/test/test_unittest.py -deleted file mode 100644 -index 1079c7df2e..0000000000 ---- a/Lib/test/test_unittest.py -+++ /dev/null -@@ -1,16 +0,0 @@ --import unittest.test -- --from test import support -- -- --def load_tests(*_): -- # used by unittest -- return unittest.test.suite() -- -- --def tearDownModule(): -- support.reap_children() -- -- --if __name__ == "__main__": -- unittest.main() -diff --git a/Lib/test/test_unittest/__init__.py b/Lib/test/test_unittest/__init__.py -new file mode 100644 -index 0000000000..bc502ef32d ---- /dev/null -+++ b/Lib/test/test_unittest/__init__.py -@@ -0,0 +1,6 @@ -+import os.path -+from test.support import load_package_tests -+ -+ -+def load_tests(*args): -+ return load_package_tests(os.path.dirname(__file__), *args) -diff --git a/Lib/test/test_unittest/__main__.py b/Lib/test/test_unittest/__main__.py -new file mode 100644 -index 0000000000..40a23a297e ---- /dev/null -+++ b/Lib/test/test_unittest/__main__.py -@@ -0,0 +1,4 @@ -+from . import load_tests -+import unittest -+ -+unittest.main() -diff --git a/Lib/unittest/test/_test_warnings.py b/Lib/test/test_unittest/_test_warnings.py -similarity index 100% -rename from Lib/unittest/test/_test_warnings.py -rename to Lib/test/test_unittest/_test_warnings.py -diff --git a/Lib/unittest/test/dummy.py b/Lib/test/test_unittest/dummy.py -similarity index 100% -rename from Lib/unittest/test/dummy.py -rename to Lib/test/test_unittest/dummy.py -diff --git a/Lib/unittest/test/support.py b/Lib/test/test_unittest/support.py -similarity index 100% -rename from Lib/unittest/test/support.py -rename to Lib/test/test_unittest/support.py -diff --git a/Lib/unittest/test/test_assertions.py b/Lib/test/test_unittest/test_assertions.py -similarity index 100% -rename from Lib/unittest/test/test_assertions.py -rename to Lib/test/test_unittest/test_assertions.py -diff --git a/Lib/unittest/test/test_async_case.py b/Lib/test/test_unittest/test_async_case.py -similarity index 100% -rename from Lib/unittest/test/test_async_case.py -rename to Lib/test/test_unittest/test_async_case.py -diff --git a/Lib/unittest/test/test_break.py b/Lib/test/test_unittest/test_break.py -similarity index 100% -rename from Lib/unittest/test/test_break.py -rename to Lib/test/test_unittest/test_break.py -diff --git a/Lib/unittest/test/test_case.py b/Lib/test/test_unittest/test_case.py -similarity index 99% -rename from Lib/unittest/test/test_case.py -rename to Lib/test/test_unittest/test_case.py -index 374a255255..e000fe4f07 100644 ---- a/Lib/unittest/test/test_case.py -+++ b/Lib/test/test_unittest/test_case.py -@@ -15,7 +15,7 @@ - - import unittest - --from unittest.test.support import ( -+from test.test_unittest.support import ( - TestEquality, TestHashing, LoggingResult, LegacyLoggingResult, - ResultWithNoStartTestRunStopTestRun - ) -diff --git a/Lib/unittest/test/test_discovery.py b/Lib/test/test_unittest/test_discovery.py -similarity index 99% -rename from Lib/unittest/test/test_discovery.py -rename to Lib/test/test_unittest/test_discovery.py -index 3b58786ec1..946fa1258e 100644 ---- a/Lib/unittest/test/test_discovery.py -+++ b/Lib/test/test_unittest/test_discovery.py -@@ -10,7 +10,7 @@ - - import unittest - import unittest.mock --import unittest.test -+import test.test_unittest - - - class TestableTestProgram(unittest.TestProgram): -@@ -789,7 +789,7 @@ def test_discovery_from_dotted_path(self): - loader = unittest.TestLoader() - - tests = [self] -- expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) -+ expectedPath = os.path.abspath(os.path.dirname(test.test_unittest.__file__)) - - self.wasRun = False - def _find_tests(start_dir, pattern): -@@ -797,7 +797,7 @@ def _find_tests(start_dir, pattern): - self.assertEqual(start_dir, expectedPath) - return tests - loader._find_tests = _find_tests -- suite = loader.discover('unittest.test') -+ suite = loader.discover('test.test_unittest') - self.assertTrue(self.wasRun) - self.assertEqual(suite._tests, tests) - -diff --git a/Lib/unittest/test/test_functiontestcase.py b/Lib/test/test_unittest/test_functiontestcase.py -similarity index 99% -rename from Lib/unittest/test/test_functiontestcase.py -rename to Lib/test/test_unittest/test_functiontestcase.py -index 4971729880..2ebed9564a 100644 ---- a/Lib/unittest/test/test_functiontestcase.py -+++ b/Lib/test/test_unittest/test_functiontestcase.py -@@ -1,6 +1,6 @@ - import unittest - --from unittest.test.support import LoggingResult -+from test.test_unittest.support import LoggingResult - - - class Test_FunctionTestCase(unittest.TestCase): -diff --git a/Lib/unittest/test/test_loader.py b/Lib/test/test_unittest/test_loader.py -similarity index 99% -rename from Lib/unittest/test/test_loader.py -rename to Lib/test/test_unittest/test_loader.py -index de2268cda9..c06ebb658d 100644 ---- a/Lib/unittest/test/test_loader.py -+++ b/Lib/test/test_unittest/test_loader.py -@@ -716,7 +716,7 @@ def test_loadTestsFromName__module_not_loaded(self): - # We're going to try to load this module as a side-effect, so it - # better not be loaded before we try. - # -- module_name = 'unittest.test.dummy' -+ module_name = 'test.test_unittest.dummy' - sys.modules.pop(module_name, None) - - loader = unittest.TestLoader() -@@ -844,7 +844,7 @@ def test_loadTestsFromNames__unknown_attr_name(self): - loader = unittest.TestLoader() - - suite = loader.loadTestsFromNames( -- ['unittest.loader.sdasfasfasdf', 'unittest.test.dummy']) -+ ['unittest.loader.sdasfasfasdf', 'test.test_unittest.dummy']) - error, test = self.check_deferred_error(loader, list(suite)[0]) - expected = "module 'unittest.loader' has no attribute 'sdasfasfasdf'" - self.assertIn( -@@ -1141,7 +1141,7 @@ def test_loadTestsFromNames__module_not_loaded(self): - # We're going to try to load this module as a side-effect, so it - # better not be loaded before we try. - # -- module_name = 'unittest.test.dummy' -+ module_name = 'test.test_unittest.dummy' - sys.modules.pop(module_name, None) - - loader = unittest.TestLoader() -diff --git a/Lib/unittest/test/test_program.py b/Lib/test/test_unittest/test_program.py -similarity index 96% -rename from Lib/unittest/test/test_program.py -rename to Lib/test/test_unittest/test_program.py -index 26a8550af8..169fc4ed94 100644 ---- a/Lib/unittest/test/test_program.py -+++ b/Lib/test/test_unittest/test_program.py -@@ -5,8 +5,8 @@ - import subprocess - from test import support - import unittest --import unittest.test --from unittest.test.test_result import BufferedWriter -+import test.test_unittest -+from test.test_unittest.test_result import BufferedWriter - - - class Test_TestProgram(unittest.TestCase): -@@ -15,7 +15,7 @@ def test_discovery_from_dotted_path(self): - loader = unittest.TestLoader() - - tests = [self] -- expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) -+ expectedPath = os.path.abspath(os.path.dirname(test.test_unittest.__file__)) - - self.wasRun = False - def _find_tests(start_dir, pattern): -@@ -23,7 +23,7 @@ def _find_tests(start_dir, pattern): - self.assertEqual(start_dir, expectedPath) - return tests - loader._find_tests = _find_tests -- suite = loader.discover('unittest.test') -+ suite = loader.discover('test.test_unittest') - self.assertTrue(self.wasRun) - self.assertEqual(suite._tests, tests) - -@@ -93,10 +93,10 @@ def run(self, test): - sys.argv = ['faketest'] - runner = FakeRunner() - program = unittest.TestProgram(testRunner=runner, exit=False, -- defaultTest='unittest.test', -+ defaultTest='test.test_unittest', - testLoader=self.FooBarLoader()) - sys.argv = old_argv -- self.assertEqual(('unittest.test',), program.testNames) -+ self.assertEqual(('test.test_unittest',), program.testNames) - - def test_defaultTest_with_iterable(self): - class FakeRunner(object): -@@ -109,10 +109,10 @@ def run(self, test): - runner = FakeRunner() - program = unittest.TestProgram( - testRunner=runner, exit=False, -- defaultTest=['unittest.test', 'unittest.test2'], -+ defaultTest=['test.test_unittest', 'test.test_unittest2'], - testLoader=self.FooBarLoader()) - sys.argv = old_argv -- self.assertEqual(['unittest.test', 'unittest.test2'], -+ self.assertEqual(['test.test_unittest', 'test.test_unittest2'], - program.testNames) - - def test_NonExit(self): -diff --git a/Lib/unittest/test/test_result.py b/Lib/test/test_unittest/test_result.py -similarity index 100% -rename from Lib/unittest/test/test_result.py -rename to Lib/test/test_unittest/test_result.py -diff --git a/Lib/unittest/test/test_runner.py b/Lib/test/test_unittest/test_runner.py -similarity index 99% -rename from Lib/unittest/test/test_runner.py -rename to Lib/test/test_unittest/test_runner.py -index d3488b40e8..9e3a0a9ca0 100644 ---- a/Lib/unittest/test/test_runner.py -+++ b/Lib/test/test_unittest/test_runner.py -@@ -8,7 +8,7 @@ - import unittest - from unittest.case import _Outcome - --from unittest.test.support import (LoggingResult, -+from test.test_unittest.support import (LoggingResult, - ResultWithNoStartTestRunStopTestRun) - - -diff --git a/Lib/unittest/test/test_setups.py b/Lib/test/test_unittest/test_setups.py -similarity index 100% -rename from Lib/unittest/test/test_setups.py -rename to Lib/test/test_unittest/test_setups.py -diff --git a/Lib/unittest/test/test_skipping.py b/Lib/test/test_unittest/test_skipping.py -similarity index 99% -rename from Lib/unittest/test/test_skipping.py -rename to Lib/test/test_unittest/test_skipping.py -index 64ceeae37e..f146dcac18 100644 ---- a/Lib/unittest/test/test_skipping.py -+++ b/Lib/test/test_unittest/test_skipping.py -@@ -1,6 +1,6 @@ - import unittest - --from unittest.test.support import LoggingResult -+from test.test_unittest.support import LoggingResult - - - class Test_TestSkipping(unittest.TestCase): -diff --git a/Lib/unittest/test/test_suite.py b/Lib/test/test_unittest/test_suite.py -similarity index 99% -rename from Lib/unittest/test/test_suite.py -rename to Lib/test/test_unittest/test_suite.py -index 0551a16996..ca52ee9d9c 100644 ---- a/Lib/unittest/test/test_suite.py -+++ b/Lib/test/test_unittest/test_suite.py -@@ -3,7 +3,7 @@ - import gc - import sys - import weakref --from unittest.test.support import LoggingResult, TestEquality -+from test.test_unittest.support import LoggingResult, TestEquality - - - ### Support code for Test_TestSuite -diff --git a/Lib/unittest/test/testmock/__init__.py b/Lib/test/test_unittest/testmock/__init__.py -similarity index 86% -rename from Lib/unittest/test/testmock/__init__.py -rename to Lib/test/test_unittest/testmock/__init__.py -index 87d7ae994d..6ee60b2376 100644 ---- a/Lib/unittest/test/testmock/__init__.py -+++ b/Lib/test/test_unittest/testmock/__init__.py -@@ -10,7 +10,7 @@ def load_tests(*args): - suite = unittest.TestSuite() - for fn in os.listdir(here): - if fn.startswith("test") and fn.endswith(".py"): -- modname = "unittest.test.testmock." + fn[:-3] -+ modname = "test.test_unittest.testmock." + fn[:-3] - __import__(modname) - module = sys.modules[modname] - suite.addTest(loader.loadTestsFromModule(module)) -diff --git a/Lib/unittest/test/testmock/__main__.py b/Lib/test/test_unittest/testmock/__main__.py -similarity index 86% -rename from Lib/unittest/test/testmock/__main__.py -rename to Lib/test/test_unittest/testmock/__main__.py -index 45c633a4ee..1e3068b0dd 100644 ---- a/Lib/unittest/test/testmock/__main__.py -+++ b/Lib/test/test_unittest/testmock/__main__.py -@@ -6,7 +6,7 @@ def load_tests(loader, standard_tests, pattern): - # top level directory cached on loader instance - this_dir = os.path.dirname(__file__) - pattern = pattern or "test*.py" -- # We are inside unittest.test.testmock, so the top-level is three notches up -+ # We are inside test.test_unittest.testmock, so the top-level is three notches up - top_level_dir = os.path.dirname(os.path.dirname(os.path.dirname(this_dir))) - package_tests = loader.discover(start_dir=this_dir, pattern=pattern, - top_level_dir=top_level_dir) -diff --git a/Lib/unittest/test/testmock/support.py b/Lib/test/test_unittest/testmock/support.py -similarity index 100% -rename from Lib/unittest/test/testmock/support.py -rename to Lib/test/test_unittest/testmock/support.py -diff --git a/Lib/unittest/test/testmock/testasync.py b/Lib/test/test_unittest/testmock/testasync.py -similarity index 100% -rename from Lib/unittest/test/testmock/testasync.py -rename to Lib/test/test_unittest/testmock/testasync.py -diff --git a/Lib/unittest/test/testmock/testcallable.py b/Lib/test/test_unittest/testmock/testcallable.py -similarity index 98% -rename from Lib/unittest/test/testmock/testcallable.py -rename to Lib/test/test_unittest/testmock/testcallable.py -index 5eadc00704..ca88511f63 100644 ---- a/Lib/unittest/test/testmock/testcallable.py -+++ b/Lib/test/test_unittest/testmock/testcallable.py -@@ -3,7 +3,7 @@ - # http://www.voidspace.org.uk/python/mock/ - - import unittest --from unittest.test.testmock.support import is_instance, X, SomeClass -+from test.test_unittest.testmock.support import is_instance, X, SomeClass - - from unittest.mock import ( - Mock, MagicMock, NonCallableMagicMock, -diff --git a/Lib/unittest/test/testmock/testhelpers.py b/Lib/test/test_unittest/testmock/testhelpers.py -similarity index 100% -rename from Lib/unittest/test/testmock/testhelpers.py -rename to Lib/test/test_unittest/testmock/testhelpers.py -diff --git a/Lib/unittest/test/testmock/testmagicmethods.py b/Lib/test/test_unittest/testmock/testmagicmethods.py -similarity index 100% -rename from Lib/unittest/test/testmock/testmagicmethods.py -rename to Lib/test/test_unittest/testmock/testmagicmethods.py -diff --git a/Lib/unittest/test/testmock/testmock.py b/Lib/test/test_unittest/testmock/testmock.py -similarity index 99% -rename from Lib/unittest/test/testmock/testmock.py -rename to Lib/test/test_unittest/testmock/testmock.py -index c99098dc4e..8a92490137 100644 ---- a/Lib/unittest/test/testmock/testmock.py -+++ b/Lib/test/test_unittest/testmock/testmock.py -@@ -5,7 +5,7 @@ - - from test.support import ALWAYS_EQ - import unittest --from unittest.test.testmock.support import is_instance -+from test.test_unittest.testmock.support import is_instance - from unittest import mock - from unittest.mock import ( - call, DEFAULT, patch, sentinel, -diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/test/test_unittest/testmock/testpatch.py -similarity index 98% -rename from Lib/unittest/test/testmock/testpatch.py -rename to Lib/test/test_unittest/testmock/testpatch.py -index 8ab63a1317..93ec0ca4be 100644 ---- a/Lib/unittest/test/testmock/testpatch.py -+++ b/Lib/test/test_unittest/testmock/testpatch.py -@@ -7,8 +7,8 @@ - from collections import OrderedDict - - import unittest --from unittest.test.testmock import support --from unittest.test.testmock.support import SomeClass, is_instance -+from test.test_unittest.testmock import support -+from test.test_unittest.testmock.support import SomeClass, is_instance - - from test.test_importlib.util import uncache - from unittest.mock import ( -@@ -669,7 +669,7 @@ def test_patch_dict_decorator_resolution(self): - # the new dictionary during function call - original = support.target.copy() - -- @patch.dict('unittest.test.testmock.support.target', {'bar': 'BAR'}) -+ @patch.dict('test.test_unittest.testmock.support.target', {'bar': 'BAR'}) - def test(): - self.assertEqual(support.target, {'foo': 'BAZ', 'bar': 'BAR'}) - -@@ -1614,7 +1614,7 @@ def test_patch_with_spec_mock_repr(self): - - - def test_patch_nested_autospec_repr(self): -- with patch('unittest.test.testmock.support', autospec=True) as m: -+ with patch('test.test_unittest.testmock.support', autospec=True) as m: - self.assertIn(" name='support.SomeClass.wibble()'", - repr(m.SomeClass.wibble())) - self.assertIn(" name='support.SomeClass().wibble()'", -@@ -1882,7 +1882,7 @@ def foo(x=0): - - with patch.object(foo, '__module__', "testpatch2"): - self.assertEqual(foo.__module__, "testpatch2") -- self.assertEqual(foo.__module__, 'unittest.test.testmock.testpatch') -+ self.assertEqual(foo.__module__, 'test.test_unittest.testmock.testpatch') - - with patch.object(foo, '__annotations__', dict([('s', 1, )])): - self.assertEqual(foo.__annotations__, dict([('s', 1, )])) -@@ -1917,16 +1917,16 @@ def test_dotted_but_module_not_loaded(self): - # This exercises the AttributeError branch of _dot_lookup. - - # make sure it's there -- import unittest.test.testmock.support -+ import test.test_unittest.testmock.support - # now make sure it's not: - with patch.dict('sys.modules'): -- del sys.modules['unittest.test.testmock.support'] -- del sys.modules['unittest.test.testmock'] -- del sys.modules['unittest.test'] -+ del sys.modules['test.test_unittest.testmock.support'] -+ del sys.modules['test.test_unittest.testmock'] -+ del sys.modules['test.test_unittest'] - del sys.modules['unittest'] - - # now make sure we can patch based on a dotted path: -- @patch('unittest.test.testmock.support.X') -+ @patch('test.test_unittest.testmock.support.X') - def test(mock): - pass - test() -@@ -1943,7 +1943,7 @@ class Foo: - - - def test_cant_set_kwargs_when_passing_a_mock(self): -- @patch('unittest.test.testmock.support.X', new=object(), x=1) -+ @patch('test.test_unittest.testmock.support.X', new=object(), x=1) - def test(): pass - with self.assertRaises(TypeError): - test() -diff --git a/Lib/unittest/test/testmock/testsealable.py b/Lib/test/test_unittest/testmock/testsealable.py -similarity index 100% -rename from Lib/unittest/test/testmock/testsealable.py -rename to Lib/test/test_unittest/testmock/testsealable.py -diff --git a/Lib/unittest/test/testmock/testsentinel.py b/Lib/test/test_unittest/testmock/testsentinel.py -similarity index 100% -rename from Lib/unittest/test/testmock/testsentinel.py -rename to Lib/test/test_unittest/testmock/testsentinel.py -diff --git a/Lib/unittest/test/testmock/testwith.py b/Lib/test/test_unittest/testmock/testwith.py -similarity index 99% -rename from Lib/unittest/test/testmock/testwith.py -rename to Lib/test/test_unittest/testmock/testwith.py -index c74d49a63c..8dc8eb1137 100644 ---- a/Lib/unittest/test/testmock/testwith.py -+++ b/Lib/test/test_unittest/testmock/testwith.py -@@ -1,7 +1,7 @@ - import unittest - from warnings import catch_warnings - --from unittest.test.testmock.support import is_instance -+from test.test_unittest.testmock.support import is_instance - from unittest.mock import MagicMock, Mock, patch, sentinel, mock_open, call - - -diff --git a/Lib/unittest/__init__.py b/Lib/unittest/__init__.py -index 005d23f6d0..b8de8c95d6 100644 ---- a/Lib/unittest/__init__.py -+++ b/Lib/unittest/__init__.py -@@ -73,16 +73,6 @@ def testMultiply(self): - _TextTestResult = TextTestResult - - --# There are no tests here, so don't try to run anything discovered from --# introspecting the symbols (e.g. FunctionTestCase). Instead, all our --# tests come from within unittest.test. --def load_tests(loader, tests, pattern): -- import os.path -- # top level directory cached on loader instance -- this_dir = os.path.dirname(__file__) -- return loader.discover(start_dir=this_dir, pattern=pattern) -- -- - # Lazy import of IsolatedAsyncioTestCase from .async_case - # It imports asyncio, which is relatively heavy, but most tests - # do not need it. -diff --git a/Lib/unittest/test/__init__.py b/Lib/unittest/test/__init__.py -deleted file mode 100644 -index 143f4ab5a3..0000000000 ---- a/Lib/unittest/test/__init__.py -+++ /dev/null -@@ -1,25 +0,0 @@ --import os --import sys --import unittest -- -- --here = os.path.dirname(__file__) --loader = unittest.defaultTestLoader -- --def suite(): -- suite = unittest.TestSuite() -- for fn in os.listdir(here): -- if fn.startswith("test") and fn.endswith(".py"): -- modname = "unittest.test." + fn[:-3] -- try: -- __import__(modname) -- except unittest.SkipTest: -- continue -- module = sys.modules[modname] -- suite.addTest(loader.loadTestsFromModule(module)) -- suite.addTest(loader.loadTestsFromName('unittest.test.testmock')) -- return suite -- -- --if __name__ == "__main__": -- unittest.main(defaultTest="suite") -diff --git a/Lib/unittest/test/__main__.py b/Lib/unittest/test/__main__.py -deleted file mode 100644 -index 44d0591e84..0000000000 ---- a/Lib/unittest/test/__main__.py -+++ /dev/null -@@ -1,18 +0,0 @@ --import os --import unittest -- -- --def load_tests(loader, standard_tests, pattern): -- # top level directory cached on loader instance -- this_dir = os.path.dirname(__file__) -- pattern = pattern or "test_*.py" -- # We are inside unittest.test, so the top-level is two notches up -- top_level_dir = os.path.dirname(os.path.dirname(this_dir)) -- package_tests = loader.discover(start_dir=this_dir, pattern=pattern, -- top_level_dir=top_level_dir) -- standard_tests.addTests(package_tests) -- return standard_tests -- -- --if __name__ == '__main__': -- unittest.main() -diff --git a/PCbuild/lib.pyproj b/PCbuild/lib.pyproj -index 692b083349..f3f44d1d8f 100644 ---- a/PCbuild/lib.pyproj -+++ b/PCbuild/lib.pyproj -@@ -1491,33 +1491,33 @@ - <Compile Include="unittest\runner.py" /> - <Compile Include="unittest\signals.py" /> - <Compile Include="unittest\suite.py" /> -- <Compile Include="unittest\test\dummy.py" /> -- <Compile Include="unittest\test\support.py" /> -- <Compile Include="unittest\test\testmock\support.py" /> -- <Compile Include="unittest\test\testmock\testcallable.py" /> -- <Compile Include="unittest\test\testmock\testhelpers.py" /> -- <Compile Include="unittest\test\testmock\testmagicmethods.py" /> -- <Compile Include="unittest\test\testmock\testmock.py" /> -- <Compile Include="unittest\test\testmock\testpatch.py" /> -- <Compile Include="unittest\test\testmock\testsentinel.py" /> -- <Compile Include="unittest\test\testmock\testwith.py" /> -- <Compile Include="unittest\test\testmock\__init__.py" /> -- <Compile Include="unittest\test\testmock\__main__.py" /> -- <Compile Include="unittest\test\test_assertions.py" /> -- <Compile Include="unittest\test\test_break.py" /> -- <Compile Include="unittest\test\test_case.py" /> -- <Compile Include="unittest\test\test_discovery.py" /> -- <Compile Include="unittest\test\test_functiontestcase.py" /> -- <Compile Include="unittest\test\test_loader.py" /> -- <Compile Include="unittest\test\test_program.py" /> -- <Compile Include="unittest\test\test_result.py" /> -- <Compile Include="unittest\test\test_runner.py" /> -- <Compile Include="unittest\test\test_setups.py" /> -- <Compile Include="unittest\test\test_skipping.py" /> -- <Compile Include="unittest\test\test_suite.py" /> -- <Compile Include="unittest\test\_test_warnings.py" /> -- <Compile Include="unittest\test\__init__.py" /> -- <Compile Include="unittest\test\__main__.py" /> -+ <Compile Include="test\test_unittest\dummy.py" /> -+ <Compile Include="test\test_unittest\support.py" /> -+ <Compile Include="test\test_unittest\testmock\support.py" /> -+ <Compile Include="test\test_unittest\testmock\testcallable.py" /> -+ <Compile Include="test\test_unittest\testmock\testhelpers.py" /> -+ <Compile Include="test\test_unittest\testmock\testmagicmethods.py" /> -+ <Compile Include="test\test_unittest\testmock\testmock.py" /> -+ <Compile Include="test\test_unittest\testmock\testpatch.py" /> -+ <Compile Include="test\test_unittest\testmock\testsentinel.py" /> -+ <Compile Include="test\test_unittest\testmock\testwith.py" /> -+ <Compile Include="test\test_unittest\testmock\__init__.py" /> -+ <Compile Include="test\test_unittest\testmock\__main__.py" /> -+ <Compile Include="test\test_unittest\test_assertions.py" /> -+ <Compile Include="test\test_unittest\test_break.py" /> -+ <Compile Include="test\test_unittest\test_case.py" /> -+ <Compile Include="test\test_unittest\test_discovery.py" /> -+ <Compile Include="test\test_unittest\test_functiontestcase.py" /> -+ <Compile Include="test\test_unittest\test_loader.py" /> -+ <Compile Include="test\test_unittest\test_program.py" /> -+ <Compile Include="test\test_unittest\test_result.py" /> -+ <Compile Include="test\test_unittest\test_runner.py" /> -+ <Compile Include="test\test_unittest\test_setups.py" /> -+ <Compile Include="test\test_unittest\test_skipping.py" /> -+ <Compile Include="test\test_unittest\test_suite.py" /> -+ <Compile Include="test\test_unittest\_test_warnings.py" /> -+ <Compile Include="test\test_unittest\__init__.py" /> -+ <Compile Include="test\test_unittest\__main__.py" /> - <Compile Include="unittest\util.py" /> - <Compile Include="unittest\__init__.py" /> - <Compile Include="unittest\__main__.py" /> -@@ -1804,6 +1804,8 @@ - <Folder Include="test\test_json" /> - <Folder Include="test\test_peg_generator" /> - <Folder Include="test\test_tools" /> -+ <Folder Include="test\test_unittest" /> -+ <Folder Include="test\test_unittest\testmock" /> - <Folder Include="test\test_warnings" /> - <Folder Include="test\test_warnings\data" /> - <Folder Include="test\tracedmodules" /> -@@ -1813,8 +1815,6 @@ - <Folder Include="tkinter\test\test_ttk" /> - <Folder Include="turtledemo" /> - <Folder Include="unittest" /> -- <Folder Include="unittest\test" /> -- <Folder Include="unittest\test\testmock" /> - <Folder Include="urllib" /> - <Folder Include="venv" /> - <Folder Include="wsgiref" /> -diff --git a/Tools/wasm/wasm_assets.py b/Tools/wasm/wasm_assets.py -index d0a0570840..67afde60f0 100755 ---- a/Tools/wasm/wasm_assets.py -+++ b/Tools/wasm/wasm_assets.py -@@ -112,7 +112,6 @@ - # regression test sub directories - OMIT_SUBDIRS = ( - "tkinter/test/", -- "unittest/test/", - ) - - def get_builddir(args: argparse.Namespace) -> pathlib.Path: --- -2.29.2.windows.2 - diff --git a/packages/test/patches/0007-gh-93839-Use-load_package_tests-for-testmock-GH-9405.patch b/packages/test/patches/0007-gh-93839-Use-load_package_tests-for-testmock-GH-9405.patch deleted file mode 100644 --- a/packages/test/patches/0007-gh-93839-Use-load_package_tests-for-testmock-GH-9405.patch +++ /dev/null @@ -1,40 +0,0 @@ -From 50ebd72fb0e69c78f95cea3d4a47589beb91ac37 Mon Sep 17 00:00:00 2001 -From: Christian Heimes <[email protected]> -Date: Tue, 21 Jun 2022 14:51:39 +0200 -Subject: [PATCH 7/9] gh-93839: Use load_package_tests() for testmock (GH-94055) - -Fixes failing tests on WebAssembly platforms. - -Automerge-Triggered-By: GH:tiran ---- - Lib/test/test_unittest/testmock/__init__.py | 17 +++-------------- - 1 file changed, 3 insertions(+), 14 deletions(-) - -diff --git a/Lib/test/test_unittest/testmock/__init__.py b/Lib/test/test_unittest/testmock/__init__.py -index 6ee60b2376..bc502ef32d 100644 ---- a/Lib/test/test_unittest/testmock/__init__.py -+++ b/Lib/test/test_unittest/testmock/__init__.py -@@ -1,17 +1,6 @@ --import os --import sys --import unittest -+import os.path -+from test.support import load_package_tests - - --here = os.path.dirname(__file__) --loader = unittest.defaultTestLoader -- - def load_tests(*args): -- suite = unittest.TestSuite() -- for fn in os.listdir(here): -- if fn.startswith("test") and fn.endswith(".py"): -- modname = "test.test_unittest.testmock." + fn[:-3] -- __import__(modname) -- module = sys.modules[modname] -- suite.addTest(loader.loadTestsFromModule(module)) -- return suite -+ return load_package_tests(os.path.dirname(__file__), *args) --- -2.29.2.windows.2 - diff --git a/packages/test/patches/0008-Move-test-directories.patch b/packages/test/patches/0008-Move-test-directories.patch deleted file mode 100644 --- a/packages/test/patches/0008-Move-test-directories.patch +++ /dev/null @@ -1,36 +0,0 @@ -From 4c71c808cc65ed6003b1e29d583c71586ebb36e1 Mon Sep 17 00:00:00 2001 -From: ryanking13 <[email protected]> -Date: Wed, 25 Jan 2023 15:54:16 +0900 -Subject: [PATCH 8/9] Move test directories - ---- - Makefile.pre.in | 6 +++--- - 1 file changed, 3 insertions(+), 3 deletions(-) - -diff --git a/Makefile.pre.in b/Makefile.pre.in -index b356f6293e..68c55a356a 100644 ---- a/Makefile.pre.in -+++ b/Makefile.pre.in -@@ -1932,8 +1932,7 @@ LIBSUBDIRS= asyncio \ - xmlrpc \ - zoneinfo \ - __phello__ --TESTSUBDIRS= ctypes/test \ -- distutils/tests \ -+TESTSUBDIRS= distutils/tests \ - idlelib/idle_test \ - lib2to3/tests \ - lib2to3/tests/data \ -@@ -2009,7 +2008,8 @@ TESTSUBDIRS= ctypes/test \ - test/ziptestdata \ - tkinter/test tkinter/test/test_tkinter \ - tkinter/test/test_ttk \ -- unittest/test unittest/test/testmock -+ test/test_ctypes \ -+ test/test_unittest test/test_unittest/testmock - - TEST_MODULES=@TEST_MODULES@ - libinstall: all $(srcdir)/Modules/xxmodule.c --- -2.29.2.windows.2 - diff --git a/packages/wrapt/test_wrapt.py b/packages/wrapt/test_wrapt.py --- a/packages/wrapt/test_wrapt.py +++ b/packages/wrapt/test_wrapt.py @@ -79,5 +79,5 @@ def _function(*args, **kwargs): self.assertEqual(result, (_args, _kwargs)) # Run tests - with unittest.TestCase().assertRaisesRegex(SystemExit, "False"): + with unittest.TestCase().assertRaisesRegex(SystemExit, "5"): unittest.main() diff --git a/pyodide-build/pyodide_build/tests/_test_recipes/joblib/meta.yaml b/pyodide-build/pyodide_build/tests/_test_recipes/joblib/meta.yaml --- a/pyodide-build/pyodide_build/tests/_test_recipes/joblib/meta.yaml +++ b/pyodide-build/pyodide_build/tests/_test_recipes/joblib/meta.yaml @@ -2,10 +2,6 @@ package: name: joblib version: 1.1.0 -requirements: - run: - - distutils - source: url: https://files.pythonhosted.org/packages/92/b9/9e3616e7e00c8165fb25175c53444533bdde05f3e974d45d9fcbbe451ee6/joblib-1.1.0.tar.gz sha256: 4158fcecd13733f8be669be0683b96ebdbbd38d23559f54dca7205aea1bf1e35 diff --git a/pyodide-build/pyodide_build/tests/fixture.py b/pyodide-build/pyodide_build/tests/fixture.py --- a/pyodide-build/pyodide_build/tests/fixture.py +++ b/pyodide-build/pyodide_build/tests/fixture.py @@ -18,7 +18,6 @@ def temp_python_lib(tmp_path_factory): (path / "test").mkdir() (path / "test" / "test_blah.py").touch() - (path / "distutils").mkdir() (path / "turtle.py").touch() (path / "module1.py").touch() diff --git a/pyodide-build/pyodide_build/tests/test_pyzip.py b/pyodide-build/pyodide_build/tests/test_pyzip.py --- a/pyodide-build/pyodide_build/tests/test_pyzip.py +++ b/pyodide-build/pyodide_build/tests/test_pyzip.py @@ -8,7 +8,7 @@ def test_defaultfilterfunc(temp_python_lib): filterfunc = default_filterfunc(temp_python_lib, verbose=True) - ignored = ["test", "distutils", "turtle.py"] + ignored = ["test", "turtle.py"] assert set(ignored) == filterfunc(str(temp_python_lib), ignored) assert set() == filterfunc(str(temp_python_lib), ["hello.py", "world.py"]) diff --git a/src/tests/python_tests.yaml b/src/tests/python_tests.yaml --- a/src/tests/python_tests.yaml +++ b/src/tests/python_tests.yaml @@ -28,7 +28,7 @@ # - multiprocessing: Fails due to no multiprocessing implementation. # - fs: Fails due to virtual filesystem issues. # - nonsense: This functionality doesn't make sense in this context. Includes -# things like `pip`, `distutils` +# things like `pip` # - crash: The Python interpreter just stopped without a traceback. Will require # further investigation. This usually seems to be caused by calling into a # system function that doesn't behave as one would expect. @@ -36,15 +36,18 @@ # - crash-firefox: Same as crash but only affecting Firefox - leakers.test_ctypes - leakers.test_selftype +- regrtestdata.import_from_tests.test_regrtest_a: + xfail: didn't correctly embed test data +- regrtestdata.import_from_tests.test_regrtest_c: + xfail: didn't correctly embed test data - test___all__: xfail: multiprocessing -- test___future__: - xfail: Dunno - test__locale: xfail: locale - test__opcode - test__osx_support: xfail: platform-specific +- test__xxinterpchannels - test__xxsubinterpreters: xfail: hits Py_FatalError("not the last thread") inside Py_EndInterpreter - test_abc @@ -55,20 +58,18 @@ - test_array - test_asdl_parser - test_ast: + xfail-safari: Stack overflow skip: - test_stdlib_validates # incompatible with zipimport - test_asyncgen: xfail: async -- test_asynchat: - xfail: async -- test_asyncio.test_asyncio_waitfor: - xfail: async - test_asyncio.test_base_events: xfail: async - test_asyncio.test_buffered_proto: xfail: async - test_asyncio.test_context: xfail: async +- test_asyncio.test_eager_task_factory - test_asyncio.test_events: xfail: async - test_asyncio.test_futures: @@ -106,13 +107,13 @@ xfail: async - test_asyncio.test_threads: xfail: async +- test_asyncio.test_timeouts - test_asyncio.test_transports - test_asyncio.test_unix_events: xfail: async +- test_asyncio.test_waitfor - test_asyncio.test_windows_events - test_asyncio.test_windows_utils -- test_asyncore: - xfail: async - test_atexit: skip: - test_general # fork @@ -159,15 +160,35 @@ - testThreading - test_c_locale_coercion - test_calendar -- test_call -- test_capi: - xfail: hangs +- test_call: + xfail: stack overflow +- test_capi.test_abstract +- test_capi.test_bytearray +- test_capi.test_bytes +- test_capi.test_codecs +- test_capi.test_complex +- test_capi.test_dict +- test_capi.test_eval_code_ex +- test_capi.test_exceptions +- test_capi.test_float +- test_capi.test_getargs +- test_capi.test_immortal +- test_capi.test_list +- test_capi.test_long +- test_capi.test_mem +- test_capi.test_misc: + skip: + - "*subinterpreter*" # Should we disable _xxsubinterpreters in Setup.local? +- test_capi.test_set +- test_capi.test_structmembers +- test_capi.test_sys +- test_capi.test_unicode +- test_capi.test_watchers - test_cgi: skip: - test_log # OSError: [Errno 70] Invalid seek - test_cgitb - test_charmapcodec -- test_check_c_globals - test_class - test_clinic - test_cmath @@ -198,8 +219,17 @@ - test_compile - test_compileall: xfail: multiprocessing +- test_compiler_assemble +- test_compiler_codegen - test_complex -- test_concurrent_futures +- test_concurrent_futures.test_as_completed +- test_concurrent_futures.test_deadlock +- test_concurrent_futures.test_future +- test_concurrent_futures.test_init +- test_concurrent_futures.test_process_pool +- test_concurrent_futures.test_shutdown +- test_concurrent_futures.test_thread_pool +- test_concurrent_futures.test_wait - test_configparser - test_contains - test_context: @@ -217,12 +247,60 @@ - test_crashers - test_crypt - test_csv -- test_ctypes: +- test_ctypes.test_anon +- test_ctypes.test_array_in_pointer +- test_ctypes.test_arrays +- test_ctypes.test_as_parameter +- test_ctypes.test_bitfields +- test_ctypes.test_buffers +- test_ctypes.test_bytes +- test_ctypes.test_byteswap +- test_ctypes.test_callbacks +- test_ctypes.test_cast +- test_ctypes.test_cfuncs +- test_ctypes.test_checkretval +- test_ctypes.test_delattr +- test_ctypes.test_errno +- test_ctypes.test_find +- test_ctypes.test_frombuffer +- test_ctypes.test_funcptr +- test_ctypes.test_functions +- test_ctypes.test_incomplete +- test_ctypes.test_init +- test_ctypes.test_internals +- test_ctypes.test_keeprefs +- test_ctypes.test_libc +- test_ctypes.test_loading +- test_ctypes.test_macholib +- test_ctypes.test_memfunctions +- test_ctypes.test_numbers +- test_ctypes.test_objects +- test_ctypes.test_parameters +- test_ctypes.test_pep3118 +- test_ctypes.test_pickling +- test_ctypes.test_pointers +- test_ctypes.test_prototypes +- test_ctypes.test_python_api +- test_ctypes.test_random_things +- test_ctypes.test_refcounts +- test_ctypes.test_repr +- test_ctypes.test_returnfuncptrs +- test_ctypes.test_simplesubclasses +- test_ctypes.test_sizes +- test_ctypes.test_slicing +- test_ctypes.test_stringptr +- test_ctypes.test_strings +- test_ctypes.test_struct_fields +- test_ctypes.test_structures: skip: - # See https://bugs.python.org/issue47208 - - test_callback_too_many_args + - test_array_in_struct_registers # needs https://github.com/libffi/libffi/pull/818 +- test_ctypes.test_unaligned_structures +- test_ctypes.test_unicode +- test_ctypes.test_values +- test_ctypes.test_varsize_struct +- test_ctypes.test_win32 +- test_ctypes.test_wintypes - test_curses -- test_dataclasses - test_datetime: xfail: strftime - test_dbm: @@ -238,7 +316,8 @@ - test_decorators - test_defaultdict - test_deque -- test_descr +- test_descr: + xfail: stack overflow - test_descrtut - test_devpoll - test_dict @@ -247,9 +326,6 @@ - test_dictviews - test_difflib - test_dis -- test_distutils: - # error while loading tests ModuleNotFoundError: No module named '_osx_support' - xfail: nonsense - test_doctest: xfail: subprocess - test_doctest2 @@ -333,19 +409,20 @@ - test_functools: skip: - "*threaded*" -- test_future: - xfail: Dunno -- test_future3: - xfail: Dunno -- test_future4: - xfail: Dunno -- test_future5: - xfail: Dunno +- test_future_stmt.test_future +- test_future_stmt.test_future_flags +- test_future_stmt.test_future_multiple_features +- test_future_stmt.test_future_multiple_imports +- test_future_stmt.test_future_single_import - test_gc: skip: - test_garbage_at_shutdown - test_trashcan_threads -- test_gdb +- test_gdb.test_backtrace +- test_gdb.test_cfunction +- test_gdb.test_cfunction_full +- test_gdb.test_misc +- test_gdb.test_pretty_print - test_generator_stop - test_generators - test_genericalias: @@ -357,8 +434,6 @@ - test_samestat_on_link - test_exists_fd - test_genexps -- test_getargs2: - xfail: Not sure - test_getopt - test_getpass - test_getpath @@ -394,17 +469,14 @@ - test_imaplib: xfail: socket - test_imghdr -- test_imp: - skip: - # incompatible with zipimport - - test_multiple_calls_to_get_data - - test_issue1267 - - test_load_from_source - test_importlib.builtin.test_finder - test_importlib.builtin.test_loader - test_importlib.extension.test_case_sensitivity -- test_importlib.extension.test_finder -- test_importlib.extension.test_loader +- test_importlib.extension.test_finder: + skip: + - "*FinderTests.test_module" +- test_importlib.extension.test_loader: + xfail: "TODO: why does it fail?" - test_importlib.extension.test_path_hook - test_importlib.frozen.test_finder - test_importlib.frozen.test_loader @@ -413,10 +485,20 @@ - test_importlib.import_.test_api - test_importlib.import_.test_caching - test_importlib.import_.test_fromlist +- test_importlib.import_.test_helpers - test_importlib.import_.test_meta_path - test_importlib.import_.test_packages - test_importlib.import_.test_path - test_importlib.import_.test_relative_imports +- test_importlib.resources.test_compatibilty_files +- test_importlib.resources.test_contents +- test_importlib.resources.test_custom +- test_importlib.resources.test_files +- test_importlib.resources.test_open +- test_importlib.resources.test_path +- test_importlib.resources.test_read +- test_importlib.resources.test_reader +- test_importlib.resources.test_resource - test_importlib.source.test_case_sensitivity - test_importlib.source.test_file_loader - test_importlib.source.test_finder @@ -427,21 +509,13 @@ skip: # incompatible with zipimport - test_reload_missing_loader -- test_importlib.test_compatibilty_files -- test_importlib.test_contents -- test_importlib.test_files - test_importlib.test_lazy - test_importlib.test_locks: xfail: threading - test_importlib.test_main - test_importlib.test_metadata_api - test_importlib.test_namespace_pkgs -- test_importlib.test_open -- test_importlib.test_path - test_importlib.test_pkg_import -- test_importlib.test_read -- test_importlib.test_reader -- test_importlib.test_resource - test_importlib.test_spec - test_importlib.test_threaded_import: xfail: threading @@ -449,9 +523,7 @@ - test_importlib.test_windows - test_importlib.test_zip - test_index -- test_inspect: - skip: - - test_nested_class_definition_inside_async_function +- test_inspect.test_inspect - test_int - test_int_literal - test_interpreters: @@ -491,8 +563,21 @@ - test_kqueue - test_largefile: xfail: segfault-outofmemory ("Array buffer allocation failed") -- test_lib2to3: - xfail: nonsense +- test_launcher +- test_lib2to3.test_all_fixers: + xfail: removed +- test_lib2to3.test_fixers: + xfail: removed +- test_lib2to3.test_main: + xfail: removed +- test_lib2to3.test_parser: + xfail: removed +- test_lib2to3.test_pytree: + xfail: removed +- test_lib2to3.test_refactor: + xfail: removed +- test_lib2to3.test_util: + xfail: removed - test_linecache: skip: # incompatible with zipimport @@ -517,6 +602,7 @@ - test_test # not sure why it fails... - test_marshal - test_math +- test_math_property - test_memoryio - test_memoryview - test_metaclass @@ -529,14 +615,24 @@ - test_basic - test_offset - test_resize_past_pos -- test_module -- test_modulefinder +- test_modulefinder: + xfail: takes a long time +- test_monitoring - test_msilib - test_multibytecodec -- test_multiprocessing_fork -- test_multiprocessing_forkserver +- test_multiprocessing_fork.test_manager +- test_multiprocessing_fork.test_misc +- test_multiprocessing_fork.test_processes +- test_multiprocessing_fork.test_threads +- test_multiprocessing_forkserver.test_manager +- test_multiprocessing_forkserver.test_misc +- test_multiprocessing_forkserver.test_processes +- test_multiprocessing_forkserver.test_threads - test_multiprocessing_main_handling -- test_multiprocessing_spawn +- test_multiprocessing_spawn.test_manager +- test_multiprocessing_spawn.test_misc +- test_multiprocessing_spawn.test_processes +- test_multiprocessing_spawn.test_threads - test_named_expressions - test_netrc - test_nis @@ -580,6 +676,9 @@ - test_peg_generator.test_first_sets - test_peg_generator.test_grammar_validator - test_peg_generator.test_pegen +- test_pep646_syntax +- test_perf_profiler +- test_perfmaps - test_pickle: xfail: dbm - test_picklebuffer @@ -591,7 +690,8 @@ - test_platform: skip: - test_architecture_via_symlink # fork -- test_plistlib +- test_plistlib: + xfail: stack overflow - test_poll: xfail: subprocess - test_popen: @@ -653,7 +753,7 @@ - test_runpy: skip: - test_pymain_run* # fork - # incompatible with zipimport + # incompatible with zipimport - test_run_module - test_run_module_alter_sys - test_run_module_in_namespace_package @@ -698,7 +798,6 @@ - test_site: xfail: "TypeError: unhashable type: 'pyodide.JsProxy'" - test_slice -- test_smtpd - test_smtplib: xfail: sockets - test_smtpnet @@ -713,6 +812,7 @@ - test_20731 - test_spwd - test_sqlite3.test_backup +- test_sqlite3.test_cli - test_sqlite3.test_dbapi - test_sqlite3.test_dump - test_sqlite3.test_factory @@ -738,15 +838,12 @@ - test_timezone - test_strtod - test_struct -- test_structmembers: - xfail: Not sure - test_structseq - test_subclassinit - test_subprocess: xfail: subprocess - test_sunau -- test_sundry: - xfail: Dunno +- test_sundry - test_super - test_support: xfail: about half the tests fork @@ -763,14 +860,12 @@ - test_syslog - test_tabnanny - test_tarfile: - xfail: Dunno skip: - - test_file_mode + - test_chains + - test_deep_symlink + - test_sly_relative* - test_extractall* - - test_link_size - - test_dereference_hardlink - - test_add_hardlink - - test_add_twice + - test_parent_symlink* - test_tcl - test_telnetlib: xfail: 7/19 fail with sockets @@ -780,6 +875,7 @@ - test_process_awareness # fork - test_truncate_with_size_parameter # setup failure FileNotFoundError: [Errno 44] No such file or directory - test_noinherit # self.assertEqual(os.get_inheritable(file.fd), False) ==> AssertionError: True != False +- test_termios - test_textwrap - test_thread: xfail: threading @@ -803,17 +899,23 @@ - test_timeit - test_timeout - test_tix -- test_tk +- test_tkinter.test_colorchooser +- test_tkinter.test_font +- test_tkinter.test_geometry_managers +- test_tkinter.test_images +- test_tkinter.test_loadtk +- test_tkinter.test_messagebox +- test_tkinter.test_misc +- test_tkinter.test_simpledialog +- test_tkinter.test_text +- test_tkinter.test_variables +- test_tkinter.test_widgets - test_tokenize -- test_tools.test_fixcid +- test_tomllib.test_data +- test_tomllib.test_error +- test_tomllib.test_misc - test_tools.test_freeze -- test_tools.test_gprof2html - test_tools.test_i18n -- test_tools.test_lll -- test_tools.test_md5sum -- test_tools.test_pathfix -- test_tools.test_pdeps -- test_tools.test_pindent - test_tools.test_reindent - test_tools.test_sundry - test_trace: @@ -821,15 +923,21 @@ - test_traceback: skip: - test_encoded_file # fork + - test_import_from* # tries to write to stdlib but it's in a zip - test_tracemalloc -- test_ttk_guionly +- test_ttk.test_extensions +- test_ttk.test_style +- test_ttk.test_widgets - test_ttk_textonly +- test_tty - test_tuple: xfail-chrome: times out - test_turtle +- test_type_aliases - test_type_annotations - test_type_cache - test_type_comments +- test_type_params - test_typechecks - test_types - test_typing: @@ -844,18 +952,19 @@ - test_unicode_file_functions - test_unicode_identifiers - test_unicodedata -- test_unittest: - xfail: Dunno - skip: - - "*async*" - - "*Interrupt*" - - "*Handler*" - # os.kill - - testTwoResults - - test_warnings - - testRemoveResult - # fork - - testSelectedTestNamesFunctionalTest +- test_unittest.test_assertions +- test_unittest.test_async_case +- test_unittest.test_break +- test_unittest.test_case +- test_unittest.test_discovery +- test_unittest.test_functiontestcase +- test_unittest.test_loader +- test_unittest.test_program +- test_unittest.test_result +- test_unittest.test_runner +- test_unittest.test_setups +- test_unittest.test_skipping +- test_unittest.test_suite - test_univnewlines - test_unpack - test_unpack_ex @@ -896,16 +1005,15 @@ - test_winreg - test_winsound - test_with +- test_wmi - test_wsgiref - test_xdrlib - test_xml_dom_minicompat - test_xml_etree: - xfail: Dunno skip: # stack overflow in v8 - - "test_recursive_repr" -- test_xml_etree_c: - xfail: Dunno + - test_recursive_repr +- test_xml_etree_c - test_xmlrpc: xfail: networking - test_xmlrpc_net @@ -913,12 +1021,17 @@ - test_xxtestfuzz - test_yield_from - test_zipapp -- test_zipfile: - xfail-chrome: times out +- test_zipfile._path.test_complexity +- test_zipfile._path.test_path +- test_zipfile.test_core: + xfail: Times out skip: - - test_many_opens # [Errno 54] Not a directory: '/proc/self/fd' + # NotADirectoryError: [Errno 54] Not a directory: '/proc/self/fd' + - test_many_opens + - test_zipfile64 - test_zipimport - test_zipimport_support - test_zlib - test_zoneinfo.test_zoneinfo +- test_zoneinfo.test_zoneinfo_property
Python 3.12 version ## 🚀 Feature <!-- A clear and concise description of the feature proposal --> Hi, I tried [REPL](https://pyodide.org/en/stable/console.html), maybe it uses the latest 0.25.0, and I noticed that the python is 3.11.3. Python 3.12 has released for a few months with a lot of new features. Since there is no issue track the progress. So, I created this one. ### Motivation <!-- Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too --> N.A. ### Pitch <!-- A clear and concise description of what you want to happen. --> N.A. ### Alternatives <!-- A clear and concise description of any alternative solutions or features you've considered, if any. --> N.A. ### Additional context <!-- Add any other context or screenshots about the feature request here. --> N.A.
Generally we aim to wait about six months after a new Python release comes out before updating, so since the Python versions are released in August, we usually do the update in February / March. This reduces the number of broken packages that we have to deal with in the update. Anyways it's about time to start working on this. @hoodmane Thanks, I see. 😃
2024-01-27T23:36:49
pyodide/pyodide
4,502
pyodide__pyodide-4502
[ "4498" ]
4a1c0ba55a0cf800906d4407bfc21be22eaa2a66
diff --git a/pyodide-build/pyodide_build/pypabuild.py b/pyodide-build/pyodide_build/pypabuild.py --- a/pyodide-build/pyodide_build/pypabuild.py +++ b/pyodide-build/pyodide_build/pypabuild.py @@ -40,6 +40,19 @@ "patchelf", ] +# corresponding env variables for symlinks +SYMLINK_ENV_VARS = { + "cc": "CC", + "c++": "CXX", + "ld": "LD", + "lld": "LLD", + "ar": "AR", + "gcc": "GCC", + "ranlib": "RANLIB", + "strip": "STRIP", + "gfortran": "FC", # https://mesonbuild.com/Reference-tables.html#compiler-and-linker-selection-variables +} + def _gen_runner( cross_build_env: Mapping[str, str], @@ -207,13 +220,8 @@ def make_command_wrapper_symlinks(symlink_dir: Path) -> dict[str, str]: symlink_path.unlink() symlink_path.symlink_to(pywasmcross_exe) - if symlink == "c++": - var = "CXX" - elif symlink == "gfortran": - var = "FC" # https://mesonbuild.com/Reference-tables.html#compiler-and-linker-selection-variables - else: - var = symlink.upper() - env[var] = str(symlink_path) + if symlink in SYMLINK_ENV_VARS: + env[SYMLINK_ENV_VARS[symlink]] = str(symlink_path) return env
diff --git a/pyodide-build/pyodide_build/tests/test_pypabuild.py b/pyodide-build/pyodide_build/tests/test_pypabuild.py --- a/pyodide-build/pyodide_build/tests/test_pypabuild.py +++ b/pyodide-build/pyodide_build/tests/test_pypabuild.py @@ -41,12 +41,13 @@ def test_make_command_wrapper_symlinks(tmp_path): assert not wrapper.is_symlink() assert wrapper.stat().st_mode & 0o755 == 0o755 - for _, path in env.items(): + for key, path in env.items(): symlink_path = symlink_dir / path assert symlink_path.exists() assert symlink_path.is_symlink() assert symlink_path.name in pywasmcross.SYMLINKS + assert key in pypabuild.SYMLINK_ENV_VARS.values() def test_get_build_env(tmp_path):
Numpy v1.26.4 build fails: Module "features" does not exist @ryanking13 @mattip @seberg v1.26.3 build succeeds Failure for v1.26.4: <details><summary>Details</summary> <p> ``` The Meson build system Version: 1.3.1 Source dir: /home/hood/Documents/programming/pyodide/packages/numpy/build/numpy-1.26.4 Build dir: /home/hood/Documents/programming/pyodide/packages/numpy/build/numpy-1.26.4/.mesonpy-c6ekdglk Build type: cross build Project name: NumPy Project version: 1.26.4 Cross compiler sanity tests disabled via the cross file. C compiler for the host machine: /tmp/tmpqfmd_k4r/cc (emscripten 3.1.52 "emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.52 (fa478400df3351f7153c0279bc638784d3d90334)") C linker for the host machine: /tmp/tmpqfmd_k4r/cc ld.wasm 18.0.0 C++ compiler for the host machine: /tmp/tmpqfmd_k4r/c++ (emscripten 3.1.52 "emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.52 (fa478400df3351f7153c0279bc638784d3d90334)") C++ linker for the host machine: /tmp/tmpqfmd_k4r/c++ ld.wasm 18.0.0 Cython compiler for the host machine: cython (cython 3.0.8) C compiler for the build machine: ccache cc (gcc 9.4.0 "cc (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0") C linker for the build machine: cc ld.bfd 2.34 C++ compiler for the build machine: ccache c++ (gcc 9.4.0 "c++ (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0") C++ linker for the build machine: c++ ld.bfd 2.34 Cython compiler for the build machine: cython (cython 3.0.8) Build machine cpu family: x86_64 Build machine cpu: x86_64 Host machine cpu family: wasm32 Host machine cpu: wasm Target machine cpu family: wasm32 Target machine cpu: wasm Program python3 found: YES (/tmp/build-env-mr2vjazb/bin/python) Found pkg-config: YES (/usr/bin/pkg-config) 0.29.1 Run-time dependency python found: YES 3.12 Has header "Python.h" with dependency python: YES Compiler for C supports arguments -fno-strict-aliasing: YES ../meson_cpu/x86/meson.build:2:15: ERROR: Module "features" does not exist ``` </p> </details>
Seems like the most likely culprit is: https://github.com/numpy/numpy/pull/25748 According to this issue, https://github.com/numpy/numpy/issues/24750, it seems like vendored meson is not picked up for some reason. I have a culprit. Let me check it out.
2024-02-09T06:10:06
pyodide/pyodide
4,548
pyodide__pyodide-4548
[ "4398" ]
482dc5098bfa81f9d286ecdfa4d77c8e761512d3
diff --git a/src/py/_pyodide/_core_docs.py b/src/py/_pyodide/_core_docs.py --- a/src/py/_pyodide/_core_docs.py +++ b/src/py/_pyodide/_core_docs.py @@ -1495,6 +1495,11 @@ def destroy_proxies(pyproxies: JsArray[Any], /) -> None: pass +def run_sync(x: Awaitable[T]) -> T: + """Hi!""" + raise NotImplementedError + + __name__ = _save_name del _save_name @@ -1519,6 +1524,7 @@ def destroy_proxies(pyproxies: JsArray[Any], /) -> None: "JsDomElement", "JsCallable", "JsTypedArray", + "run_sync", "create_once_callable", "create_proxy", "destroy_proxies", diff --git a/src/py/pyodide/ffi/__init__.py b/src/py/pyodide/ffi/__init__.py --- a/src/py/pyodide/ffi/__init__.py +++ b/src/py/pyodide/ffi/__init__.py @@ -20,6 +20,7 @@ # that would be difficult to maintain. for t in [ "JsException", + "run_sync", "create_once_callable", "create_proxy", "destroy_proxies", diff --git a/src/py/pyodide/webloop.py b/src/py/pyodide/webloop.py --- a/src/py/pyodide/webloop.py +++ b/src/py/pyodide/webloop.py @@ -167,26 +167,6 @@ def wrapper(fut: Future[T]) -> None: self.add_done_callback(wrapper) return result - def syncify(self): - """Block until the future is resolved. Only works if JS Promise - integration is enabled in the runtime and the current Python call stack - was entered via :js:func:`pyodide.runPythonAsync`, by calling an async - Python function, or via :js:func:`~PyCallable.callSyncifying`. - - - .. admonition:: Experimental - :class: warning - - This feature is not yet stable. - """ - from .ffi import create_proxy - - p = create_proxy(self) - try: - return p.syncify() # type:ignore[attr-defined] - finally: - p.destroy() - class PyodideTask(Task[T], PyodideFuture[T]): """Inherits from both :py:class:`~asyncio.Task` and
diff --git a/src/tests/test_stack_switching.py b/src/tests/test_stack_switching.py --- a/src/tests/test_stack_switching.py +++ b/src/tests/test_stack_switching.py @@ -6,15 +6,84 @@ @requires_jspi @run_in_pyodide -def test_syncify_create_task(selenium): - import asyncio +def test_syncify_awaitable_types_accept(selenium): + from asyncio import create_task, gather, sleep + + from js import sleep as js_sleep + from pyodide.code import run_js + from pyodide.ffi import run_sync async def test(): - await asyncio.sleep(0.1) + await sleep(0.1) return 7 - task = asyncio.create_task(test()) - assert task.syncify() == 7 # type:ignore[attr-defined] + assert run_sync(test()) == 7 + assert run_sync(create_task(test())) == 7 + run_sync(sleep(0.1)) + run_sync(js_sleep(100)) + res = run_sync(gather(test(), sleep(0.1), js_sleep(100), js_sleep(100))) + assert list(res) == [7, None, None, None] + p = run_js("[sleep(100)]")[0] + run_sync(p) + + +@requires_jspi +@run_in_pyodide +def test_syncify_awaitable_type_errors(selenium): + import pytest + + from pyodide.ffi import run_sync + + with pytest.raises(TypeError): + run_sync(1) # type:ignore[arg-type] + with pytest.raises(TypeError): + run_sync(None) # type:ignore[arg-type] + with pytest.raises(TypeError): + run_sync([1, 2, 3]) # type:ignore[arg-type] + with pytest.raises(TypeError): + run_sync(iter([1, 2, 3])) # type:ignore[arg-type] + + def f(): + yield 1 + yield 2 + yield 3 + + with pytest.raises(TypeError): + run_sync(f()) + + [email protected](reason="FIXME!") +def test_throw_from_switcher(selenium): + """ + Currently failing: + + Uncaught PythonError: Traceback (most recent call last): + File "<exec>", line 9, in b + Exception: hi + + The above exception was the direct cause of the following exception: + + SystemError: <function a at 0x9aaea0> returned a result with an exception set + """ + selenium.run_js( + """ + pyodide.runPython(` + async def a(): + pass + + def b(): + raise Exception("hi") + `); + + const a = pyodide.globals.get("a"); + const b = pyodide.globals.get("b"); + + await Promise.all([ + b.callSyncifying(), + a(), + ]); + """ + ) @pytest.mark.xfail_browsers(node="Scopes don't work as needed") @@ -31,7 +100,10 @@ def test_syncify_not_supported1(selenium_standalone_noload): "WebAssembly stack switching not supported in this JavaScript runtime" ); await assertThrows( - () => pyodide.runPython("from js import sleep; sleep().syncify()"), + () => pyodide.runPython(` + from pyodide.ffi import run_sync + run_sync(1) + `), "PythonError", "RuntimeError: WebAssembly stack switching not supported in this JavaScript runtime" ); @@ -56,7 +128,10 @@ def test_syncify_not_supported2(selenium_standalone_noload): "WebAssembly stack switching not supported in this JavaScript runtime" ); await assertThrows( - () => pyodide.runPython("from js import sleep; sleep().syncify()"), + () => pyodide.runPython(` + from pyodide.ffi import run_sync + run_sync(1) + `), "PythonError", "RuntimeError: WebAssembly stack switching not supported in this JavaScript runtime" ); @@ -68,6 +143,7 @@ def test_syncify_not_supported2(selenium_standalone_noload): @run_in_pyodide def test_syncify1(selenium): from pyodide.code import run_js + from pyodide.ffi import run_sync test = run_js( """ @@ -77,7 +153,7 @@ def test_syncify1(selenium): }) """ ) - assert test().syncify() == 7 + assert run_sync(test()) == 7 @requires_jspi @@ -87,12 +163,13 @@ def test_syncify2(selenium): import pytest + from pyodide.ffi import run_sync from pyodide_js import loadPackage with pytest.raises(ModuleNotFoundError): importlib.metadata.version("micropip") - loadPackage("micropip").syncify() + run_sync(loadPackage("micropip")) assert importlib.metadata.version("micropip") @@ -103,7 +180,7 @@ def test_syncify_error(selenium): import pytest from pyodide.code import run_js - from pyodide.ffi import JsException + from pyodide.ffi import JsException, run_sync asyncThrow = run_js( """ @@ -114,13 +191,14 @@ def test_syncify_error(selenium): ) with pytest.raises(JsException, match="hi"): - asyncThrow().syncify() + run_sync(asyncThrow()) @requires_jspi @run_in_pyodide def test_syncify_null(selenium): from pyodide.code import run_js + from pyodide.ffi import run_sync asyncNull = run_js( """ @@ -130,7 +208,7 @@ def test_syncify_null(selenium): }) """ ) - assert asyncNull().syncify() is None + assert run_sync(asyncNull()) is None @requires_jspi @@ -140,6 +218,7 @@ def test_syncify_no_suspender(selenium): await pyodide.loadPackage("pytest"); pyodide.runPython(` from pyodide.code import run_js + from pyodide.ffi import run_sync import pytest test = run_js( @@ -151,7 +230,7 @@ def test_syncify_no_suspender(selenium): ''' ) with pytest.raises(RuntimeError, match="No suspender"): - test().syncify() + run_sync(test()) del test `); """ @@ -163,6 +242,7 @@ def test_syncify_no_suspender(selenium): @run_in_pyodide(packages=["fpcast-test"]) def test_syncify_getset(selenium): from pyodide.code import run_js + from pyodide.ffi import run_sync test = run_js( """ @@ -175,7 +255,7 @@ def test_syncify_getset(selenium): x = [] def wrapper(): - x.append(test().syncify()) + x.append(run_sync(test())) import fpcast_test @@ -192,6 +272,7 @@ def wrapper(): @run_in_pyodide def test_syncify_ctypes(selenium): from pyodide.code import run_js + from pyodide.ffi import run_sync test = run_js( """ @@ -203,7 +284,7 @@ def test_syncify_ctypes(selenium): ) def wrapper(): - return test().syncify() + return run_sync(test()) from ctypes import py_object, pythonapi @@ -219,6 +300,7 @@ def test_cpp_exceptions_and_syncify(selenium): selenium.run_js( """ ptr = pyodide.runPython(` + from pyodide.ffi import run_sync from pyodide.code import run_js temp = run_js( ''' @@ -231,7 +313,7 @@ def test_cpp_exceptions_and_syncify(selenium): def f(): try: - return temp().syncify() + return run_sync(temp()) except Exception as e: print(e) return -1 @@ -261,11 +343,12 @@ def test_two_way_transfer(selenium): res = selenium.run_js( """ pyodide.runPython(` + from pyodide.ffi import run_sync l = [] def f(n, t): from js import sleep for i in range(5): - sleep(t).syncify() + run_sync(sleep(t)) l.append([n, i]) `); f = pyodide.globals.get("f"); @@ -295,16 +378,17 @@ def f(n, t): def test_sync_async_mix(selenium): res = selenium.run_js( """ - pyodide.runPython( - ` + pyodide.runPython(` + from pyodide.ffi import run_sync from js import sleep + l = []; async def a(t): await sleep(t) l.append(["a", t]) def b(t): - sleep(t).syncify() + run_sync(sleep(t)) l.append(["b", t]) `); const a = pyodide.globals.get("a"); @@ -357,18 +441,19 @@ def test_nested_syncify(selenium): pyodide.globals.set("getStuff", getStuff); pyodide.runPython(` + from pyodide.ffi import run_sync from js import sleep def g(): - sleep(25).syncify() - return f1().syncify() + run_sync(sleep(25)) + return run_sync(f1()) def g1(): - sleep(25).syncify() - return f2().syncify() + run_sync(sleep(25)) + return run_sync(f2()) def g2(): - sleep(25).syncify() - return getStuff().syncify() + run_sync(sleep(25)) + return run_sync(getStuff()) `); const l = pyodide.runPython("l = []; l") const g = pyodide.globals.get("g"); @@ -379,7 +464,7 @@ def g2(): p.push(pyodide.runPythonAsync(` from js import sleep for i in range(20): - sleep(9).syncify() + run_sync(sleep(9)) l.append(i) `)); await Promise.all(p); @@ -398,9 +483,10 @@ def g2(): @requires_jspi @run_in_pyodide async def test_promise_methods(selenium): - from asyncio import ensure_future, sleep + from asyncio import sleep from pyodide.code import run_js + from pyodide.ffi import run_sync async_pass = run_js( """ @@ -420,7 +506,7 @@ async def test_promise_methods(selenium): def f(*args): print("will sleep") - ensure_future(sleep(0.1)).syncify() # type:ignore[attr-defined] + run_sync(sleep(0.1)) print("have slept") await async_pass().then(f, f)
Using `asyncio.gather()` with `syncify()` raises error ## 🐛 Bug Using `asyncio.gather()` with `syncify()` isn't possible out of the box ### To Reproduce Open [browser with last version of Pyodide](https://pyodide.org/en/latest/console.html) and run the next code: ```python await pyodide.runPythonSyncifying(` import asyncio async def test(x): await asyncio.sleep(0.1 * x) return x + 1 res = asyncio.create_task(asyncio.gather(test(5), test(3), test(10))).syncify() print(*res) `); ``` This code will raise the error: ![image](https://github.com/pyodide/pyodide/assets/32600554/54d3e8bb-23c2-4ada-a051-c858d74e5471) The next workaround will work as expected: ```python await pyodide.runPythonSyncifying(` import asyncio async def test(x): await asyncio.sleep(0.1 * x) return x + 1 async def better_gather(*coros): return await asyncio.gather(*coros) res = asyncio.create_task(better_gather(test(5), test(3), test(10))).syncify() print(*res) `); ``` ### Expected behavior Expected the first code snippet to work :) ### Environment - Pyodide Version: 0.25.0 - Browser version: Version 120.0.6099.199 (Official Build) (64-bit) - Any other relevant information: - - Enabled JSPI flag in Chrome: chrome://flags/#enable-experimental-webassembly-stack-switching
2024-02-23T02:36:38
pyodide/pyodide
4,554
pyodide__pyodide-4554
[ "4541" ]
dc4cb1b78fcf93ea1b313b16b3af5b8e1dd53085
diff --git a/conftest.py b/conftest.py --- a/conftest.py +++ b/conftest.py @@ -54,6 +54,9 @@ only_node = pytest.mark.xfail_browsers( chrome="node only", firefox="node only", safari="node only" ) +only_chrome = pytest.mark.xfail_browsers( + node="chrome only", firefox="chrome only", safari="chrome only" +) def pytest_addoption(parser):
diff --git a/src/tests/test_filesystem.py b/src/tests/test_filesystem.py --- a/src/tests/test_filesystem.py +++ b/src/tests/test_filesystem.py @@ -4,6 +4,9 @@ """ import pytest +from pytest_pyodide import run_in_pyodide + +from conftest import only_chrome @pytest.mark.skip_refcount_check @@ -22,7 +25,7 @@ def test_idbfs_persist_code(selenium_standalone): f""" let mountDir = '{mount_dir}'; pyodide.FS.mkdir(mountDir); - pyodide.FS.mount(pyodide.FS.filesystems.{fstype}, {{root : "."}}, "{mount_dir}"); + pyodide.FS.mount(pyodide.FS.filesystems.{fstype}, {{root : "."}}, mountDir); """ ) # create file in mount @@ -109,9 +112,7 @@ def test_idbfs_persist_code(selenium_standalone): @pytest.mark.requires_dynamic_linking [email protected]_browsers( - node="Not available", firefox="Not available", safari="Not available" -) +@only_chrome def test_nativefs_dir(request, selenium_standalone): # Note: Using *real* native file system requires # user interaction so it is not available in headless mode. @@ -254,3 +255,78 @@ def test_nativefs_dir(request, selenium_standalone): pyodide.FS.unmount("/mnt/nativefs"); """ ) + + [email protected] +def browser(selenium): + return selenium.browser + + [email protected] +def runner(request): + return request.config.option.runner + + +@run_in_pyodide +def test_fs_dup(selenium, browser): + from os import close, dup + from pathlib import Path + + from pyodide.code import run_js + + if browser == "node": + fstype = "NODEFS" + else: + fstype = "IDBFS" + + mount_dir = Path("/mount_test") + mount_dir.mkdir(exist_ok=True) + run_js( + """ + (fstype, mountDir) => + pyodide.FS.mount(pyodide.FS.filesystems[fstype], {root : "."}, mountDir); + """ + )(fstype, str(mount_dir)) + + file = open("/mount_test/a.txt", "w") + fd2 = dup(file.fileno()) + close(fd2) + file.write("abcd") + file.close() + + [email protected]_dynamic_linking +@only_chrome +@run_in_pyodide +async def test_nativefs_dup(selenium, runner): + from os import close, dup + + import pytest + + from pyodide.code import run_js + + # Note: Using *real* native file system requires + # user interaction so it is not available in headless mode. + # So in this test we use OPFS (Origin Private File System) + # which is part of File System Access API but uses indexDB as a backend. + + if runner == "playwright": + pytest.xfail("Playwright doesn't support file system access APIs") + + await run_js( + """ + async () => { + root = await navigator.storage.getDirectory(); + testFileHandle = await root.getFileHandle('test_read', { create: true }); + writable = await testFileHandle.createWritable(); + await writable.write("hello_read"); + await writable.close(); + await pyodide.mountNativeFS("/mnt/nativefs", root); + } + """ + )() + file = open("/mnt/nativefs/test_read") + fd2 = dup(file.fileno()) + close(fd2) + assert file.read() == "hello_read" + file.close()
`OSError: [Errno 9] Bad file descriptor` when trying to load `.npy` files, works with `.npz` file format ## 🐛 Bug NumPy is unable to load arrays from `.npy` binaries, but it can read from compressed `.npz` archives. ### To Reproduce I noticed this error when compiling PyWavelets (`pywt`) from source via the Emscripten toolchain. In an activated virtual environment created by Pyodide, run the following: ```bash git clone https://github.com/PyWavelets/pywt.git pip install . ``` and then ```python import pywt import numpy as np aero = pywt.data.aero() ref = np.array([[178, 178, 179], [170, 173, 171], [185, 174, 171]]) np.testing.assert_allclose(aero[:3, :3], ref) ``` should fail. However, [after converting](https://github.com/PyWavelets/pywt/pull/701/files#diff-86b5b5c7cbe8cc8368f6991c914b7263019507351ce567543cbf2b627b91aa57) these `.npy` files to `.npz`, NumPy can safely load the arrays from the files as requested. Here is an example of conversion from `.npy` to `.npz`: ```python import numpy as np ecg = np.load("pywt/data/ecg.npy") np.savez(file="ecg.npz", data=ecg) ``` after which `ecg.npz` can be loaded as follows: ```python import numpy as np loaded = np.load("ecg.npz") print(loaded["data"]) ``` ### Expected behavior The Pyodide environment should be able to load the `.npy` file format stored in a directory, but [fails with multiple `OSError`s](https://github.com/agriyakhetarpal/pywt/actions/runs/7993252511/job/21828629911), possibly due to the lack of a server for filesystem access as the Pyodide documentation mentions – but this doesn't explain why `.npz` files work? The expected behaviour should be that all file formats work. ### Environment - Pyodide Version<!-- (e.g. 1.8.1) -->: `pyodide-build` version 0.25.0 - Browser version<!-- (e.g. Chrome 95.0.4638.54) -->: N/A - Any other relevant information: <!-- If you are building Pyodide by yourself, please also include these information: --> <!-- - Commit hash of Pyodide git repository: - Build environment<!--(e.g. Ubuntu 18.04, pyodide/pyodide-env:19 docker)- ->: --> ### Additional context xref: https://github.com/PyWavelets/pywt/pull/701
Thanks for the report @agriyakhetarpal. So far I am not able to reproduce it. What is the traceback you are seeing? I did the following steps: ```sh mkdir tmp/pyodide-bug-4541 cd tmp/pyodide-bug-4541 python3.11 -m venv .venv pip install pyodide-build pyodide venv .venv-pyodide git clone https://github.com/PyWavelets/pywt.git --depth 1 pyodide build pywt .venv-pyodide/bin/pip install pywt/dist/* ``` Then I made a file with the contents you provided: ```py import pywt import numpy as np aero = pywt.data.aero() ref = np.array([[178, 178, 179], [170, 173, 171], [185, 174, 171]]) np.testing.assert_allclose(aero[:3, :3], ref) ``` Then I ran ```sh .venv-pyodide/bin/python reproduction.py ``` and this executed the code without error. > So far I am not able to reproduce it. What is the traceback you are seeing? Ah, that may be a timing issue - I just merged the workaround (and a Pyodide CI job from @agriyakhetarpal!) at https://github.com/PyWavelets/pywt/pull/701. With commit `e69b126c096` I think it'll reproduce. Thanks for verifying, you might have to go back one commit in the `pywt` directory and re-run the `reproduction.py` script, because we had fixed this upstream by converting the `.npy` files to `.npz` before your message here: https://github.com/PyWavelets/pywt/pull/701 Moreover, the above example – it turns out, used a `.npz` file, so that was probably invalid. Maybe accessing the files can be tried directly instead of the API that `pywt` provides? ```python import numpy as np loaded_data = np.load("pywt/data/'ecg.npy') ``` and then running array operations on the `loaded_data` array (it should fail at the time of loading, ideally)? Edit: ah, @rgommers and I posted at the same time! Okay, with commit `e69b126c096` and ```py import numpy as np loaded_data = np.load("pywt/pywt/data/ecg.npy") ``` I now reproduce the bug: ```py Traceback (most recent call last): File "/tmp/pyodide-bug-4541/repro.py", line 11, in <module> File "/tmp/pyodide-bug-4541/.venv-pyodide/lib/python3.11/site-packages/numpy/lib/npyio.py", line 422, in load File "/lib/python311.zip/contextlib.py", line 589, in __exit__ File "/lib/python311.zip/contextlib.py", line 574, in __exit__ OSError: [Errno 8] Bad file descriptor ``` Thanks @agriyakhetarpal and @rgommers! A slightly simpler reproducer: ```py from numpy.lib import format with open("pywt/pywt/data/ecg.npy", "rb") as fid: format.read_array(fid) ``` And another layer in: ```py import numpy as np with open("pywt/pywt/data/ecg.npy", "rb") as fid: np.fromfile(fid, dtype=np.int32, count=1024) ``` And inside of `array_fromfile` we encounter our nemesis, `dup2`: https://github.com/numpy/numpy/blob/main/numpy/_core/src/multiarray/multiarraymodule.c?plain=1#L2348 Can you tell me @rgommers why it is that the function called `npy_PyFile_Dup2` calls `os.dup` and not `os.dup2`? https://github.com/numpy/numpy/blob/main/numpy/_core/include/numpy/npy_3kcompat.h?plain=1#L246 :laughing: Great question. Git blame tells me that that line of code has not been touched in 15 years. Given the name, it's not unlikely that it was a simple error that didn't matter on other platforms. From your comments I assume you've run into `dup`/`dup2` before? Both are documented as "not available for WASI": https://docs.python.org/3/library/os.html#os.dup. No statement on WASM. From the numpy 1.8.1 release notes: _"The utility function `npy_PyFile_Dup` and `npy_PyFile_DupClose` are broken by the internal buffering python 3 applies to its file objects. To fix this two new functions `npy_PyFile_Dup2` and `npy_PyFile_DupClose2` are declared in `npy_3kcompat.h` and the old functions are deprecated. Due to the fragile nature of these functions it is recommended to instead use the python API when possible."_ So the `Dup2` here may not have meant the Python-level `dup2`. > From your comments I assume you've run into dup/dup2 before? Yeah there have been at least five other bugs involving dup. At this point it's the first thing I expect when I see a bug report like this. https://github.com/emscripten-core/emscripten/pulls?q=is%3Apr+author%3Ahoodmane+dup > So the Dup2 here may not have meant the Python-level dup2. As you say, it seems not. Anyways I found the bug. Emscripten's filesystem maintains separate file descriptors from the linux host, so it has a mapping from the emscripten file descriptor to the linux file descriptor. In the reproduction, the file is opened and linux assigns it descriptor 27, Emscripten assigns it descriptor 3. When we `dup` the descriptor, Emscripten makes a new descriptor 4, also pointing to linux descriptor 27. Then when we close emscripten descriptor 4 which closes linux descriptor 27 and finally when emscripten descriptor 3 is closed it tries to close linux descriptor 27 again which raises `EBADF: close() on bad file descriptor` which propagates into the OS error you see. We either need to also do a native `dup` on the linux descriptor or reference count it. Wow, that was a quick fix! Thanks a lot @hoodmane. This issue can be closed, right? I'll make a pr backporting the patch and ading a test case and close when that is merged.
2024-02-23T19:41:06
pyodide/pyodide
4,568
pyodide__pyodide-4568
[ "4006" ]
07a06070e0e2502e550138459880286dcdadcb13
diff --git a/src/py/pyodide/webloop.py b/src/py/pyodide/webloop.py --- a/src/py/pyodide/webloop.py +++ b/src/py/pyodide/webloop.py @@ -11,7 +11,7 @@ from .ffi import IN_BROWSER, create_once_callable if IN_BROWSER: - from js import setTimeout + from pyodide_js._api import scheduleCallback T = TypeVar("T") S = TypeVar("S") @@ -343,7 +343,10 @@ def run_handle(): else: raise - setTimeout(create_once_callable(run_handle, _may_syncify=True), delay * 1000) + scheduleCallback( + create_once_callable(run_handle, _may_syncify=True), delay * 1000 + ) + return h def _decrement_in_progress(self, *args):
diff --git a/src/js/test/unit/scheduler.test.ts b/src/js/test/unit/scheduler.test.ts new file mode 100644 --- /dev/null +++ b/src/js/test/unit/scheduler.test.ts @@ -0,0 +1,21 @@ +import * as chai from "chai"; +import { scheduleCallback } from "../../scheduler"; + +describe("scheduleCallback", () => { + // Note: This test requires `--exit` flag to be set for mocha + // to avoid hanging the process + // see: https://github.com/facebook/react/issues/26608 + it("should call the callback immediately if timeout is 0", () => { + const start = Date.now(); + scheduleCallback(() => { + chai.assert.isAtMost(Date.now() - start, 4); + }); + }); + + it("should call the callback after the given timeout", () => { + const start = Date.now(); + scheduleCallback(() => { + chai.assert.isAtLeast(Date.now() - start, 10); + }, 10); + }); +}); diff --git a/src/tests/test_webloop.py b/src/tests/test_webloop.py --- a/src/tests/test_webloop.py +++ b/src/tests/test_webloop.py @@ -497,3 +497,20 @@ async def temp(): loop._no_in_progress_handler = None loop._keyboard_interrupt_handler = None loop._system_exit_handler = None + + +@run_in_pyodide +async def test_zero_timeout(selenium): + import asyncio + import time + + now = time.time() + + for _ in range(1000): + await asyncio.sleep(0) + + done = time.time() + elapsed = done - now + + # Very rough check, we hope it's less than 4s (1000 * 4ms [setTimeout delay in most browsers]) + assert elapsed < 4, f"elapsed: {elapsed}s"
Better performing event loop ## Proposed refactoring or deprecation The current implementation in [webloop.py](https://github.com/pyodide/pyodide/blob/3caa249177c09624b4e2039d4a68cfcf2fb014c4/src/py/pyodide/webloop.py#L342) relies on javascript's setTimeout function. While this implementation works, it introduces an issue for delays < 4ms, because per standard in all browsers `setTimeout` supports a minimum delay value of 4ms. On occasions developers introduce `await asyncio.sleep(0)` in their code to relinquish execution for a brief period in time in parts of asynchronous functions which would be called repetitively thus hogging the event loop. Since pyodide uses setTimeout, each call to `await asyncio.sleep(0)` will introduce a 4ms delay which in turn makes the code appear slow. ### Motivation Aardwolf RDP client implementation is running slower than expected on pyodide because of this issue. ### Pitch I'd like to have a replacement implemented in pyodide's `webloop.py` for `setTimeout` which supports faster callbacks. ### Additional context I did some tests which did speed up my code by replacing calls for setTimeout with a MessageChannel-based implementation if `delay==0`. It worked on the live tests, here are the results: - default behaviour ``` import time import asyncio >>> async def measure_execution_time(): ... num_measurements = 1000 ... total_time = 0 ... for _ in range(num_measurements): ... start_time = time.perf_counter() ... await asyncio.sleep(0) ... end_time = time.perf_counter() ... total_time += (end_time - start_time) ... average_time = total_time / num_measurements ... print(f"On average, the function took {average_time} seconds to execute") ... >>> await measure_execution_time() On average, the function took 0.00456210000899992 seconds to execute >>> await measure_execution_time() On average, the function took 0.004544299998000042 seconds to execute ``` - modifying `webloop.py` to use `zeroTimeout`: ``` function zeroTimeout(callback, delay) { if(delay == 0){ const channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(''); } else{ setTimeout(callback, delay); } } ``` ``` Python 3.11.2 (main, Jul 21 2023 11:59:42) on WebAssembly/Emscripten Type "help", "copyright", "credits" or "license" for more information. >>> import asyncio >>> import time >>> async def measure_execution_time(): ... num_measurements = 1000 ... total_time = 0 ... for _ in range(num_measurements): ... start_time = time.perf_counter() ... await asyncio.sleep(0) ... end_time = time.perf_counter() ... total_time += (end_time - start_time) ... average_time = total_time / num_measurements ... print(f"On average, the function took {average_time} seconds to execute") ... >>> await measure_execution_time() On average, the function took 0.00016000000100000023 seconds to execute >>> await measure_execution_time() On average, the function took 0.00016209999599999493 seconds to execute >>> await measure_execution_time() On average, the function took 0.00014569999600001893 seconds to execute ``` The `webloop.py` script was modified in the following way: ``` if IN_BROWSER: from js import setTimeout as originalSetTimeout try: from js import zeroTimeout as setTimeout except ImportError: setTimeout = originalSetTimeout print('Failed to import zeroTimeout') ``` ``` def run_handle(*args, **kwargs): ``` The latter modification was needed because the `MessageChannel` version must dispatch some data to `run_handle`. *WARNING* I have no idea if this messes up something on the long run!!!!
Not sure if related or not (as it's on using regular Emscripten/WASM in Chrome without pyodide), but I noticed that even mild file manipulation of Emscripten's `Module.FS` on the main UI thread (even if using async) slows Chrome UI rendering considerably (seems no simple way to ensure regular enough "ui events handling" when some background, even async procesing is happening). So far my sentiment is that for almost any work we must use Web Workers to avoid any UI freezes... Thanks @skelsec. I wonder if we could use something like: ```js if (delay_ms < 4) { await 0; } else { await sleep(delay_ms); } ``` I have some code that uses asyncio.sleep(0) and runs a lot slower in Pyodide than I would expect. Is there an easy way to test this with a PyScript XWorker or a pyodide WebWorker? @e-nikolov I think you can open a PR with the proposed fixes here. Personally, I am okay with @skelsec's fix, so unless other Pyodide devs are against it, we can merge. One thing we need to check is that `MessageChannel` support in Node (it looks like Node < 15 partially support `MessageChannel`?)
2024-02-26T12:46:55
pyodide/pyodide
4,705
pyodide__pyodide-4705
[ "4704" ]
975565bc3f14daf2d22545275ea9680f49a979f3
diff --git a/pyodide-build/pyodide_build/pywasmcross.py b/pyodide-build/pyodide_build/pywasmcross.py --- a/pyodide-build/pyodide_build/pywasmcross.py +++ b/pyodide-build/pyodide_build/pywasmcross.py @@ -479,7 +479,7 @@ def handle_command_generate_args( # noqa: C901 return line elif cmd == "cmake": # If it is a build/install command, or running a script, we don't do anything. - if "--build" in line or "--install" in line or "-P" in line: + if "--build" in line or "--install" in line or "-P" in line or "-E" in line: return line flags = get_cmake_compiler_flags()
cmake -E capabilities is broken ## 🐛 Bug The most recent version of scikit-build-core switched to using `cmake -E capabilities` instead of `cmake --version`, as that's the recommended way to get information about CMake. https://github.com/scikit-build/scikit-build-core/pull/675 However, https://github.com/pyodide/pyodide/blob/975565bc3f14daf2d22545275ea9680f49a979f3/pyodide-build/pyodide_build/pywasmcross.py#L493 is adding `--fresh` to all cmake commands, which breaks this with "`-E capabilities accepts no additional arguments`". `cmake --version` doesn't care about the extra flag. (I assume this also may break all other `cmake -E` commands? Also `-P` (script) commands?) Edit: -P is already checked, is -E needs to be added. I think if this is going to be forcefully injected, it needs to be done more carefully based on the command being passed.
2024-04-19T22:11:50
pyodide/pyodide
4,722
pyodide__pyodide-4722
[ "4721" ]
334628426ff4e906266e55a0ca0f7c8c5468a1a5
diff --git a/pyodide-build/pyodide_build/buildpkg.py b/pyodide-build/pyodide_build/buildpkg.py --- a/pyodide-build/pyodide_build/buildpkg.py +++ b/pyodide-build/pyodide_build/buildpkg.py @@ -4,18 +4,18 @@ Builds a Pyodide package. """ -import cgi import fnmatch import os +import re import shutil import subprocess import sys -import urllib from collections.abc import Iterator from datetime import datetime from pathlib import Path from typing import Any, cast -from urllib import parse, request + +import requests from . import common, pypabuild from .bash_runner import BashRunnerWithSharedEnvironment, get_bash_runner @@ -301,9 +301,10 @@ def _download_and_extract(self) -> None: max_retry = 3 for retry_cnt in range(max_retry): + response = requests.get(url) try: - response = request.urlopen(url) - except urllib.error.URLError as e: + response.raise_for_status() + except requests.HTTPError as e: if retry_cnt == max_retry - 1: raise RuntimeError( f"Failed to download {url} after {max_retry} trials" @@ -313,18 +314,18 @@ def _download_and_extract(self) -> None: break - # TODO: replace cgi with something else (will be removed in Python 3.13) - _, parameters = cgi.parse_header( - response.headers.get("Content-Disposition", "") - ) - if "filename" in parameters: - tarballname = parameters["filename"] - else: - tarballname = Path(parse.urlparse(response.geturl()).path).name - self.build_dir.mkdir(parents=True, exist_ok=True) + + tarballname = url.split("/")[-1] + if "Content-Disposition" in response.headers: + filenames = re.findall( + "filename=(.+)", response.headers["Content-Disposition"] + ) + if filenames: + tarballname = filenames[0] + tarballpath = self.build_dir / tarballname - tarballpath.write_bytes(response.read()) + tarballpath.write_bytes(response.content) checksum = self.source_metadata.sha256 if checksum is not None:
Remove possible query string from tarballname For CoolProp, we are getting `tarballname` as `'CoolProp_sources.zip?viasf=1'` which then crashes when we give it to `shutil.unpack_archive` with `Unknown archive format`.
Thanks for fixing this!
2024-04-27T03:53:06
pyodide/pyodide
4,806
pyodide__pyodide-4806
[ "4783" ]
d317e66d174efa203c59f094eb7714c0b90f7613
diff --git a/pyodide-build/pyodide_build/cli/build.py b/pyodide-build/pyodide_build/cli/build.py --- a/pyodide-build/pyodide_build/cli/build.py +++ b/pyodide-build/pyodide_build/cli/build.py @@ -282,5 +282,6 @@ def main( "context_settings": { "ignore_unknown_options": True, "allow_extra_args": True, + "help_option_names": ["-h", "--help"], }, }
`pyodide build -h` should print help text ## 🐛 Bug `pyodide build -h` treats `-h` as a package name rather than as a request for help text.
Click has a horrible (IMO) default of not treating `-h` as help. You have to enable it.
2024-05-26T21:25:59
pyodide/pyodide
4,812
pyodide__pyodide-4812
[ "4813" ]
43cce6e5fffa4cfcb0ae3709a9c40844e720dabb
diff --git a/pyodide-build/pyodide_build/out_of_tree/venv.py b/pyodide-build/pyodide_build/out_of_tree/venv.py --- a/pyodide-build/pyodide_build/out_of_tree/venv.py +++ b/pyodide-build/pyodide_build/out_of_tree/venv.py @@ -86,6 +86,7 @@ def get_pip_monkeypatch(venv_bin: Path) -> str: print([ os.name, sys.platform, + platform.system(), sys.implementation._multiarch, sysconfig.get_platform() ]) @@ -129,7 +130,7 @@ def _emscripten_platforms(): yield from tags._generic_platforms() def platform_tags(): - if platform.system() == "emscripten": + if platform.system() == "Emscripten": yield from _emscripten_platforms() return return orig_platform_tags() @@ -137,12 +138,12 @@ def platform_tags(): tags.platform_tags = platform_tags """ f""" - os_name, sys_platform, multiarch, host_platform = {platform_data} + os_name, sys_platform, platform_system, multiarch, host_platform = {platform_data} os.name = os_name orig_platform = sys.platform sys.platform = sys_platform sys.implementation._multiarch = multiarch - platform.system = lambda: sys_platform + platform.system = lambda: platform_system platform.machine = lambda: "wasm32" os.environ["_PYTHON_HOST_PLATFORM"] = host_platform os.environ["_PYTHON_SYSCONFIGDATA_NAME"] = f'_sysconfigdata_{{sys.abiflags}}_{{sys.platform}}_{{sys.implementation._multiarch}}'
Add support for environment markers in dependency specifiers ## Description `micropip` at the time of writing apparently does not work with dependency specifiers – specifically, [environment markers](https://packaging.python.org/en/latest/specifications/dependency-specifiers/#environment-markers). A reproducer is as follows: ##### `pyproject.toml` ```toml [project] name = "mypackage" dependencies = [ 'asciitree', 'numpy>=1.26.2', # this works 'fasteners; sys_platform != "emscripten"', # or 'fasteners; platform_system != "Emscripten"' 'scipy', # ... ] license = { text = "BSD-3-Clause" } # and so on ``` which ignores the restriction I put in place on `fasteners`, and proceeds to install it anyway ([workflow logs](https://github.com/agriyakhetarpal/zarr-python/actions/runs/9210973305/job/25339222585#step:8:48)). Though, I understand that this example might be a stub – another edge case with some additional context plus more logs is available below. ## Expected behaviour The expected behaviour would be to support the parsing of environment-marker-based dependency specifiers when installing a package and therefore conditionally include or exclude dependencies from PEP-621-style dependency metadata in `pyproject.toml` through the supported grammar mentioned in the Python Packaging guide. In this case, it should exclude `fasteners`. ## Additional context I stumbled across this when I was trying to add out-of-tree Pyodide builds for the Zarr package (xref: zarr-developers/zarr-python#1903), where `zarr` requires `numcodecs` as a dependency, but it does not include the `[msgpack]` optional dependency for `numcodecs`. This makes the tests suite fail to run because of import errors across the package (not sure about the reason) – which is why I was trying to add something like this: ```toml dependencies = [ 'numcodecs>=0.10.0', 'numcodecs[msgpack]>=0.10.0; platform_system == "Emscripten"', ``` to conditionally include the `msgpack` dependency when running in a Pyodide virtual environment, but this does not currently work and `micropip` does not install `msgpack` (the `[msgpack]` optional dependency is defined to install just the `msgpack` package as of now). However, if I remove `platform_system == "Emscripten"` from the above TOML table, and keep just `numcodecs[msgpack]>=0.10.0`, it _does_ install `msgpack` as expected ([workflow logs](https://github.com/agriyakhetarpal/zarr-python/actions/runs/9211012984/job/25339362619#step:8:51)). While I can add `msgpack` as a dependency directly at this time because there is no pin on its version, it could cause issues in situations where there would be constraints on optional dependencies (perhaps pyodide/micropip#93 would be helpful there) – say, if `numcodecs[msgpack]` were to require `msgpack>=0.12.0`, I would have to install `msgpack>=0.12.0` in a further and separate `pip install ...` command invocation, which is probably okay for one dependency or two, but for cases where there can be several optional dependencies, there would not be much of a choice but to either carefully (and manually) sync in multiple locations the versions of the packages being installed, or prepare a lockfile beforehand and keep updating it.
Thanks for the report! This looks like a bug... but I am not sure this is a bug in micropip. @hoodmane does `pyodide venv` rely on micropip when installing packages? I guess `platform_system` is somehow incorrect in pyodide venv. One thing I suspect is that in the browser, I get the following values for `packaging.markers.default_environment()`. - 'platform_system': 'Emscripten' (platform.system) - 'sys_platform': 'emscripten' (sys.platform) While in `pyodide venv`, both `platform.system` and `sys.platform` seem to be set to `emscripten` (note that the first letter is not capital) ([code pointer](https://github.com/pyodide/pyodide/blob/c53ff47046412b53d85d2761baf6272071692bc1/pyodide-build/pyodide_build/out_of_tree/venv.py#L140C60-L145)) > Thanks for the report! This looks like a bug... but I am not sure this is a bug in micropip. Oops, thanks! Please feel free to transfer this issue over to the Pyodide repository if that would make better sense. Also, thanks for the pointer – I'll probably need to read a bit more to investigate, but considering that we need to manage and ensure the return of just two values ("Emscripten" versus "emscripten"), that should be an easier fix for now. I think this is a tiny fix, I'll take care of it.
2024-05-28T14:30:06
pyodide/pyodide
4,833
pyodide__pyodide-4833
[ "4832" ]
7cf233e4589af3a5ab31b8417cc783f929e3942f
diff --git a/src/py/_pyodide/_core_docs.py b/src/py/_pyodide/_core_docs.py --- a/src/py/_pyodide/_core_docs.py +++ b/src/py/_pyodide/_core_docs.py @@ -17,7 +17,7 @@ ) from functools import reduce from types import TracebackType -from typing import IO, Any, Generic, Protocol, TypeVar, overload +from typing import IO, Any, Generic, ParamSpec, Protocol, TypeVar, overload from .docs_argspec import docs_argspec @@ -33,6 +33,7 @@ _save_name = __name__ __name__ = "" +P = ParamSpec("P") T = TypeVar("T") S = TypeVar("S") KT = TypeVar("KT") # Key type. @@ -346,7 +347,7 @@ def default_converter(value, convert, cache): raise NotImplementedError -class JsDoubleProxy(JsProxy): +class JsDoubleProxy(JsProxy, Generic[T]): """A double proxy created with :py:func:`create_proxy`.""" _js_type_flags = ["IS_DOUBLE_PROXY"] @@ -355,7 +356,7 @@ def destroy(self) -> None: """Destroy the proxy.""" pass - def unwrap(self) -> Any: + def unwrap(self) -> T: """Unwrap a double proxy created with :py:func:`create_proxy` into the wrapped Python object. """ @@ -843,11 +844,15 @@ def aclose(self) -> Awaitable[None]: raise NotImplementedError -class JsCallable(JsProxy): +class JsCallable(JsProxy, Generic[P, T]): _js_type_flags = ["IS_CALLABLE"] - def __call__(self): - pass + __call__: Callable[P, T] + + +class JsCallableDoubleProxy( + JsDoubleProxy[Callable[P, T]], JsCallable[P, T], Generic[P, T] +): ... class JsArray(JsIterable[T], Generic[T], MutableSequence[T], metaclass=_ABCMeta): @@ -1113,7 +1118,7 @@ def __delitem__(self, idx: KT) -> None: return None -class JsOnceCallable(JsCallable): +class JsOnceCallable(JsCallable[P, T], Generic[P, T]): def destroy(self): pass @@ -1198,20 +1203,32 @@ def style(self) -> Any: @docs_argspec("(obj: Callable[..., Any], /) -> JsOnceCallable") def create_once_callable( - obj: Callable[..., Any], /, *, _may_syncify: bool = False -) -> JsOnceCallable: + obj: Callable[P, T], /, *, _may_syncify: bool = False +) -> JsOnceCallable[P, T]: """Wrap a Python Callable in a JavaScript function that can be called once. After being called the proxy will decrement the reference count of the Callable. The JavaScript function also has a ``destroy`` API that can be used to release the proxy without calling it. """ - return obj # type: ignore[return-value] + return obj # type:ignore[return-value] + + +@overload +def create_proxy( + obj: Callable[P, T], /, *, capture_this: bool = False, roundtrip: bool = True +) -> JsCallableDoubleProxy[P, T]: ... + + +@overload +def create_proxy( + obj: T, /, *, capture_this: bool = False, roundtrip: bool = True +) -> JsDoubleProxy[T]: ... def create_proxy( - obj: Any, /, *, capture_this: bool = False, roundtrip: bool = True -) -> JsDoubleProxy: + obj: T, /, *, capture_this: bool = False, roundtrip: bool = True +) -> JsDoubleProxy[T]: """Create a :py:class:`JsProxy` of a :js:class:`~pyodide.ffi.PyProxy`. This allows explicit control over the lifetime of the @@ -1244,7 +1261,7 @@ def create_proxy( With ``roundtrip=False`` this would be an error. """ - return obj + return obj # type:ignore[return-value] # from python2js diff --git a/src/py/pyodide/_state.py b/src/py/pyodide/_state.py --- a/src/py/pyodide/_state.py +++ b/src/py/pyodide/_state.py @@ -40,7 +40,7 @@ def restore_state(state: dict[str, Any]) -> int: del sys.modules[key] sys.modules.update(loaded_js_modules) - sys.last_exc = None # type:ignore[attr-defined] + sys.last_exc = None # type:ignore[assignment] sys.last_type = None sys.last_value = None sys.last_traceback = None diff --git a/src/py/pyodide/console.py b/src/py/pyodide/console.py --- a/src/py/pyodide/console.py +++ b/src/py/pyodide/console.py @@ -398,7 +398,7 @@ def formatsyntaxerror(self, e: Exception) -> str: This doesn't include a stack trace because there isn't one. The actual error object is stored into :py:data:`sys.last_value`. """ - sys.last_exc = e # type:ignore[attr-defined] + sys.last_exc = e sys.last_type = type(e) sys.last_value = e sys.last_traceback = None @@ -420,7 +420,7 @@ def formattraceback(self, e: BaseException) -> str: The actual error object is stored into :py:data:`sys.last_value`. """ - sys.last_exc = e # type:ignore[attr-defined] + sys.last_exc = e sys.last_type = type(e) sys.last_value = e sys.last_traceback = e.__traceback__
diff --git a/src/tests/test_jsproxy.py b/src/tests/test_jsproxy.py --- a/src/tests/test_jsproxy.py +++ b/src/tests/test_jsproxy.py @@ -1780,7 +1780,7 @@ def test_jsarray_remove(selenium): a.remove(78) assert a.to_py() == l l.append([]) # type:ignore[arg-type] - p = create_proxy([], roundtrip=False) + p = create_proxy([], roundtrip=False) # type:ignore[var-annotated] a.append(p) assert a.to_py() == l l.remove([]) # type:ignore[arg-type] diff --git a/src/tests/test_pyodide.py b/src/tests/test_pyodide.py --- a/src/tests/test_pyodide.py +++ b/src/tests/test_pyodide.py @@ -836,7 +836,7 @@ def __del__(self): assert sys.getrefcount(f) == 2 proxy = create_proxy(f) assert sys.getrefcount(f) == 3 - assert proxy() == 7 # type:ignore[operator] + assert proxy() == 7 testAddListener(proxy) assert sys.getrefcount(f) == 3 assert testCallListener() == 7 @@ -890,7 +890,7 @@ def test_return_destroyed_value(selenium): from pyodide.ffi import JsException, create_proxy f = run_js("(function(x){ return x; })") - p = create_proxy([]) + p = create_proxy([]) # type: ignore[var-annotated] p.destroy() with pytest.raises(JsException, match="Object has already been destroyed"): f(p) diff --git a/src/tests/test_static_typing.py b/src/tests/test_static_typing.py new file mode 100644 --- /dev/null +++ b/src/tests/test_static_typing.py @@ -0,0 +1,76 @@ +from inspect import getsource +from pathlib import Path +from textwrap import dedent +from typing import TypeVar, assert_type + +from mypy.api import run +from pytest import raises + + +def _mypy_check(source: str) -> tuple[str, str, int]: + path = str(Path(__file__).parent.parent.parent / "pyproject.toml") + stdout, stderr, exit_status = run(["-c", source, "--config-file", path]) + return stdout, stderr, exit_status + + +def assert_no_error(source: str) -> None: + stdout, _, exit_status = _mypy_check(f"from typing import *\n\n{dedent(source)}") + assert exit_status == 0, stdout + + +def test_self(): + with raises(AssertionError): + assert_no_error("a: str = 123") + + +def test_create_proxy(): + def _(): + from pyodide.ffi import create_proxy + + a: int = 2 + assert_type(create_proxy(a).unwrap(), int) + + assert_no_error(getsource(_)) + + +def test_generic(): + def _(): + from pyodide.ffi import JsDoubleProxy, JsPromise + + def _(a: JsPromise[int]) -> None: + assert_type(a.then(str), JsPromise[str]) + + def _(b: JsDoubleProxy[str]) -> None: + assert_type(b.unwrap(), str) + + assert_no_error(getsource(_)) + + +def test_callable_generic(): + def _(): + from pyodide.ffi import create_once_callable, create_proxy + + T = TypeVar("T", int, float, str) + + def f(x: T) -> T: + return x * 2 + + assert_type(create_once_callable(f)(2), int) + assert_type(create_proxy(f)(""), str) + + assert_no_error(getsource(_)) + + +def test_decorator_usage(): + def _(): + from pyodide.ffi import create_once_callable + + T = TypeVar("T") + + @create_once_callable + def f(x: T) -> list[T]: + return [x] + + assert_type(f((int(input()), str(input()))), list[tuple[int, str]]) + + assert_no_error(getsource(_))
Wrong typing for `create_proxy` and `create_once_callable` ## 🐛 Bug `create_proxy` is often used to register a callback to a JavaScript instance, like `addeventlistener` or `some_promise.then`, and `create_once_callable` is often used to decorate single-use functions. So I think their biggest usage is **to decorate callables**. But the typing is wrong. A callable decorated with it lose all of its typing signatures, makes type checkers keep throwing false positive errors. ### To Reproduce ```py from typing import reveal_type from pyodide.ffi import create_once_callable @create_once_callable def f(x: int) -> int: return x a = f(123) reveal_type(a) ``` ```sh > mypy ./test.py error: Too many arguments for "__call__" [call-arg] test.py:13: note: Revealed type is "Any" > pyright ./test.py error: Expected 0 positional arguments (reportCallIssue) information: Type of "a" is "Unknown" ``` ### Expected behavior 1. No error 2. The revealed type should be `int` ### Environment - Pyodide Version<!-- (e.g. 0.25.0) -->: `0.26.0` - Browser version<!-- (e.g. Chrome 122.0.4638.54) -->: none - Any other relevant information: none ### Additional context I think it is easy to solve this by generic typing. Also since pyodide is already using 3.12 (and pyodide-py has a `requires-python = ">=3.12"`), we can use python3.12's new type syntax to do this elegantly. <details><summary>Like this</summary> <p> ```py from typing import Callable class JsCallable[**P, T](JsProxy): def __init__(self, obj: Callable[P, T]): ... def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: ... ``` Instead of ```py from typing import Callable, Generic, ParamSpec, TypeVar P = ParamSpec("P") T = TypeVar("T") class JsCallable(JsProxy, Generic(P, T)): def __init__(self, obj: Callable[P, T]): ... def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: ... ``` </p> </details> But I just noticed that **PEP 695 generics** are not yet supported by `mypy` yet, so maybe I shouldn't use it.
2024-06-02T16:01:59
pyodide/pyodide
4,836
pyodide__pyodide-4836
[ "2964" ]
0f2ee22320cb43e831907d59b51afe8d93829dcc
diff --git a/packages/cpp-exceptions-test2/src/cpp_exceptions_test2/__init__.py b/packages/cpp-exceptions-test2/src/cpp_exceptions_test2/__init__.py new file mode 100644 diff --git a/packages/cpp-exceptions-test2/src/setup.py b/packages/cpp-exceptions-test2/src/setup.py new file mode 100644 --- /dev/null +++ b/packages/cpp-exceptions-test2/src/setup.py @@ -0,0 +1,16 @@ +from setuptools import Extension, setup + +setup( + name="cpp-exceptions-test2", + version="1.0", + ext_modules=[ + Extension( + name="cpp_exceptions_test2", # as it would be imported + # may include packages/namespaces separated by `.` + language="c++", + sources=[ + "cpp_exceptions_test2.cpp" + ], # all sources are compiled into a single binary file + ), + ], +)
diff --git a/src/tests/test_cmdline_runner.py b/src/tests/test_cmdline_runner.py --- a/src/tests/test_cmdline_runner.py +++ b/src/tests/test_cmdline_runner.py @@ -502,3 +502,19 @@ def test_sys_exit(selenium, venv): assert result.returncode == 12 assert result.stdout == "" assert result.stderr == "" + + +def test_cpp_exceptions(selenium, venv): + result = install_pkg(venv, "cpp-exceptions-test2") + print(result.stdout) + print(result.stderr) + assert result.returncode == 0 + result = subprocess.run( + [venv / "bin/python", "-c", "import cpp_exceptions_test2"], + capture_output=True, + encoding="utf-8", + ) + print(result.stdout) + print(result.stderr) + assert result.returncode == 1 + assert "ImportError: oops" in result.stderr
TypeError: getWasmTableEntry(...) is not a function ## 🐛 Bug ``` pyodide.asm.js:10 Pyodide has suffered a fatal error. Please report this to the Pyodide maintainers. pyodide.asm.js:10 The cause of the fatal error was: pyodide.asm.js:10 TypeError: getWasmTableEntry(...) is not a function at invoke_ii (pyodide.asm.js:10:1544237) at 00bcba5a:0x54516 at invoke_viiiiiiiiiiiiiii (pyodide.asm.js:10:1548668) at 00bcba5a:0x414a2 at invoke_viii (pyodide.asm.js:10:1545014) at 00bcba5a:0x56286 at method_call_trampoline (pyodide.asm.js:10:216572) at pyodide.asm.wasm:0x162162 at method_call_trampoline (pyodide.asm.js:10:216572) at pyodide.asm.wasm:0x126317 API.fatal_error @ pyodide.asm.js:10 Module.callPyObjectKwargs @ pyodide.asm.js:10 Module.callPyObject @ pyodide.asm.js:10 apply @ pyodide.asm.js:10 apply @ pyodide.asm.js:10 runPython @ pyodide.asm.js:10 main @ (index):15 await in main (async) (anonymous) @ (index):22 pyodide.asm.js:10 Stack (most recent call first): pyodide.asm.js:10 File "<exec>", line 5 in <module> pyodide.asm.js:10 File "/lib/python3.10/site-packages/_pyodide/_base.py", line 304 in run pyodide.asm.js:10 File "/lib/python3.10/site-packages/_pyodide/_base.py", line 435 in eval_code (index):21 Uncaught (in promise) TypeError: getWasmTableEntry(...) is not a function at invoke_ii (pyodide.asm.js:10:1544237) at 00bcba5a:0x54516 at invoke_viiiiiiiiiiiiiii (pyodide.asm.js:10:1548668) at 00bcba5a:0x414a2 at invoke_viii (pyodide.asm.js:10:1545014) at 00bcba5a:0x56286 at method_call_trampoline (pyodide.asm.js:10:216572) at pyodide.asm.wasm:0x162162 at method_call_trampoline (pyodide.asm.js:10:216572) at pyodide.asm.wasm:0x126317 ``` ### To Reproduce https://github.com/kitao/pyxel/tree/maturin * First install the maturin beta version: `pip install -U --pre maturin` * Build with maturin: `RUSTUP_TOOLCHAIN=nightly maturin build -o dist --release --target wasm32-unknown-emscripten` * Run `./scripts/start_server` and open `http://localhost:8000` in browser, see the error in console. ### Expected behavior No `TypeError: getWasmTableEntry(...) is not a function` in console. ### Environment - Pyodide Version<!-- (e.g. 1.8.1) -->: 0.21.0 - Browser version<!-- (e.g. Chrome 95.0.4638.54) -->: 104.0.5112.79 - Any other relevant information: <!-- If you are building Pyodide by yourself, please also include these information: --> <!-- - Commit hash of Pyodide git repository: - Build environment<!--(e.g. Ubuntu 18.04, pyodide/pyodide-env:19 docker)- ->: --> ### Additional context <!-- Add any other context about the problem here. -->
<img width="540" alt="image" src="https://user-images.githubusercontent.com/1556054/184469209-50bedef2-60e5-4aff-b9cf-3b4473f234fb.png"> I do see `getWasmTableEntry` function in minified `pyodide.asm.js`, kinda odd. Further debugging shows that `getWasmTableEntry(0)` returned `null` so `getWasmTableEntry(0)(a1)` throws `TypeError: getWasmTableEntry(...) is not a function` <img width="618" alt="image" src="https://user-images.githubusercontent.com/1556054/184469476-2e96c3d4-c64e-4763-9dc1-321fe136ca03.png"> Use a debug build of the wheel shows a different error ``` pyodide.asm.js:formatted:3231 TypeError: Cannot read properties of undefined (reading 'apply') at stubs.<computed> (pyodide.asm.js:formatted:8037:49) at sdl2::video::_$LT$impl$u20$sdl2..sdl..VideoSubsystem$GT$::desktop_display_mode::h4260488f51b53104 (138d923e:0x3a8287) at invoke_viii (pyodide.asm.js:formatted:49510:41) at _$LT$pyxel..platform_sdl2..PlatformSdl2$u20$as$u20$pyxel..platform..Platform$GT$::new::h2b4331a8480d882d (138d923e:0x230577) at pyxel::Pyxel::new::hf0a38d431462844d (138d923e:0x28edcf) at pyxel_wrapper::system_wrapper::init::h3708483ad3f6cd52 (138d923e:0x10792e) at pyxel_wrapper::system_wrapper::__pyfunction_init::_$u7b$$u7b$closure$u7d$$u7d$::hdacd4ac63436b841 (138d923e:0x1aa522) at std::panicking::try::do_call::h0deb1ab2490d9ce2 (138d923e:0xcb16b) at invoke_vi (pyodide.asm.js:formatted:49543:41) at __rust_try (138d923e:0x8e92e) ``` Patch https://github.com/kitao/pyxel/blob/30bb7b5e087408ed3737ab1e7e224bf9bb3f789d/crates/pyxel-engine/src/platform_sdl2.rs#L59-L60 to `let scale = get_scale(width, height);` reverts back to the original `TypeError: getWasmTableEntry(...) is not a function` error <img width="904" alt="image" src="https://user-images.githubusercontent.com/1556054/184470795-39bac57b-1dd7-4c63-88af-aeb4aea085e1.png"> Thanks for the report, @messense. I can reproduce the error. For those who want to quickly reproduce the error, here is the wheel of pyxel (compressed due to Github limitation). [pyxel-1.8.0-cp37-abi3-emscripten_3_1_14_wasm32.zip](https://github.com/pyodide/pyodide/files/9330928/pyxel-1.8.0-cp37-abi3-emscripten_3_1_14_wasm32.zip) What happens if you build with `panic=abort`? @hoodmane With `panic=abort` ``` TypeError: Cannot read properties of undefined (reading 'apply') at stubs.<computed> (pyodide.asm.js:10:253214) at 00898aaa:0x2393f at method_call_trampoline (pyodide.asm.js:10:216572) at pyodide.asm.wasm:0x162162 at method_call_trampoline (pyodide.asm.js:10:216572) at pyodide.asm.wasm:0x126317 at pyodide.asm.wasm:0x1e246f at pyodide.asm.wasm:0x1e00b3 at pyodide.asm.wasm:0x1da6a5 at pyodide.asm.wasm:0x1d9a6a ``` Looks like progress. We should patch library_dylink to report the name of the missing symbols so that we can get better error messages in this case. We can probably contribute such a change to emscripten. Add a conditional breakpoint shows that the missing symbols is `SDL_GetDesktopDisplayMode`, seems like SDL2 isn't properly linked? I don't know much about linking in Emscripten, not sure what went wrong. I thought the linking error occurred because LLVM version mismatch. Emscripten 3.1.14 uses LLVM 15, but rustc 1.65.0-nightly (latest) uses LLVM 14. However, when I downgraded pyodide to 0.20.0 and emscripten 2.0.27 (which uses LLVM 14) , it threw the following error: ![image](https://user-images.githubusercontent.com/20869932/184562851-736b3f96-1003-4894-b712-ac5e344b5f49.png) So I was not able to find out whether the LLVM version matters. To reproduce: I built it using `RUSTUP_TOOLCHAIN=nightly maturin build -o dist --release --target wasm32-unknown-emscripten -- -C target-feature=+mutable-globals`, with rustc 1.65.0-nightly. And I used `pyodide.loadPackage` to load the emscripten wheel. (Due to the limitation of pyodide 0.20.0) ```js async function main() { let pyodide = await loadPyodide(); await pyodide.loadPackage(location.href.replace(/\/[^\/]+?\.[^\/]+?$/, '/')+"pyxel-1.8.0-cp37-abi3-emscripten_2_0_27_wasm32.whl"); await pyodide.runPython(` import pyxel print("PYXEL_VERSION = ", pyxel.PYXEL_VERSION) print("KEY_BACKSPACE = ", pyxel.KEY_BACKSPACE) pyxel.init(100, 100) `); } main(); ``` Probably the issue is that we aren't linking SDL into Pyodide? > Probably the issue is that we aren't linking SDL into Pyodide? OK, I've just read the [Dynamic Linking](https://emscripten.org/docs/compiling/Dynamic-Linking.html) documentation of Emscripten now. In this case I think Pyodide is the **main module** and pyxel is the **side module**, because only main module has system libraries linked in, in order to make it work we need to link SDL into Pyodide, right? @hoodmane Do we have an easy way to do a customized Pyodide build with SDL2 linked in? There is a closed issue that seems related to this. https://github.com/pyodide/pyodide/issues/1657#issuecomment-870091116 Should I rebuild pyodide with modified `MAIN_MODULE_LDFLAGS` in [Makefile.envs](https://github.com/pyodide/pyodide/blob/main/Makefile.envs#L98)? I guess another option is to statically link SDL2 in pyxel? See https://github.com/Rust-SDL2/rust-sdl2#bundled-feature and https://github.com/Rust-SDL2/rust-sdl2#static-linking-in-linux, I haven't tried so not sure whether it will build or not for `wasm32-unknown-emscripten` target. > Should I rebuild pyodide with modified `MAIN_MODULE_LDFLAGS` in [Makefile.envs](https://github.com/pyodide/pyodide/blob/main/Makefile.envs?rgh-link-date=2022-08-15T07%3A29%3A36Z#L98)? Yes. You need to add `-sUSE_SDL=2` to the `MAIN_MODULE_LDFLAGS`. > another option is to statically link SDL2 in pyxel? This is not possible because SDL2 is implemented in Javascript and Emscripten does not currently allow dynamically loading Javascript. I rebuilt pyodide with `-sUSE_SDL=2`, then the message changed: ![image](https://user-images.githubusercontent.com/20869932/184601948-6083f0f9-2219-43da-adf1-7901d21e18cd.png) I assumed this is related to a canvas issue(https://github.com/emscripten-ports/SDL2/issues/130), so I added a blank canvas with id "canvas": ```html <!-- Bootstrap HTML for running the unit tests. --> <!DOCTYPE html> <html> <head> <title>pyodide</title> <script src="./pyodide.js"></script> </head> <body> <canvas id="canvas"></canvas> <script type="text/javascript"> async function main(){ const pyodide = await loadPyodide(); await pyodide.loadPackage("micropip") const micropip = pyodide.pyimport("micropip") await micropip.install("pyxel-1.8.0-cp37-abi3-emscripten_3_1_14_wasm32.whl") await pyodide.runPython(` import pyxel pyxel.init(600,480) `) } main() </script> </body> </html> ``` Then the error changed: ![image](https://user-images.githubusercontent.com/20869932/184601384-e2c89c66-0f03-4ba1-b39f-f0d2fba1d7d4.png) Although it crashes, the initial linking issue seems to be resolved. @km19809 Can you upload the built `pyodide.js` somewhere? @messense [Dropbox](https://www.dropbox.com/s/4tba71egs6jhza1/pyodide_sdl.tar?dl=0) I think this issue is resolved, but I post the link here as a (potential) conclusion. I think setting [`-sGL_WORKAROUND_SAFARI_GETCONTEXT_BUG=0`](https://github.com/emscripten-core/emscripten/blob/main/src/library_webgl.js#L632) would fix the most recent error. You may also want [`-sMAX_WEBGL_VERSION=2`.](https://emscripten.org/docs/optimizing/Optimizing-WebGL.html?highlight=webgl#which-gl-mode-to-target) Thanks for the help! Please don't hesitate to open a follow up issue if you can't figure out how to get it working. > I think setting [`-sGL_WORKAROUND_SAFARI_GETCONTEXT_BUG=0`](https://github.com/emscripten-core/emscripten/blob/main/src/library_webgl.js#L632) would fix the most recent error. > > You may also want [`-sMAX_WEBGL_VERSION=2`.](https://emscripten.org/docs/optimizing/Optimizing-WebGL.html?highlight=webgl#which-gl-mode-to-target) This resolved SafariWebGL2 issue. (It still crashes though 😂) Thank you a lot! Using the new cibuildwheel support, both boost-histogram and iminuit report this error. I can reproduce it, I'll take a look soon =)
2024-06-04T05:00:26
streamlink/streamlink
42
streamlink__streamlink-42
[ "38" ]
d94ee92a48aeec2bfca177bd0348f952e2a1b108
diff --git a/src/streamlink/__init__.py b/src/streamlink/__init__.py --- a/src/streamlink/__init__.py +++ b/src/streamlink/__init__.py @@ -12,7 +12,7 @@ __title__ = "streamlink" -__version__ = "1.14.0-rc1" +__version__ = "0.0.1" __license__ = "Simplified BSD" __author__ = "Christopher Rosell" __copyright__ = "Copyright 2011-2015 Christopher Rosell"
Version information out of sync in docs Caused by [this](https://github.com/streamlink/streamlink/blob/d5a50c42a2f251fe4fccc37d588cd72c66287bfd/src/streamlink/__init__.py#L15).
2016-09-25T19:34:11
streamlink/streamlink
60
streamlink__streamlink-60
[ "50" ]
d550d0988116898c315f6b0777defadbbdacad95
diff --git a/src/streamlink/plugins/picarto.py b/src/streamlink/plugins/picarto.py --- a/src/streamlink/plugins/picarto.py +++ b/src/streamlink/plugins/picarto.py @@ -13,7 +13,7 @@ """, re.VERBOSE) _channel_casing_re = re.compile(r""" - <script>placeStreamChannelFlash\('(?P<channel>[^']+)',[^,]+,[^,]+,'(?P<visibility>[^']+)',[^,]+\);</script> + <script>placeStreamChannel(Flash)?\('(?P<channel>[^']+)',[^,]+,[^,]+,'(?P<visibility>[^']+)'(,[^,]+)?\);</script> """, re.VERBOSE)
Picarto Multi Streams Seems that a fix for the Picarto multi streams has been provided here: https://github.com/chrippa/livestreamer/pull/1469 Thanks!
2016-10-01T00:33:18
streamlink/streamlink
73
streamlink__streamlink-73
[ "70" ]
de376577ba46c701ee46e6d086572d735637db7c
diff --git a/src/streamlink/plugins/crunchyroll.py b/src/streamlink/plugins/crunchyroll.py --- a/src/streamlink/plugins/crunchyroll.py +++ b/src/streamlink/plugins/crunchyroll.py @@ -58,13 +58,12 @@ def parse_timestamp(ts): { "streams": validate.all( [{ - "quality": validate.text, + "quality": validate.any(validate.text, None), "url": validate.url( scheme="http", path=validate.endswith(".m3u8") ) - }], - validate.filter(lambda s: s["quality"] != "adaptive") + }] ) } ) @@ -227,11 +226,24 @@ def _get_streams(self): if not info: return - # TODO: Use dict comprehension here after dropping Python 2.6 support. - return dict( - (stream["quality"], HLSStream(self.session, stream["url"])) - for stream in info["streams"] - ) + # The adaptive quality stream contains a superset of all the other streams listeed + has_adaptive = any([s[u"quality"] == u"adaptive" for s in info[u"streams"]]) + if has_adaptive: + self.logger.debug(u"Loading streams from adaptive playlist") + for stream in filter(lambda x: x[u"quality"] == u"adaptive", info[u"streams"]): + return HLSStream.parse_variant_playlist(self.session, stream["url"]) + else: + streams = {} + # If there is no adaptive quality stream then parse each individual result + for stream in info[u"streams"]: + # the video_encode_id indicates that the stream is not a variant playlist + if u"video_encode_id" in stream: + streams[stream[u"quality"]] = HLSStream(self.session, stream[u"url"]) + else: + # otherwise the stream url is actually a list of stream qualities + streams.update(HLSStream.parse_variant_playlist(self.session, stream[u"url"])) + + return streams def _get_device_id(self): """Returns the saved device id or creates a new one and saves it."""
Crunchyroll unable to validate API responce. This has a issue on livestreamer but not here see: https://github.com/chrippa/livestreamer/issues/1492 It may only affect newer content as erased ep. 1-4 work fine but ep. 5+ result in > MacBook:~ owner$ streamlink http://www.crunchyroll.com/erased/episode-5-getaway-691801 best > [cli][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/erased/episode-5-getaway-691801 > [plugin.crunchyroll][warning] No authentication provided, you won't be able to access premium restricted content > error: Unable to validate API response: Unable to validate key 'stream_data': {u'hardsub_lang': u'enUS', u'format': u'hls', u'streams': [{u'url': u'http://serve.cxcdn.net/s/v/1xupsfbghtu0it3/m/a161c1b1d20712dc542b8104a0729401/master.m3u8?v=fcd87a7116303e39f71df0e96ca09a1e&k=MUNHWkhabDZveDk5VGRaQnFkYUFscVFmdHJRPV97ImEiOiI5MSwsamFKUCxlblVTLjEiLCJjIjoxNDc0OTEyNjU0LCJkIjoiY3JhbmltZSIsImciOiJaWiIsImgiOiIxeHVwc2ZiZ2h0dTBpdDMiLCJsIjo3MjAwLCJwIjoiMSIsInIiOiJjMzBkODIiLCJzIjoxNDc1ODEsInQiOjE0NzU3MTE5MTIsInYiOjN9', u'expires': u'2016-10-06T04:57:05+00:00', u'quality': u'adaptive'}, {u'url': u'http://serve.cxcdn.net/s/v/1xupsfbghtu0it3/m/4e405bc9b9d829183da8832912d0e31e/jaJP.m3u8?v=fcd87a7116303e39f71df0e96ca09a1e&k=d3hGSFJEd3lONVZYaEhBT0xPU3hGSHZ1THFVPV97ImEiOiI5MSwxLGphSlAsZW5VUy4xIiwiYyI6MTQ3NDkxMjY1NCwiZCI6ImNyYW5pbWUiLCJnIjoiWloiLCJoIjoiMXh1cHNmYmdodHUwaXQzIiwibCI6NzIwMCwicCI6IjEiLCJyIjoiYzMwZDgyIiwicyI6OTYzMTAxLCJ0IjoxNDc1NzExOTEyLCJ2IjozfQ', u'width': u'432', u'expires': u'2016-10-06T04:57:05+00:00', u'quality': None, u'height': u'240'}, {u'url': u'http://serve.cxcdn.net/s/v/1xupsfbghtu0it3/m/cd9946094d0e536db3ae6650154af915/jaJP.m3u8?v=fcd87a7116303e39f71df0e96ca09a1e&k=dGRWYTdLK1FjaGltcnRSdEYvcTJyaFdpNUpNPV97ImEiOiI5MSwyLGphSlAsZW5VUy4xIiwiYyI6MTQ3NDkxMjY1NCwiZCI6ImNyYW5pbWUiLCJnIjoiWloiLCJoIjoiMXh1cHNmYmdodHUwaXQzIiwibCI6NzIwMCwicCI6IjEiLCJyIjoiYzMwZDgyIiwicyI6OTE4MDcxLCJ0IjoxNDc1NzExOTEyLCJ2IjozfQ', u'width': u'640', u'expires': u'2016-10-06T04:57:05+00:00', u'quality': u'low', u'height': u'360'}, {u'url': u'http://serve.cxcdn.net/s/v/1xupsfbghtu0it3/m/63d92074b50a72d9bc0d14c8995844b9/jaJP.m3u8?v=fcd87a7116303e39f71df0e96ca09a1e&k=WTBkUnZwbEZnMFExRlFlL1ZYT2x6THBYdVdVPV97ImEiOiI5MSwzLGphSlAsZW5VUy4xIiwiYyI6MTQ3NDkxMjY1NCwiZCI6ImNyYW5pbWUiLCJnIjoiWloiLCJoIjoiMXh1cHNmYmdodHUwaXQzIiwibCI6NzIwMCwicCI6IjEiLCJyIjoiYzMwZDgyIiwicyI6ODY3NjIyLCJ0IjoxNDc1NzExOTEyLCJ2IjozfQ', u'width': u'848', u'expires': u'2016-10-06T04:57:05+00:00', u'quality': u'mid', u'height': u'480'}], u'audio_lang': u'jaJP'} does not equal None or Unable to validate key 'streams': Unable to validate key 'quality': Type of None should be 'basestring' but is 'NoneType'
If this is a bug and not crunchyroll registering the video on their end, we should consider implementing some of the code from [here](https://github.com/aheadley/python-crunchyroll), which could be easier than trying to diagnose the crunchyroll plugin. Even with a """""hotfix""""" (me using validate.transform to turn None into "none"), I still got this out, so there seem to be more underlying issues even. > ╭─ashlynn@arch ~ > ╰─➤ streamlink 'http://www.crunchyroll.com/yu-gi-oh-5ds/episode-58-the-destiny-ahead-dark-king-the-ruler-of-hell-667003' best > [cli][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/yu-gi-oh-5ds/episode-58-the-destiny-ahead-dark-king-the-ruler-of-hell-667003 > [plugin.crunchyroll][warning] No authentication provided, you won't be able to access premium restricted content > [cli][info] Available streams: none, low (worst), mid (best) > [cli][info] Opening stream: mid (hls) > [cli][error] Could not open stream: Attempted to play a variant playlist, use 'hlsvariant://http://serve.cxcdn.net/s/v/qk3vxe6ojlocp3k/m/0bcf3b9a953ab4b6aa460796669c9f03/jaJP.m3u8?v=53d5ef6a41b7b9ef4e06844c543d92b0&k=d2J0aWFtczhOcFZsTTJ3STVyb0pWWU5JbEhjPV97ImEiOiI5MSwzLGphSlAsZW5VUy4xIiwiYyI6MTQ3NDkxMjExNCwiZCI6ImNyYW5pbWUiLCJnIjoiWloiLCJoIjoicWszdnhlNm9qbG9jcDNrIiwibCI6NzIwMCwicCI6IjEiLCJyIjoiYzMwZDgyIiwicyI6NTgzNjI5LCJ0IjoxNDc1NzY2Mjc0LCJ2IjozfQ' instead
2016-10-07T12:08:47
streamlink/streamlink
95
streamlink__streamlink-95
[ "93" ]
4b365edeaf49873f09e7aba755b25b8790e48bbe
diff --git a/src/streamlink/plugins/connectcast.py b/src/streamlink/plugins/connectcast.py --- a/src/streamlink/plugins/connectcast.py +++ b/src/streamlink/plugins/connectcast.py @@ -3,13 +3,11 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate -from streamlink.stream import HDSStream - -SWF_URL = "https://www.connectcast.tv/jwplayer/jwplayer.flash.swf" - -_url_re = re.compile("http(s)?://(\w+\.)?connectcast.tv/") -_manifest_re = re.compile(".*data-playback=\"([^\"]*)\".*") +from streamlink.stream import RTMPStream +_url_re = re.compile(r"http(?:s)?://connectcast.tv/(\w+)?") +_stream_re = re.compile(r'<video src="mp4:(.*?)"') +_stream_url = "http://connectcast.tv/channel/stream/{channel}" class ConnectCast(Plugin): @classmethod @@ -17,14 +15,15 @@ def can_handle_url(self, url): return _url_re.match(url) def _get_streams(self): - res = http.get(self.url) - match = _manifest_re.search(res.text) - manifest = match.group(1) - streams = {} - streams.update( - HDSStream.parse_manifest(self.session, manifest, pvswf=SWF_URL) - ) - - return streams + url_match = _url_re.match(self.url) + stream_url = _stream_url.format(channel=url_match.group(1)) + res = self.session.http.get(stream_url) + match = _stream_re.search(res.content) + if match: + params = dict(rtmp="rtmp://stream.connectcast.tv/live", + playpath=match.group(1), + live=True) + + return dict(live=RTMPStream(self.session, params)) __plugin__ = ConnectCast
Connectcast stream fails with "invalid url" Attempting to load an active connectcast stream via `streamlink connectcast.tv/streamname` results in an error: `error: Unable to open URL: (Invalid URL '': No schema supplied. Perhaps you mean http://?)` Similarly, using `http://connectcast.tv/streamname` for the url also fails. Running on Windows, built with python 3.5.0rc2
2016-10-18T17:40:31
streamlink/streamlink
114
streamlink__streamlink-114
[ "112" ]
934f5d9060516bd8866fe217cd30666efba66fbf
diff --git a/src/streamlink/plugins/piczel.py b/src/streamlink/plugins/piczel.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/piczel.py @@ -0,0 +1,70 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http, validate +from streamlink.stream import RTMPStream, HLSStream + +STREAMS_URL = "https://piczel.tv:3000/streams/{0}?&page=1&sfw=false&live_only=true" +HLS_URL = "https://5810b93fdf674.streamlock.net:1936/live/{0}/playlist.m3u8" +RTMP_URL = "rtmp://piczel.tv:1935/live/{0}" + +_url_re = re.compile("https://piczel.tv/watch/(\w+)") + +_streams_schema = validate.Schema( + { + "type": validate.text, + "data": [ + { + "id": int, + "live": bool, + "slug": validate.text + } + ] + } +) + +class Piczel(Plugin): + @classmethod + def can_handle_url(cls, url): + return _url_re.match(url) + + def _get_streams(self): + match = _url_re.match(self.url) + if not match: + return + + channel_name = match.group(1) + + res = http.get(STREAMS_URL.format(channel_name)) + streams = http.json(res, schema=_streams_schema) + if streams["type"] not in ("multi", "stream"): + return + + for stream in streams["data"]: + if stream["slug"] != channel_name: + continue + + if not stream["live"]: + return + + streams = {} + + try: + streams.update(HLSStream.parse_variant_playlist(self.session, HLS_URL.format(stream["id"]))) + except IOError as e: + # fix for hosted offline streams + if "404 Client Error" in str(e): + return + raise + + streams["rtmp"] = RTMPStream(self.session, { + "rtmp": RTMP_URL.format(stream["id"]), + "pageUrl": self.url, + "live": True + }) + + return streams + + return + +__plugin__ = Piczel
Piczel.tv support This is [something I requested](https://github.com/chrippa/livestreamer/issues/1205) when this was livestreamer, and the author made a little headway in determining that it defaults to HTTP-DASH but there's also a HLS stream available. I've since switched over to streamlink.
Try this: https://raw.githubusercontent.com/intact/livestreamer/fe7bd9fc6ba50450e57af6dcd76cfe2400fb5ddc/src/livestreamer/plugins/piczel.py But change every instance of "livestreamer" into "streamlink" Yeah, I got the notification when they posted it on the linked issue. I'll let you know how it goes the next time I watch something on Piczel.
2016-11-01T22:51:40
streamlink/streamlink
121
streamlink__streamlink-121
[ "106" ]
d20d1a62b53fc49aab6c9df3bc52020ee77ae607
diff --git a/src/streamlink/plugins/livecodingtv.py b/src/streamlink/plugins/livecodingtv.py --- a/src/streamlink/plugins/livecodingtv.py +++ b/src/streamlink/plugins/livecodingtv.py @@ -1,12 +1,20 @@ import re from streamlink.plugin import Plugin +from streamlink.stream import HLSStream from streamlink.stream import RTMPStream, HTTPStream from streamlink.plugin.api import http -_vod_re = re.compile('\"(http(s)?://.*\.mp4\?t=.*)\"') -_rtmp_re = re.compile('rtmp://[^"]+/(?P<channel>\w+)+[^/"]+') -_url_re = re.compile('http(s)?://(?:\w+.)?\livecoding\.tv') +_streams_re = re.compile(r""" + src:\s+"( + rtmp://.*?\?t=.*?| # RTMP stream + https?://.*?playlist.m3u8.*?\?t=.*?| # HLS stream + https?://.*?manifest.mpd.*?\?t=.*?| # DASH stream + https?://.*?.mp4\?t=.*? # HTTP stream + )".*? + type:\s+"(.*?)" # which stream type it is + """, re.M | re.DOTALL | re.VERBOSE) +_url_re = re.compile(r"http(s)?://(?:\w+\.)?livecoding\.tv") class LivecodingTV(Plugin): @@ -16,18 +24,19 @@ def can_handle_url(cls, url): def _get_streams(self): res = http.get(self.url) - match = _rtmp_re.search(res.content.decode('utf-8')) - if match: - params = { - "rtmp": match.group(0), - "pageUrl": self.url, - "live": True, - } - yield 'live', RTMPStream(self.session, params) - return - - match = _vod_re.search(res.content.decode('utf-8')) - if match: - yield 'vod', HTTPStream(self.session, match.group(1)) + match = _streams_re.findall(res.content.decode('utf-8')) + for url, stream_type in match: + if stream_type == "rtmp/mp4" and RTMPStream.is_usable(self.session): + params = { + "rtmp": url, + "pageUrl": self.url, + "live": True, + } + yield 'live', RTMPStream(self.session, params) + elif stream_type == "application/x-mpegURL": + for s in HLSStream.parse_variant_playlist(self.session, url).items(): + yield s + elif stream_type == "video/mp4": + yield 'vod', HTTPStream(self.session, url) __plugin__ = LivecodingTV
Plugin LivecodingTV fails to load on Python 3.6.0b2 on Windows 10 x64 Just running streamlink raises the following error on my system with a fresh install: ``` C:\WINDOWS\system32>streamlink Failed to load plugin livecodingtv: File "c:\program files\python36\lib\imp.py", line 234, in load_module return load_source(name, filename, file) File "c:\program files\python36\lib\imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 675, in _load File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 677, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "c:\program files\python36\lib\site-packages\streamlink\plugins\livecodingtv.py", line 9, in <module> _url_re = re.compile('http(s)?://(?:\w+.)?\livecoding\.tv') File "c:\program files\python36\lib\re.py", line 233, in compile return _compile(pattern, flags) File "c:\program files\python36\lib\re.py", line 301, in _compile p = sre_compile.compile(pattern, flags) File "c:\program files\python36\lib\sre_compile.py", line 562, in compile p = sre_parse.parse(p, flags) File "c:\program files\python36\lib\sre_parse.py", line 856, in parse p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False) File "c:\program files\python36\lib\sre_parse.py", line 415, in _parse_sub itemsappend(_parse(source, state, verbose)) File "c:\program files\python36\lib\sre_parse.py", line 501, in _parse code = _escape(source, this, state) File "c:\program files\python36\lib\sre_parse.py", line 401, in _escape raise source.error("bad escape %s" % escape, len(escape)) sre_constants.error: bad escape \l at position 20 usage: streamlink [OPTIONS] [URL] [STREAM] Use -h/--help to see the available options or read the manual at http://docs.streamlink.io/ C:\WINDOWS\system32>python --version Python 3.6.0b2 ```
change https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugins/livecodingtv.py#L9 to ``` _url_re = re.compile(r"http(s)?://(?:\w+\.)?livecoding\.tv") ```
2016-11-03T11:00:54
streamlink/streamlink
122
streamlink__streamlink-122
[ "120" ]
d20d1a62b53fc49aab6c9df3bc52020ee77ae607
diff --git a/src/streamlink/plugin/api/http_session.py b/src/streamlink/plugin/api/http_session.py --- a/src/streamlink/plugin/api/http_session.py +++ b/src/streamlink/plugin/api/http_session.py @@ -66,9 +66,34 @@ def __init__(self, *args, **kwargs): self.mount("http://", HTTPAdapterWithReadTimeout()) self.mount("https://", HTTPAdapterWithReadTimeout()) + @classmethod + def determine_json_encoding(cls, sample): + """ + Determine which Unicode encoding the JSON text sample is encoded with + + RFC4627 (http://www.ietf.org/rfc/rfc4627.txt) suggests that the encoding of JSON text can be determined + by checking the pattern of NULL bytes in first 4 octets of the text. + :param sample: a sample of at least 4 bytes of the JSON text + :return: the most likely encoding of the JSON text + """ + nulls_at = [i for i, j in enumerate(bytearray(sample[:4])) if j == 0] + if nulls_at == [0, 1, 2]: + return "UTF-32BE" + elif nulls_at == [0, 2]: + return "UTF-16BE" + elif nulls_at == [1, 2, 3]: + return "UTF-32LE" + elif nulls_at == [1, 3]: + return "UTF-16LE" + else: + return "UTF-8" + @classmethod def json(cls, res, *args, **kwargs): """Parses JSON from a response.""" + # if an encoding is already set then use the provided encoding + if res.encoding is None: + res.encoding = cls.determine_json_encoding(res.content[:4]) return parse_json(res.text, *args, **kwargs) @classmethod
diff --git a/tests/test_plugin_api_http_session.py b/tests/test_plugin_api_http_session.py --- a/tests/test_plugin_api_http_session.py +++ b/tests/test_plugin_api_http_session.py @@ -1,5 +1,13 @@ +# coding=utf-8 import unittest +import requests + +try: + from unittest.mock import patch, PropertyMock +except ImportError: + from mock import patch, PropertyMock + from streamlink.exceptions import PluginError from streamlink.plugin.api.http_session import HTTPSession @@ -16,5 +24,26 @@ def stream_data(): self.assertRaises(PluginError, stream_data) + def test_json_encoding(self): + json_str = u"{\"test\": \"Α and Ω\"}" + + # encode the json string with each encoding and assert that the correct one is detected + for encoding in ["UTF-32BE", "UTF-32LE", "UTF-16BE", "UTF-16LE", "UTF-8"]: + with patch('requests.Response.content', new_callable=PropertyMock) as mock_content: + mock_content.return_value = json_str.encode(encoding) + res = requests.Response() + + self.assertEqual(HTTPSession.json(res), {u"test": u"\u0391 and \u03a9"}) + + def test_json_encoding_override(self): + json_text = u"{\"test\": \"Α and Ω\"}".encode("cp949") + + with patch('requests.Response.content', new_callable=PropertyMock) as mock_content: + mock_content.return_value = json_text + res = requests.Response() + res.encoding = "cp949" + + self.assertEqual(HTTPSession.json(res), {u"test": u"\u0391 and \u03a9"}) + if __name__ == "__main__": unittest.main()
Non unicode escaped API breaks the plugin I have a problem on Streamlink 0.0.2 with Twitch plugin. Luckily I figured out what's going on and fixed my own copy of code. So I would like to share my fix though I am not sure with my decision. My question is: > Is it safe to assume that JSON APIs other than Twitch, use particular text encoding? Here is some error log. ``` > streamlink.exe --player <some my player> --twitch-oauth-token <redacted> https://twitch.tv/<readacted> source [cli][info] Found matching plugin twitch for URL https://twitch.tv/<readacted> [plugin.twitch][info] Attempting to authenticate using OAuth token error: 'cp949' codec can't encode character '\u011b' in position 48: illegal multibyte sequence ``` Little backgrounds. 1. Twitch API does not escape 'non-ascii' characters. 2. Twitch API does not state `charset` in the `Content-type` header. Only states MIME type `application/json`. 3. I am running Korean version of Windows 10, and the plugin tries to decode response body with OS default encoding(presumably) which is CP949 in my case. Let me follow the code flow. 1. Twitch plugin tries to authenticate with my OAuth token, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L264 2. ...which is `user` method in helper class, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L208 3. ...which requests API with GET method, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L167 4. I know Twitch API returns in JSON format, so going https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L182 5. ...which tries to parse response body text in JSON, implicitly tries to decode response body from bytes to str, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugin/api/http_session.py#L70 I could simply edit `http_session.py` and fix it by stating 'known' charset before accessing `text` property, something like: ``` + if res.encoding is None: + res.encoding = 'utf8' return parse_json(res.text, *args, **kwargs) ```
I guess #19 is related. Because it also happened to me with Livestreamer.
2016-11-03T13:26:49
streamlink/streamlink
125
streamlink__streamlink-125
[ "82" ]
127ac26eb6823e030cf4223016e91aa66717e743
diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py --- a/src/streamlink/plugins/twitch.py +++ b/src/streamlink/plugins/twitch.py @@ -1,3 +1,4 @@ +# coding=utf-8 import re import requests @@ -214,7 +215,7 @@ def videos(self, video_id, **params): def viewer_info(self, **params): return self.call("/api/viewer/info", **params) - def hosted_channel(self, **params): + def hosted_channel(self, **params): return self.call_subdomain("tmi", "/hosts", format="", **params) @@ -244,6 +245,7 @@ def __init__(self, url): self.subdomain = match.get("subdomain") self.video_type = match.get("video_type") self.video_id = match.get("video_id") + self._hosted_chain = [] parsed = urlparse(url) self.params = parse_query(parsed.query) @@ -389,6 +391,7 @@ def _create_video_clip(self, chunks, start_offset, stop_offset): tags=playlist_tags, duration=playlist_duration) def _get_video_streams(self): + self.logger.debug("Getting video steams for {} (type={})".format(self.video_id, self.video_type)) self._authenticate() if self.video_type == "b": @@ -435,22 +438,34 @@ def _check_for_host(self): host_info = self.api.hosted_channel(include_logins=1, host=channel_id).json()["hosts"][0] if "target_login" in host_info: self.logger.info("{0} is hosting {1}".format(self.channel, host_info["target_login"])) - self.channel = host_info["target_login"] - return True - return False + return host_info["target_login"] def _get_hls_streams(self, type="live"): + self.logger.debug("Getting {} HLS streams for {}".format(type, self.channel)) self._authenticate() - if self._check_for_host() and self.options.get("disable_hosting"): + hosted_channel = self._check_for_host() + if hosted_channel and self.options.get("disable_hosting"): self.logger.info("hosting was disabled by command line option") return {} - else: - self.logger.info("switching to {}", self.channel) + elif hosted_channel: + self.logger.info("switching to {}", hosted_channel) + if hosted_channel in self._hosted_chain: + self._hosted_chain.append(hosted_channel) + self.logger.error(u"A loop of hosted channels has been detected, " + "cannot find a playable stream. ({})".format(u" -> ".join(self._hosted_chain))) + return {} + self._hosted_chain.append(hosted_channel) + self.channel = hosted_channel + return self._get_hls_streams(type) + sig, token = self._access_token(type) if type == "live": url = self.usher.channel(self.channel, sig=sig, token=token) elif type == "video": url = self.usher.video(self.video_id, nauthsig=sig, nauth=token) + else: + self.logger.debug("Unknown HLS stream type: {}".format(type)) + return {} try: streams = HLSStream.parse_variant_playlist(self.session, url) diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -403,9 +403,9 @@ def fetch_streams_infinite(plugin, interval): if not streams: console.logger.info("Waiting for streams, retrying every {0} " - "second(s)", args.retry_streams) + "second(s)", interval) while not streams: - sleep(args.retry_streams) + sleep(interval) try: streams = fetch_streams(plugin)
retry-streams overrides twitch-disable-hosting When using both arguments `--retry-streams DELAY` and `--twitch-disable-hosting`, on the first retry streams are switched to the hosted stream anyway. Instead, streamlink should keep retrying without streaming the hosted stream.
I'm from Brazil, as I install streamlink in windows 7? @veludo32 Please don't spam multiple issues/unrelated issues.
2016-11-04T13:31:02
streamlink/streamlink
130
streamlink__streamlink-130
[ "128" ]
28d673756c1556c6c0795be884e22641b0997254
diff --git a/src/streamlink/plugins/goodgame.py b/src/streamlink/plugins/goodgame.py --- a/src/streamlink/plugins/goodgame.py +++ b/src/streamlink/plugins/goodgame.py @@ -4,7 +4,7 @@ from streamlink.plugin.api import http from streamlink.stream import HLSStream -HLS_URL_FORMAT = "http://hls.goodgame.ru/hls/{0}{1}.m3u8" +HLS_URL_FORMAT = "https://hls.goodgame.ru/hls/{0}{1}.m3u8" QUALITIES = { "1080p": "", "720p": "_720", @@ -12,13 +12,8 @@ "240p": "_240" } -_url_re = re.compile("http://(?:www\.)?goodgame.ru/channel/(?P<user>\w+)") -_stream_re = re.compile( - "meta property=\"og:video:iframe\" content=\"http://goodgame.ru/player/html\?(\w+)\"" -) -_ddos_re = re.compile( - "document.cookie=\"(__DDOS_[^;]+)" -) +_url_re = re.compile("https://(?:www\.)?goodgame.ru/channel/(?P<user>\w+)") +_stream_re = re.compile(r'var src = "([^"]+)";') class GoodGame(Plugin): @classmethod @@ -36,11 +31,6 @@ def _get_streams(self): } 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
Goodgame moved to the new version of the site Goodgame moved to the new version of the site (https://github.com/chrippa/livestreamer/issues/1513 ; https://github.com/chrippa/livestreamer/issues/1518 ; https://github.com/chrippa/livestreamer/pull/1527). Fix the plugin please.
2016-11-06T18:47:08
streamlink/streamlink
135
streamlink__streamlink-135
[ "127" ]
ec64ee2a142535054d2256e26d35655c911559ed
diff --git a/src/streamlink/plugins/younow.py b/src/streamlink/plugins/younow.py --- a/src/streamlink/plugins/younow.py +++ b/src/streamlink/plugins/younow.py @@ -6,7 +6,7 @@ from streamlink.plugin.api import http from streamlink.stream import RTMPStream -jsonapi= "http://www.younow.com/php/api/broadcast/info/curId=0/user=" +jsonapi= "https://api.younow.com/php/api/broadcast/info/curId=0/user=" # http://younow.com/channel/ _url_re = re.compile("http(s)?://(\w+.)?younow.com/(?P<channel>[^/&?]+)")
younow.com is broken They have changed the API url to this one: `https://api.younow.com/php/api/broadcast/info/curId=0/user=` in: https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugins/younow.py#L9 It still needs rtmpdump.exe, so it will give you the following error, related to #56 `[cli][error] Could not open stream: Unable to find rtmpdump.exe command` #81 fixes it, and the plugin works fine.
@beardypig Can you make a pull request for this too? I'm not a github expert, so I don't know how to do it, but the proposed modification fixes the plugin. @stevek123 will do :-)
2016-11-07T09:07:24
streamlink/streamlink
141
streamlink__streamlink-141
[ "140" ]
9adeec109de143a883903bdc7c134eff571eaeb0
diff --git a/src/streamlink/plugins/euronews.py b/src/streamlink/plugins/euronews.py --- a/src/streamlink/plugins/euronews.py +++ b/src/streamlink/plugins/euronews.py @@ -1,46 +1,77 @@ import re -from itertools import chain - -from streamlink.compat import urlparse from streamlink.plugin import Plugin from streamlink.plugin.api import http +from streamlink.plugin.api import validate from streamlink.stream import HLSStream, HTTPStream -from streamlink.plugin.api.support_plugin import common_jwplayer as jwplayer - -_url_re = re.compile("http(s)?://(\w+\.)?euronews.com") - class Euronews(Plugin): - @classmethod - def can_handle_url(self, url): - return _url_re.match(url) + _url_re = re.compile("http(?:s)?://(\w+)\.?euronews.com/(live|.*)") + _re_vod = re.compile(r'<meta\s+property="og:video"\s+content="(http.*?)"\s*/>') + _live_api_url = "http://fr.euronews.com/api/watchlive.json" + _live_schema = validate.Schema({ + u"url": validate.url() + }) + _stream_api_schema = validate.Schema({ + u'status': u'ok', + u'primary': { + validate.text: { + validate.optional(u'hls'): validate.url(), + validate.optional(u'rtsp'): validate.url(scheme="rtsp") + } + }, + validate.optional(u'backup'): { + validate.text: { + validate.optional(u'hls'): validate.url(), + validate.optional(u'rtsp'): validate.url(scheme="rtsp") + } + } + }) - def _create_stream(self, source): - url = source["file"] + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) - if urlparse(url).path.endswith("m3u8"): - streams = HLSStream.parse_variant_playlist(self.session, url) + def _get_vod_stream(self): + """ + Find the VOD video url + :return: video url + """ + res = http.get(self.url) + video_urls = self._re_vod.findall(res.text) + if len(video_urls): + return dict(vod=HTTPStream(self.session, video_urls[0])) - # TODO: Replace with "yield from" when dropping Python 2. - for stream in streams.items(): - yield stream - else: - name = source.get("label", "vod") - yield name, HTTPStream(self.session, url) + def _get_live_streams(self, language): + """ + Get the live stream in a particular language + :param language: + :return: + """ + res = http.get(self._live_api_url) + live_res = http.json(res, schema=self._live_schema) + api_res = http.get(live_res[u"url"]) + stream_data = http.json(api_res, schema=self._stream_api_schema) + # find the stream in the requested language + if language in stream_data[u'primary']: + playlist_url = stream_data[u'primary'][language][u"hls"] + return HLSStream.parse_variant_playlist(self.session, playlist_url) def _get_streams(self): - res = http.get(self.url) - playlist = jwplayer.parse_playlist(res) - if not playlist: - return + """ + Find the streams for euronews + :return: + """ + match = self._url_re.match(self.url) + language, path = match.groups() - for item in playlist: - streams = map(self._create_stream, item["sources"]) + # remap domain to language (default to english) + language = {"www": "en", "": "en", "arabic": "ar"}.get(language, language) - # TODO: Replace with "yield from" when dropping Python 2. - for stream in chain.from_iterable(streams): - yield stream + if path == "live": + return self._get_live_streams(language) + else: + return self._get_vod_stream() __plugin__ = Euronews
Euronews plugin broken I dig up EuroNews plugin which is broken since December 2014. https://github.com/chrippa/livestreamer/issues/626
Good job!
2016-11-08T16:16:36
streamlink/streamlink
152
streamlink__streamlink-152
[ "151" ]
e2af160c50281e7f3fd20035bf5d5baa9c9d4245
diff --git a/src/streamlink/plugins/connectcast.py b/src/streamlink/plugins/connectcast.py --- a/src/streamlink/plugins/connectcast.py +++ b/src/streamlink/plugins/connectcast.py @@ -18,7 +18,7 @@ def _get_streams(self): url_match = _url_re.match(self.url) stream_url = _stream_url.format(channel=url_match.group(1)) res = self.session.http.get(stream_url) - match = _stream_re.search(res.content) + match = _stream_re.search(res.text) if match: params = dict(rtmp="rtmp://stream.connectcast.tv/live", playpath=match.group(1),
Connectcast: can't use a string pattern on a bytes-like object ``` Traceback (most recent call last): File "/usr/bin/streamlink", line 11, in <module> load_entry_point('streamlink==0.0.2', 'console_scripts', 'streamlink')() File "/usr/lib/python3.4/site-packages/streamlink_cli/main.py", line 899, in m ain handle_url() File "/usr/lib/python3.4/site-packages/streamlink_cli/main.py", line 479, in h andle_url streams = fetch_streams(plugin) File "/usr/lib/python3.4/site-packages/streamlink_cli/main.py", line 392, in f etch_streams sorting_excludes=args.stream_sorting_excludes) File "/usr/lib/python3.4/site-packages/streamlink/plugin/plugin.py", line 316, in get_streams return self.streams(*args, **kwargs) File "/usr/lib/python3.4/site-packages/streamlink/plugin/plugin.py", line 230, in streams ostreams = self._get_streams() File "/usr/lib/python3.4/site-packages/streamlink/plugins/connectcast.py", lin e 21, in _get_streams match = _stream_re.search(res.content) TypeError: can't use a string pattern on a bytes-like object ```
That's my bad...
2016-11-11T15:27:30
streamlink/streamlink
154
streamlink__streamlink-154
[ "138" ]
3aac695039ce2d35fb447e1c1d3ff9769f593c82
diff --git a/src/streamlink/plugins/zdf_mediathek.py b/src/streamlink/plugins/zdf_mediathek.py --- a/src/streamlink/plugins/zdf_mediathek.py +++ b/src/streamlink/plugins/zdf_mediathek.py @@ -2,9 +2,11 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate -from streamlink.stream import HDSStream, HLSStream, RTMPStream +from streamlink.stream import HDSStream, HLSStream +from streamlink.plugin.api.utils import parse_query + +API_URL = "https://api.zdf.de" -API_URL = "http://www.zdf.de/ZDFmediathek/xmlservice/web/beitragsDetails" QUALITY_WEIGHTS = { "hd": 720, "veryhigh": 480, @@ -12,6 +14,7 @@ "med": 176, "low": 112 } + STREAMING_TYPES = { "h264_aac_f4f_http_f4m_http": ( "HDS", HDSStream.parse_manifest @@ -22,25 +25,43 @@ } _url_re = re.compile(""" - http(s)?://(\w+\.)?zdf.de/zdfmediathek(\#)?/.+ - /(live|video) - /(?P<video_id>\d+) + http(s)?://(\w+\.)?zdf.de/ """, re.VERBOSE | re.IGNORECASE) -_schema = validate.Schema( - validate.xml_findall("video/formitaeten/formitaet"), - [ - validate.union({ - "type": validate.get("basetype"), - "quality": validate.xml_findtext("quality"), - "url": validate.all( - validate.xml_findtext("url"), - validate.url() - ) - }) - ] +_documents_schema = validate.Schema( + { + "mainVideoContent": { + "http://zdf.de/rels/target": { + "http://zdf.de/rels/streams/ptmd": validate.text + }, + }, + } ) +_schema = validate.Schema( + { + "priorityList": [ + { + "formitaeten": [ + { + "type": validate.text, + "qualities": [ + { + "audio": { + "tracks": [ + { + "uri": validate.text + } + ] + } + } + ] + } + ] + } + ] + } +) class zdf_mediathek(Plugin): @classmethod @@ -55,40 +76,35 @@ def stream_weight(cls, key): return Plugin.stream_weight(key) - def _create_rtmp_stream(self, url): - return RTMPStream(self.session, { - "rtmp": self._get_meta_url(url), - "pageUrl": self.url, - }) - - def _get_meta_url(self, url): - res = http.get(url, exception=IOError) - root = http.xml(res, exception=IOError) - return root.findtext("default-stream-url") - def _get_streams(self): match = _url_re.match(self.url) - video_id = match.group("video_id") - res = http.get(API_URL, params=dict(ak="web", id=video_id)) - fmts = http.xml(res, schema=_schema) + title = self.url.rsplit('/', 1)[-1] + if title.endswith(".html"): + title = title[:-5] + + request_url = "https://api.zdf.de/content/documents/%s.json?profile=player" % title + res = http.get(request_url, headers={"Api-Auth" : "Bearer d2726b6c8c655e42b68b0db26131b15b22bd1a32"}) + document = http.json(res, schema=_documents_schema) + + stream_request_url = document["mainVideoContent"]["http://zdf.de/rels/target"]["http://zdf.de/rels/streams/ptmd"] + stream_request_url = API_URL + stream_request_url + + res = http.get(stream_request_url) + res = http.json(res, schema=_schema) + formatList = res["priorityList"]["formitaeten"] streams = {} - for fmt in fmts: - if fmt["type"] in STREAMING_TYPES: - name, parser = STREAMING_TYPES[fmt["type"]] - try: - streams.update(parser(self.session, fmt["url"])) - except IOError as err: - self.logger.error("Failed to extract {0} streams: {1}", - name, err) - - elif fmt["type"] == "h264_aac_mp4_rtmp_zdfmeta_http": - name = fmt["quality"] - try: - streams[name] = self._create_rtmp_stream(fmt["url"]) - except IOError as err: - self.logger.error("Failed to extract RTMP stream '{0}': {1}", - name, err) + for format_ in formatList: + if format_["type"] in STREAMING_TYPES: + name, parser = STREAMING_TYPES[format_["type"]] + for quality in format_["qualities"]: + tracks = quality["audio"]["tracks"] + for track in tracks: + try: + streams.update(parser(self.session, track["uri"])) + except IOError as err: + self.logger.error("Failed to extract {0} streams: {1}", + name, err) return streams
ZDF Mediathek-Plugin not working anymore The ZDF Mediathek got a relaunch with a change of url structure and a new API. The plugin needs to be adapated to meet the changed platform. As I am an avid user of this plugin myself, I will definitely take a look into it, but it might take awhile as I never wrote one before. Is the original developer of this plugin present by chance?
> Is the original developer of this plugin present by chance? https://github.com/streamlink/streamlink/blame/master/src/streamlink/plugins/zdf_mediathek.py @skulblakka I hope you don't mind me pinging you here 😄 Oh, could have looked that up myself - sorry. Didnt take a look at the existing plugin yet, cause i reckon you can't reuse much of it. @bastimeyer I don't mind ;) I basically know how to get the streams and everything however I can't wrap my head around the validation stuff @chrippa implemented into the plugins (that wasn't there when I made the original ZDF plugin).
2016-11-11T18:03:39
streamlink/streamlink
163
streamlink__streamlink-163
[ "147" ]
878ec58e93292a31068c57b3de7db953cf137c8a
diff --git a/src/streamlink/plugins/cybergame.py b/src/streamlink/plugins/cybergame.py --- a/src/streamlink/plugins/cybergame.py +++ b/src/streamlink/plugins/cybergame.py @@ -5,6 +5,7 @@ from streamlink.plugin.api import http, validate from streamlink.stream import RTMPStream +LIVE_STREAM_URL = "rtmp://stream1.cybergame.tv:2936/live/" PLAYLIST_URL = "http://api.cybergame.tv/p/playlist.smil" _url_re = re.compile(""" @@ -46,7 +47,7 @@ class Cybergame(Plugin): @classmethod - def can_handle_url(self, url): + def can_handle_url(cls, url): return _url_re.match(url) def _get_playlist(self, **params): @@ -75,6 +76,10 @@ def _get_streams(self): if video_id: return self._get_playlist(vod=video_id) elif channel: - return self._get_playlist(channel=channel) + return {'live': RTMPStream( + self.session, + dict(rtmp=LIVE_STREAM_URL, app="live", pageUrl=self.url, playpath=channel, live=True) + )} + __plugin__ = Cybergame
cybergame.tv plugin not work for livestreams `[cli][info] Found matching plugin cybergame for URL http://cybergame.tv/sharkisfinetoo/` `[cli][info] Available streams: 720p (worst, best)` `[cli][info] Opening stream: 720p (rtmp)` `[cli][error] No data returned from stream` For stream `http://cybergame.tv/<channel>` Internet Download Manager produces a link like `rtmp://cybergametv.cdnvideo.ru/cybergame//<channel>` VODs fine.
Does that stream URL work? I could not get it to work. With some wiresharking I managed to get it working with `rtmp://stream1.cybergame.tv:2936/live/<channel>`. @beardypig Sorry. Your is work. My no longer works(yesterday works). OK, that's weird ... maybe they change it frequently? I found the RTMP URL in the end, it was in `http://api.cybergame.tv/p/embed.php?c=<channel>&type=embed&w=100pc&h=100pc&auto=true&advforced=true&nick=` eg. http://api.cybergame.tv/p/embed.php?c=op-mizantrop&type=embed&w=100pc&h=100pc&auto=true&advforced=true&nick= ![111](https://cloud.githubusercontent.com/assets/14862821/20174529/acb3f8d8-a757-11e6-86ee-b605e7034cf4.JPG) - maybe it help? (view-source:http://api.cybergame.tv/p/embed.php?c=ebrellika&type=embed&w=100pc&h=100pc&auto=true&advforced=true) That's what i was referring to :) Sorry. Now I understood. I do not know much English:) No problem :D I will check it over the next few days as see if it changes, and make the necessary changes to the plugin. OK! Thanks!
2016-11-14T14:57:40
streamlink/streamlink
185
streamlink__streamlink-185
[ "182" ]
96c0bfa3b862bacb89286f158ee0f45ed75bee30
diff --git a/src/streamlink/plugins/livestream.py b/src/streamlink/plugins/livestream.py --- a/src/streamlink/plugins/livestream.py +++ b/src/streamlink/plugins/livestream.py @@ -22,7 +22,10 @@ ), }, None) }, - validate.optional("playerUri"): validate.text + validate.optional("playerUri"): validate.text, + validate.optional("viewerPlusSwfUrl"): validate.url(scheme="http"), + validate.optional("lsPlayerSwfUrl"): validate.text, + validate.optional("hdPlayerSwfUrl"): validate.text }) _smil_schema = validate.Schema(validate.union({ "http_base": validate.all( @@ -93,7 +96,7 @@ def _get_streams(self): play_url = stream_info.get("play_url") if play_url: - swf_url = info.get("playerUri") + swf_url = info.get("playerUri") or info.get("hdPlayerSwfUrl") or info.get("lsPlayerSwfUrl") or info.get("viewerPlusSwfUrl") if swf_url: if not swf_url.startswith("http"): swf_url = "http://" + swf_url
Plugin for Livestream.com not working right? exit's quickly for hls and not at all for normal streams I am trying to get a live stream on livestreamer.com to work and i can't get it to play more then about 35 seconds... When I run this command: streamlink "http://livestream.com/Miraclenet/events/5004281" 270p --fifo --player omxplayer it gives me an error about an swf being needed. When I run this command: streamlink "http://livestream.com/Miraclenet/events/5004281" 270p_hls --fifo --player omxplayer it will play the stream but just for about 35 seconds or so... I kinda don't want to have to restart it every 35 seconds to watch this stream... I'd like it to run until I stop it myself... Any help for this non-python, non-linux guy would be very helpful... btw, this is running on a Raspberry Pi. Just got a nice little 7 inch lcd for it and set it up on my desk to be able to watch it while I work, but can't get it to play for long at a time... (edited to correct commands used)
A little additional information if it helps... With the HLS stream, after about 35 seconds and it stops the text output on the command line says that the stream has ended... ... For starters, this is the **streamlink** issue tracker; your original post commands seem to reference _livestreamer_: > livestreamer "http://livestream.com/Miraclenet/events/5004281" 270p --fifo --player omxplayer > (snip) > livestreamer "http://livestream.com/Miraclenet/events/5004281" 270p_hls --fifo --player omxplayer If those are typos and you indeed meant "streamlink", then this is surely a duplicate of your previous #101 FWIW, I don't own a Pi to test, but on Windows (Vista SP2 x86): `streamlink -o "Miraclenet_270.ts" "http://livestream.com/Miraclenet/events/5004281" 270p` => ``` [Streamlink for Windows] [cli][info] Found matching plugin livestream for URL http://livestream.com/Mirac lenet/events/5004281 [cli][info] Available streams: 270p_hls, 486p_hls, 432p_hls, 270p (worst), 432p, 486p (best) [cli][info] Opening stream: 270p (akamaihd) [cli][error] Could not open stream: A SWF URL is required to create session token ``` so this must be an issue with the plugin itself; the SWF URL on that page is: `https://cdn.livestream.com/swf/LSPlayer.swf` The POST request on my browser is: `https://livestream-f.akamaihd.net/control/18265544_5004281_lsi8gash3zeu6woo8ja_1_678@25357?cmd=sendingNewToken&v=3.8.0.52&r=CVLHK&g=GPGJOYRSKNUS&lvl1=0,10,0.75,0,0,NaN,0,0,1,678,0,1479661942.435,0,0,0,0,5955,NaN,0,0,0,4628,u,false&swf=https%3A//cdn.livestream.com/swf/LSPlayer.swf` Unless the non-hls streams are fixed by a dev in the know, switch to the hls ones, as suggested to you... Using latest streamlink code snapshot (git-96c0bfa), 270p_hls variant is dumped without interruptions: `streamlink -o "Miraclenet_270.ts" "http://livestream.com/Miraclenet/events/5004281" 270p_hls` => ``` [Streamlink for Windows] [cli][info] Found matching plugin livestream for URL http://livestream.com/Mirac lenet/events/5004281 [cli][info] Available streams: 486p_hls, 270p_hls, 432p_hls, 270p (worst), 432p, 486p (best) [cli][info] Opening stream: 270p_hls (hls) File Miraclenet_270.ts already exists! Overwrite it? [y/N] y [download][Miraclenet_270.ts] Written 6.3 MB (3m3s @ 30.6 KB/s) ``` Here it is being played back in a Windows player: ![miraclenet_270p_hls](https://cloud.githubusercontent.com/assets/9669492/20464819/c8aaeb16-af57-11e6-84f7-48ddf87637d1.jpg) So maybe the stream interruption you observe is related to Raspbian and/or omxplayer... Sorry I couldn't help more... yes, that livestreamer part was a typo because that's what I used to use and I was away for a while taking care of some family business (My mother had past and I had to travel half way around the world almost, to help take care of some things and with one of the memorial services for her)... and yes, I had closed that previous report because I got it to be playing for a short period of time and that was enough for then (about 35 seconds)... When you play the stream in windows media player with streamlink, how long will it play for? did you use mostly the same command as me but changing the player? I think this is due to a regression in livestream #1277 - see my updated comment there: https://github.com/chrippa/livestreamer/pull/1277#issuecomment-237193950 It's now been fixed by @intact on livestream (amazingly fast work, beat me to it!), so hopefully will be here soon. @Junior1544 Very sorry for your loss; my most sincere condolences... The screenshot I posted was of a player (MPC-BE) playing back a downloaded .ts file - I, mostly, first download and then watch. But I did try to use the "-p" switch to feed the stream in real time to VLC.exe and (although VLC did not display stream duration) the stream managed to play continuously for at least 5min, when I exited the player... (BTW, when MPC-HC 1.7.10, latest stable release, was tried, only the audio part of the stream was played back, with no video at all!). So, I guess, the hls streams look OK here... EDIT: I managed to pipe the hls live stream to MPC-BE (that shows played stream duration), as you can see it was at 02:24 when the screenshot was taken: ![mpcbe](https://cloud.githubusercontent.com/assets/9669492/20465238/931cf868-af61-11e6-9698-5cda22a442a2.jpg) I just manually applied @intact's livestreamer changes (mentioned above) to streamlink's livestream.py, and can confirm @intact's fix works on streamlink too for non-HLS streams (thanks!). HLS streams stop after a minute or so still. @intact do you mind if we pull your patch for livestreamer in to streamlink? I just did the code changes in my livestream.py that was in @intact's patch, and it seems to be working at about 4 minutes now... so much better then the 35 seconds I was getting before... I'm hoping it'll run for at least half an hour before stopping because that I can deal with! I really hope this can be put into the next releases of the code base here because it'll make it so much easier to update to the next release of streamlink... If I knew how, push the code in here myself, but i'm just barely learning the github system here and really don't know linux much yet... still very much a newbie here! Thank you all for all your help and i'll post again once I have a better idea of how long this will run for before stopping on it's own... --James ok, it's been running for almost 3 hours now without problem! Thank you guys for pointing me to the right solution for this problem! maybe there can be an hls solution somewhere, but this is working great for me! Thank you! --James Since no-one in this thread felt the need to comment, despite me posting screenshots, does any of the developers have any clue as to why the livestream hls stream seems to function properly here (no interruptions), whereas both the original poster (@Junior1544) and @stevekmcc experience sudden terminations (the former after 35secs, the latter after 1min or so)? Does streamlink (or the embedded Python 3.5.2) behave differently on Windows 32bit? BTW, in one other experiment, I left the "MiracleNet" stream going on, it was still strong at 02h03min56sec when the following shot was taken: ![mpc-be](https://cloud.githubusercontent.com/assets/9669492/20467535/57eb414c-af92-11e6-8edb-199833b4ded3.jpg) Just being curious, that's all :smile: Well, I'm using this on a raspberry pi and it's using python 2.7 i believe... I don't know if that'll make any difference but just wanted to let you know... raspberry pi B+, Raspbian Jessie up to date, python 2.7, omxplayer. HLS streams probably haven't worked for months (at least they didn't in April nor now). I've attached debug output for an HLS run,with time logged at the start and end. [hls.txt](https://github.com/streamlink/streamlink/files/602516/hls.txt) I can't reproduce the '35 seconds bug' in both Python 2.7 and Python 3.5.2 maybe it depends on OS or Player (like @Vangelis66 say) ? In my case im using Windows 10
2016-11-21T09:41:11
streamlink/streamlink
191
streamlink__streamlink-191
[ "190" ]
1ad9b9a81e7b2f12e0a62a896c1ea7ffa81228ac
diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -533,7 +533,7 @@ def authenticate_twitch_oauth(): access to their Twitch account.""" client_id = TWITCH_CLIENT_ID - redirect_uri = "http://streamlink.tanuki.se/en/develop/twitch_oauth.html" + redirect_uri = "https://streamlink.github.io/twitch_oauth.html" url = ("https://api.twitch.tv/kraken/oauth2/authorize/" "?response_type=token&client_id={0}&redirect_uri=" "{1}&scope=user_read+user_subscriptions").format(client_id, redirect_uri)
Error with using --twitch-oauth-authenticate Using that causes a browser to open to http://livestreamer.tanuki.se/en/develop/twitch_oauth.html?error=redirect_mismatch&error_description=Parameter+redirect_uri+does+not+match+registered+URI In the main.py file this link is show http://streamlink.tanuki.se/en/develop/twitch_oauth.html when it should link to this https://streamlink.github.io/twitch_oauth.html https://github.com/streamlink/streamlink/blob/master/src/streamlink_cli/main.py#L536 https://github.com/streamlink/streamlink/issues/4#issuecomment-261737748
2016-11-22T00:42:13
streamlink/streamlink
204
streamlink__streamlink-204
[ "192" ]
1606f94d7c751ef5d4df1aaa04f1a3784e19f9ef
diff --git a/src/streamlink/plugins/nhkworld.py b/src/streamlink/plugins/nhkworld.py --- a/src/streamlink/plugins/nhkworld.py +++ b/src/streamlink/plugins/nhkworld.py @@ -4,42 +4,28 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate -from streamlink.stream import HDSStream +from streamlink.stream import HLSStream -API_URL = "http://api.sh.nhk.fivecool.tv/api/cdn/?publicId=3bz2huey&playerId=7Dy" +API_URL = "http://{}.nhk.or.jp/nhkworld/app/tv/hlslive_web.xml" -_url_re = re.compile("http(s)?://(\w+\.)?nhk.or.jp/nhkworld") -_schema = validate.Schema({ - "live-streams": [{ - "streams": validate.all( - [{ - "protocol": validate.text, - "streamUrl": validate.text - }], - validate.filter(lambda s: s["protocol"] in ("http-flash", "http-hds")) - ) - }] -}) +_url_re = re.compile("http(?:s)?://(?:(\w+)\.)?nhk.or.jp/nhkworld") +_schema = validate.Schema( + validate.xml_findtext("./main_url/wstrm") +) class NHKWorld(Plugin): @classmethod def can_handle_url(cls, url): - return _url_re.match(url) + return _url_re.match(url) is not None def _get_streams(self): - res = http.get(API_URL) - data = http.json(res, schema=_schema) - - streams = {} - for livestreams in data["live-streams"]: - for stream in livestreams["streams"]: - url = stream["streamUrl"] - for name, stream in HDSStream.parse_manifest(self.session, url).items(): - if name.endswith("k"): - streams[name] = stream - - return streams + # get the HLS xml from the same sub domain as the main url, defaulting to www + sdomain = _url_re.match(self.url).group(1) or "www" + res = http.get(API_URL.format(sdomain)) + + stream_url = http.xml(res, schema=_schema) + return HLSStream.parse_variant_playlist(self.session, stream_url) __plugin__ = NHKWorld
NHK live issue Hello guys and thanks for continuing the work on this amazing tool . Was trying to see infos on Nhk live and despite listed as supported in the plugins list i can't get it to work : Stream Link: http://www3.nhk.or.jp/nhkworld/en/live/ and windows console response : [Streamlink for Windows] [cli][info] Found matching plugin nhkworld for URL http://www3.nhk.or.jp/nhkworld/en/live/ error: Unable to open URL: http://api.sh.nhk.fivecool.tv/api/cdn/?publicId=3bz2huey&playerId=7Dy (HTTPConnectionPool(host='api.sh.nhk.fivecool.tv', port=80): Max retries exceeded with url: /api/cdn/?publicId=3bz2huey&playerId=7Dy (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x01DD 8650>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',))) [End of Streamlink for Windows] Thanks a lot .
2016-11-24T09:56:51
streamlink/streamlink
205
streamlink__streamlink-205
[ "199" ]
1606f94d7c751ef5d4df1aaa04f1a3784e19f9ef
diff --git a/src/streamlink/plugins/picarto.py b/src/streamlink/plugins/picarto.py --- a/src/streamlink/plugins/picarto.py +++ b/src/streamlink/plugins/picarto.py @@ -2,47 +2,69 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http +from streamlink.stream import HLSStream from streamlink.stream import RTMPStream API_CHANNEL_INFO = "https://picarto.tv/process/channel" RTMP_URL = "rtmp://{}:1935/play/" RTMP_PLAYPATH = "golive+{}?token={}" +HLS_URL = "https://{}/hls/{}/index.m3u8?token={}" _url_re = re.compile(r""" https?://(\w+\.)?picarto\.tv/[^&?/] """, re.VERBOSE) +# placeStream(channel, playerID, product, offlineImage, online, token, tech) _channel_casing_re = re.compile(r""" - <script>placeStreamChannel(Flash)?\('(?P<channel>[^']+)',[^,]+,[^,]+,'(?P<visibility>[^']+)'(,[^,]+)?\);</script> + <script>\s*placeStream\s*\((.*?)\);?\s*</script> """, re.VERBOSE) class Picarto(Plugin): @classmethod - def can_handle_url(self, url): - return _url_re.match(url) + def can_handle_url(cls, url): + return _url_re.match(url) is not None + + @staticmethod + def _get_stream_arguments(page): + match = _channel_casing_re.search(page.text) + if not match: + raise ValueError + + # transform the arguments + channel, player_id, product, offline_image, online, visibility, is_flash = \ + map(lambda a: a.strip("' \""), match.group(1).split(",")) + player_id, product, offline_image, online, is_flash = \ + map(lambda a: bool(int(a)), [player_id, product, offline_image, online, is_flash]) + + return channel, player_id, product, offline_image, online, visibility, is_flash def _get_streams(self): - page_res = http.get(self.url) - match = _channel_casing_re.search(page_res.text) + page = http.get(self.url) - if not match: - return {} + try: + channel, _, _, _, online, visibility, is_flash = self._get_stream_arguments(page) + except ValueError: + return - channel = match.group("channel") - visibility = match.group("visibility") + if not online: + self.logger.error("This stream is currently offline") + return channel_server_res = http.post(API_CHANNEL_INFO, data={ "loadbalancinginfo": channel }) - streams = {} - streams["live"] = RTMPStream(self.session, { - "rtmp": RTMP_URL.format(channel_server_res.text), - "playpath": RTMP_PLAYPATH.format(channel, visibility), - "pageUrl": self.url, - "live": True - }) - return streams + if is_flash: + return {"live": RTMPStream(self.session, { + "rtmp": RTMP_URL.format(channel_server_res.text), + "playpath": RTMP_PLAYPATH.format(channel, visibility), + "pageUrl": self.url, + "live": True + })} + else: + return HLSStream.parse_variant_playlist(self.session, + HLS_URL.format(channel_server_res.text, channel, visibility), + verify=False) __plugin__ = Picarto
picarto updated streamlink no longer works Hey guys picarto no longer works because they said they updated the player so html5 can be default soon. when you run the program it says found matching plugin picarto for url https:// https://picarto.tv/picknamehere then the it says error: no stream on this URL: https://picarto.tv/picknamehere. thanks guys for the awesome program hopefully it gets solved soon!
I'm glad im not the only one have the same problem, picarto also no longer works for me.
2016-11-24T10:59:57
streamlink/streamlink
206
streamlink__streamlink-206
[ "150" ]
1606f94d7c751ef5d4df1aaa04f1a3784e19f9ef
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -38,6 +38,9 @@ # requests >2.12.0 currently has strict IDNA2008 parsing that breaks on some non-compliant URIs (YouTube) deps.append("requests>=1.0,<2.12.0") +# this version of pycryptodome is known to work and has a Windows wheel for py2.7, py3.3-3.5 +deps.append("pycryptodome==3.4.3") + # When we build an egg for the Win32 bootstrap we don't want dependency # information built into it. if environ.get("NO_DEPS"):
pyCrypto module needed on Windows Many thanks to all the team for all that's been accomplished so far! OS is Windows Vista SP2 x86, latest MS updates. Trying to rip the clips from: [Watch The 2016 MTV EMA Performances](http://www.mtv.co.uk/ema/videos/watch-the-2016-mtv-ema-performances#lush-lifeaint-my-fault-live-at-the-2016-mtv-emas) (all 14 of them!). They are using AppleHLS stream methodology (through Adobe Flash Player plugin), Firefox's "Web Console" is being used as a "URL sniffer" to retrieve the URIs of the master HLS playlists. E.g. the 3rd clip in the list (_Zara Larsson - Lush Life + Ain't My Fault (Live At The 2016 MTV EMAs_)) would, in my machine some minutes ago, generate the following "master.m3u8" URI: `https://cp450888-vh.akamaihd.net/i/mtviestor/_!/intlod/MTVInternational/MBUS/TACTIC/MVI_dev/INDIE/VIAMTVIPY/C9849AELU0/VIAMTVIPYC9849AELU0_,384x216_150_b30,384x216_400_m30,448x252_450_b30,512x288_750_m30,640x360_1200_m30,960x540_2200_m31,1280x720_3500_h32,.mp4.csmil/master.m3u8?hdnea=st%3D1478827808%7Eexp%3D1478842208%7Eacl%3D%2Fi%2Fmtviestor%2F_*%2Fintlod%2FMTVInternational%2FMBUS%2FTACTIC%2FMVI_dev%2FINDIE%2FVIAMTVIPY%2FC9849AELU0%2FVIAMTVIPYC9849AELU0_%2C384x216_150_b30%2C384x216_400_m30%2C448x252_450_b30%2C512x288_750_m30%2C640x360_1200_m30%2C960x540_2200_m31%2C1280x720_3500_h32%2C.mp4.csmil%2F*%7Ehmac%3D2a2832ab8eaa83616893a8205ab193153af54097d724f98252d7bf2a4d137159&__a__=off&__b__=450&__viacc__=NONE"` (If you want to test yourself, generate a fresh one on your machine!) The version of Streamlink used is the Py3.5.2 based standalone package created by @RosadinTV (see https://github.com/streamlink/streamlink/issues/86), but in all probability my reported issue would've also happened had I been using the official Win32 installer at [streamlink-0.0.2.exe](https://github.com/streamlink/streamlink/releases/download/0.0.2/streamlink-0.0.2.exe) Trying to fetch the above clip with streamlink fails, because the pyCrypto module is needed: ``` F:\Applications\Livestreamer\StreamlinkPortable[byRosadinTV]\Streamlink-0.0.2-wi n32-v2.0>streamlink -o "03. Zara Larsson - Lush Life + Ain't My Fault (Live At T he 2016 MTV EMAs).ts" "hlsvariant://https://cp450888-vh.akamaihd.net/i/mtvies tor/_!/intlod/MTVInternational/MBUS/TACTIC/MVI_dev/INDIE/VIAMTVIPY/C9849AELU0/VI AMTVIPYC9849AELU0_,384x216_150_b30,384x216_400_m30,448x252_450_b30,512x288_750_m 30,640x360_1200_m30,960x540_2200_m31,1280x720_3500_h32,.mp4.csmil/master.m3u8?hd nea=st%3D1478827808%7Eexp%3D1478842208%7Eacl%3D%2Fi%2Fmtviestor%2F_*%2Fintlod%2F MTVInternational%2FMBUS%2FTACTIC%2FMVI_dev%2FINDIE%2FVIAMTVIPY%2FC9849AELU0%2FVI AMTVIPYC9849AELU0_%2C384x216_150_b30%2C384x216_400_m30%2C448x252_450_b30%2C512x2 88_750_m30%2C640x360_1200_m30%2C960x540_2200_m31%2C1280x720_3500_h32%2C.mp4.csmi l%2F*%7Ehmac%3D2a2832ab8eaa83616893a8205ab193153af54097d724f98252d7bf2a4d137159& __a__=off&__b__=450&__viacc__=NONE" best [cli][info] Found matching plugin stream for URL hlsvariant://https://cp450888-v h.akamaihd.net/i/mtviestor/_!/intlod/MTVInternational/MBUS/TACTIC/MVI_dev/INDIE/ VIAMTVIPY/C9849AELU0/VIAMTVIPYC9849AELU0_,384x216_150_b30,384x216_400_m30,448x25 2_450_b30,512x288_750_m30,640x360_1200_m30,960x540_2200_m31,1280x720_3500_h32,.m p4.csmil/master.m3u8?hdnea=st%3D1478827808%7Eexp%3D1478842208%7Eacl%3D%2Fi%2Fmtv iestor%2F_*%2Fintlod%2FMTVInternational%2FMBUS%2FTACTIC%2FMVI_dev%2FINDIE%2FVIAM TVIPY%2FC9849AELU0%2FVIAMTVIPYC9849AELU0_%2C384x216_150_b30%2C384x216_400_m30%2C 448x252_450_b30%2C512x288_750_m30%2C640x360_1200_m30%2C960x540_2200_m31%2C1280x7 20_3500_h32%2C.mp4.csmil%2F*%7Ehmac%3D2a2832ab8eaa83616893a8205ab193153af54097d7 24f98252d7bf2a4d137159&__a__=off&__b__=450&__viacc__=NONE [cli][info] Available streams: 216p (worst), 252p, 288p, 360p, 540p, 720p (best) [cli][info] Opening stream: 720p (hls) [cli][error] Could not open stream: Need pyCrypto installed to decrypt this stre am ``` As far as I can tell, neither the package I am currently using nor the official win32 installer has by default the pyCrypto module installed; I am not seeing an easy way to install it on my standalone package (probably because of my limited python-fu), and I am wondering whether it's at all possible in the case of the standard win installation (?). In the end, I had to go back to livestreamer, because the last windows nightly package published at [Nightly Zip build](http://livestreamer-builds.s3.amazonaws.com/livestreamer-latest-win32.zip) apparently has the pyCrypto module integrated, hence: ``` F:\Applications\Livestreamer\livestreamer-v1.12.2-120-gab80dbd>livestreamer -o " 03. Zara Larsson - Lush Life + Ain't My Fault (Live At The 2016 MTV EMAs).ts" "hlsvariant://https://cp450888-vh.akamaihd.net/i/mtviestor/_!/intlod/MTVInterna tional/MBUS/TACTIC/MVI_dev/INDIE/VIAMTVIPY/C9849AELU0/VIAMTVIPYC9849AELU0_,384x2 16_150_b30,384x216_400_m30,448x252_450_b30,512x288_750_m30,640x360_1200_m30,960x 540_2200_m31,1280x720_3500_h32,.mp4.csmil/master.m3u8?hdnea=st%3D1478827808%7Eex p%3D1478842208%7Eacl%3D%2Fi%2Fmtviestor%2F_*%2Fintlod%2FMTVInternational%2FMBUS% 2FTACTIC%2FMVI_dev%2FINDIE%2FVIAMTVIPY%2FC9849AELU0%2FVIAMTVIPYC9849AELU0_%2C384 x216_150_b30%2C384x216_400_m30%2C448x252_450_b30%2C512x288_750_m30%2C640x360_120 0_m30%2C960x540_2200_m31%2C1280x720_3500_h32%2C.mp4.csmil%2F*%7Ehmac%3D2a2832ab8 eaa83616893a8205ab193153af54097d724f98252d7bf2a4d137159&__a__=off&__b__=450&__vi acc__=NONE" best [cli][info] Found matching plugin stream for URL hlsvariant://https://cp450888-v h.akamaihd.net/i/mtviestor/_!/intlod/MTVInternational/MBUS/TACTIC/MVI_dev/INDIE/ VIAMTVIPY/C9849AELU0/VIAMTVIPYC9849AELU0_,384x216_150_b30,384x216_400_m30,448x25 2_450_b30,512x288_750_m30,640x360_1200_m30,960x540_2200_m31,1280x720_3500_h32,.m p4.csmil/master.m3u8?hdnea=st%3D1478827808%7Eexp%3D1478842208%7Eacl%3D%2Fi%2Fmtv iestor%2F_*%2Fintlod%2FMTVInternational%2FMBUS%2FTACTIC%2FMVI_dev%2FINDIE%2FVIAM TVIPY%2FC9849AELU0%2FVIAMTVIPYC9849AELU0_%2C384x216_150_b30%2C384x216_400_m30%2C 448x252_450_b30%2C512x288_750_m30%2C640x360_1200_m30%2C960x540_2200_m31%2C1280x7 20_3500_h32%2C.mp4.csmil%2F*%7Ehmac%3D2a2832ab8eaa83616893a8205ab193153af54097d7 24f98252d7bf2a4d137159&__a__=off&__b__=450&__viacc__=NONE [cli][info] Available streams: 216p (worst), 252p, 288p, 360p, 540p, 720p (best) [cli][info] Opening stream: 720p (hls) [download][..he 2016 MTV EMAs).ts.ts] Written 99.1 MB (1m14s @ 1.4 MB/s) [ cli][info] Stream ended ``` I am aware that Windows always represents a PITA for the developers of Open Source apps, however any resolution of this issue (marginal as it may be) will be highly welcome! Many regards.
@Vangelis66 Hi, download this and extract inside the Streamlink folder of my release: https://1drv.ms/u/s!AteNlrENG5PD9WfqTY3jZ2Vg0Qo4 PS: I 've been busy last week, but when i can i will try to release the Automatic Windows Build i have promessed. I am astonished developing team didn't include pycrypto into streamlink core as chrippa did to livestreamer. @RosadinTV, you're my hero! "Crypto" folder was placed within "Streamlink" directory and now portable Streamlink downloads those MTV clips fine: ``` F:\Applications\Livestreamer\StreamlinkPortable[byRosadinTV]\Streamlink-0.0.2-wi n32-v2.0>streamlink -o "03. Zara Larsson - Lush Life + Ain't My Fault (Live At T he 2016 MTV EMAs).ts" "hlsvariant://https://cp450888-vh.akamaihd.net/i/mtviestor /_!/intlod/MTVInternational/MBUS/TACTIC/MVI_dev/INDIE/VIAMTVIPY/C9849AELU0/VIAMT VIPYC9849AELU0_,384x216_150_b30,384x216_400_m30,448x252_450_b30,512x288_750_m30, 640x360_1200_m30,960x540_2200_m31,1280x720_3500_h32,.mp4.csmil/master.m3u8?hdnea =st%3D1478877688%7Eexp%3D1478892088%7Eacl%3D%2Fi%2Fmtviestor%2F_*%2Fintlod%2FMTV International%2FMBUS%2FTACTIC%2FMVI_dev%2FINDIE%2FVIAMTVIPY%2FC9849AELU0%2FVIAMT VIPYC9849AELU0_%2C384x216_150_b30%2C384x216_400_m30%2C448x252_450_b30%2C512x288_ 750_m30%2C640x360_1200_m30%2C960x540_2200_m31%2C1280x720_3500_h32%2C.mp4.csmil%2 F*%7Ehmac%3Dad2e8b0fe901b2b376e6d187ed32cf5209f6a651657770c197033f9151b50b5c&__a __=off&__b__=450&__viacc__=NONE" best [cli][info] Found matching plugin stream for URL hlsvariant://https://cp450888-v h.akamaihd.net/i/mtviestor/_!/intlod/MTVInternational/MBUS/TACTIC/MVI_dev/INDIE/ VIAMTVIPY/C9849AELU0/VIAMTVIPYC9849AELU0_,384x216_150_b30,384x216_400_m30,448x25 2_450_b30,512x288_750_m30,640x360_1200_m30,960x540_2200_m31,1280x720_3500_h32,.m p4.csmil/master.m3u8?hdnea=st%3D1478877688%7Eexp%3D1478892088%7Eacl%3D%2Fi%2Fmtv iestor%2F_*%2Fintlod%2FMTVInternational%2FMBUS%2FTACTIC%2FMVI_dev%2FINDIE%2FVIAM TVIPY%2FC9849AELU0%2FVIAMTVIPYC9849AELU0_%2C384x216_150_b30%2C384x216_400_m30%2C 448x252_450_b30%2C512x288_750_m30%2C640x360_1200_m30%2C960x540_2200_m31%2C1280x7 20_3500_h32%2C.mp4.csmil%2F*%7Ehmac%3Dad2e8b0fe901b2b376e6d187ed32cf5209f6a65165 7770c197033f9151b50b5c&__a__=off&__b__=450&__viacc__=NONE [cli][info] Available streams: 216p (worst), 252p, 288p, 360p, 540p, 720p (best) [cli][info] Opening stream: 720p (hls) [download][..t The 2016 MTV EMAs).ts] Written 99.1 MB (1m20s @ 1.3 MB/s) [ cli][info] Stream ended ``` So again a BIG thanks for your support! (Those 720p clips do look nice on friend's new 50'' TV!!!) @karlo2105 : Are you refering (by "**you**") to @RosadinTV ? I don' think it was his fault to begin with... If you mean the "streamlink" dev team, then yes, this is something they should probably fix... Cheers @Vangelis66 Cool, glad to see it works 😄 In response to @karlo2105 i dont think is a problem with streamlink itself, problably both @sbstp and me forgive to include the PyCrypto package, in the case of livestreamer PyCrypto is placed inside library.zip file, but in fact is the same (also note by the new way we are using the whole library instead of the reduced one included in livestreamer release) @karlo2105 This is an open source project run by volunteers, many of which were not familiar with the internal workings of the original project and there hadn't been any development in a year, so sometimes things are going to get missed for rarely used streaming services like MTV. The constant negativity really isn't warranted, and is actively detrimental to the project so please stop. If you don't like something then fix it, you have the ability to open PRs just as much as anyone else. If you don't think development is occurring quickly enough, or you want a specific feature in a more timely manner then please pay someone to work on said feature. @gravyboat I didn't say a single word when Chrippa slowed and stopped developping Livestreamer. I am grateful to anybody who is fixing code and developing furthermore streamlink. All I can do is open issues when i noticed some plugin is broken and to encourage you to keep on. I don't have developer skills. You can take any time you want to continue developing or not. I was not aware that pycrypto library wasn't included in Livestreamer fork but I agree it's better to use the whole pycrypto library instead of the reduced one. Yeah, it's just an oversight. I based the installer on the setup.py script, and there's no mention of pycrypto in it. **To all**: I never thought my report would create an ill atmosphere between the developers and us, mere users-testers... @gravyboat: I am very well aware of the way Open Source projects exist, function and continue to develop over time, as I am following quite a number of them; all the above is achieved through a considerable effort on the part of the developers, taking a serious bite out of their everyday lives/spare time; not to mention the altruistic nature of actually sharing knowledge/code! With regards to the comment made by @karlo2105, maybe his actual wording wasn't carefully chosen, so that left some room for misinterpretation (even to me when I first read it...). Please acknowledge that English is not a native language for most of us (including me), so "accidents" may happen... What I sometimes resent is the attitude from some developers, also echoed in your comment, that "_If you don't like something then fix it, you have the ability to open PRs just as much as anyone else_". The cruel fact is that I have zero coding skills, so the above suggestion is a no-go for me, much like it is for @karlo2105; but I like to contribute to Open Source projects in the best (and only) way I can, which is identifying and reporting bugs. I am never pushy or demanding on the devs, just letting them know that something doesn't work as intended. It's up to them to follow up my report in the best way/time they see fit (and that is why I am so pleasantly surprised by @RosadinTV's immediate response!). Reporting bugs in an efficient fashion also takes spare time for the reporter and is also done on a pure voluntary basis; I would argue my spare time is as precious as a developer's spare time... With reference to this specific issue I filed, what I wanted to achieve could be done with the abandoned livestreamer app; I could let the issue slip away and stay silent about it, especially, as you put it, since it involves "_rarely used streaming services like MTV_". But I chose to report it so that, in the long run, streamlink would get better... To conclude and summarize, of course all the credit goes to the coders, but mere users-testers like myself and @karlo2105 do play some role in the evolution of the project! @Vangelis66 Yes, of course, bugs reporting and testing is a really good job, it can be as important as programming. The important thing about these types of projects is that each contributes what it can. PS: What is your native language? @RosadinTV asked: > What is your native language? ... Well, I'd have thought my username gave that away already, but it's actually **_Greek_**! @Vangelis66 Cool, in my case is Spanish .. It's good to see so much diversity. @Vangelis66 You're absolutely right and my comment was not targeted at you (your bug report was great) and I could have done a better job thinking about how it sounded when others read the comment I was responding to and my response. My apologies @karlo2105. Reporting bugs and doing testing is critical to an open source project and your help is greatly appreciated. I apologize if my comment came off negatively, it was not intended to. I would never mean to infer that reporting bugs or creating issues is in some way less valuable than the work that developers or anyone else does on an open source project. We all contribute in our own way, I simply want to ensure these interactions are positive and there is understanding between everyone that sometimes things are missed, we are only human after all! We can only fix the things we are aware of, so please keep sharing and providing these excellent troubleshooting steps you have taken to provide us with as much information as possible. Please do not discredit yourself as 'mere user-testers', as software without any users is worthless, and helping to improve that software (whether through code, bug reports, writing documentation, etc.) is one of the most valuable things a project can ask for. This is an international community of people who love this project, and I want to ensure we keep things positive and constructive so we can continue to gain new users, new contributors, new bug reporters, and everything in-between! While we wait for a new release, you can install pyCrypto for Python 3.5 with this: https://github.com/sfbahr/PyCrypto-Wheels @gravyboat @beardypig I believe this issue is resolved with the new installer, correct? Maybe we should add pycryptodome to the setup.py as well. @sbstp I think so, let's double check with @beardypig but we should be able to close this out. I'm not sure about pycrptodome. I assume most users on Linux would just install it themselves, but we can discuss it. Personally I would add it to the `setup.py` file, the only thing is to double check the external dependencies - I'm not sure if you need any additional header files to compile the extension (which pip will have to do on linux and macOS). I don't think it doesn't require anything extra... On a minimal Ubuntu 16.04 VM I installed `pycryptodome` with out installing anything except `python-pip` from apt. I'm fine with including it then.
2016-11-24T12:15:17
streamlink/streamlink
249
streamlink__streamlink-249
[ "243" ]
47e270c35ae375b41dcac797d3fdcd170f7ab01e
diff --git a/src/streamlink/plugins/crunchyroll.py b/src/streamlink/plugins/crunchyroll.py --- a/src/streamlink/plugins/crunchyroll.py +++ b/src/streamlink/plugins/crunchyroll.py @@ -25,6 +25,11 @@ "high": 720, "ultra": 1080, } +STREAM_NAMES = { + "120k": "low", + "328k": "mid", + "864k": "high" +} def parse_timestamp(ts): @@ -62,7 +67,8 @@ def parse_timestamp(ts): "url": validate.url( scheme="http", path=validate.endswith(".m3u8") - ) + ), + validate.optional("video_encode_id"): validate.text }] ) } @@ -77,7 +83,8 @@ def parse_timestamp(ts): validate.transform(parse_timestamp) ), "user": { - "username": validate.text + "username": validate.any(validate.text, None), + "email": validate.text } }) _session_schema = validate.Schema( @@ -226,24 +233,32 @@ def _get_streams(self): if not info: return - # The adaptive quality stream contains a superset of all the other streams listeed + streams = {} + + # The adaptive quality stream sometimes a subset of all the other streams listed, ultra is no included has_adaptive = any([s[u"quality"] == u"adaptive" for s in info[u"streams"]]) if has_adaptive: self.logger.debug(u"Loading streams from adaptive playlist") for stream in filter(lambda x: x[u"quality"] == u"adaptive", info[u"streams"]): - return HLSStream.parse_variant_playlist(self.session, stream["url"]) - else: - streams = {} - # If there is no adaptive quality stream then parse each individual result - for stream in info[u"streams"]: + for q, s in HLSStream.parse_variant_playlist(self.session, stream[u"url"]).items(): + # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams + name = STREAM_NAMES.get(q, q) + streams[name] = s + + # If there is no adaptive quality stream then parse each individual result + for stream in info[u"streams"]: + if stream[u"quality"] != u"adaptive": # the video_encode_id indicates that the stream is not a variant playlist if u"video_encode_id" in stream: streams[stream[u"quality"]] = HLSStream(self.session, stream[u"url"]) else: # otherwise the stream url is actually a list of stream qualities - streams.update(HLSStream.parse_variant_playlist(self.session, stream[u"url"])) + for q, s in HLSStream.parse_variant_playlist(self.session, stream[u"url"]).items(): + # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams + name = STREAM_NAMES.get(q, q) + streams[name] = s - return streams + return streams def _get_device_id(self): """Returns the saved device id or creates a new one and saves it.""" @@ -301,7 +316,7 @@ def _create_api(self): api.auth = login["auth"] self.logger.info("Successfully logged in as '{0}'", - login["user"]["username"]) + login["user"]["username"] or login["user"]["email"]) expires = (login["expires"] - current_time).total_seconds() self.cache.set("auth", login["auth"], expires)
Crunchyroll can't find 1080p streams The current plugin seems to only find streams up to 720p. However I tested the old plugin and it seems to be working again I tested the links I used in #70 and a few more but couldn't reproduce the issue with the old plugin. More testing may be needed but it's more than likely safe to revert back.
2016-12-05T10:51:05
streamlink/streamlink
338
streamlink__streamlink-338
[ "318" ]
642946aabfcf688ab806e5120b0c94cb91756b61
diff --git a/src/streamlink/plugins/tvcatchup.py b/src/streamlink/plugins/tvcatchup.py --- a/src/streamlink/plugins/tvcatchup.py +++ b/src/streamlink/plugins/tvcatchup.py @@ -6,7 +6,7 @@ USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" _url_re = re.compile("http://(?:www\.)?tvcatchup.com/watch/\w+") -_stream_re = re.compile(r"\"(?P<stream_url>https?://.*m3u8\?.*clientKey=[^\"]*)\";") +_stream_re = re.compile(r'''(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''') class TVCatchup(Plugin): @@ -24,7 +24,7 @@ def _get_streams(self): match = _stream_re.search(res.text, re.IGNORECASE | re.MULTILINE) if match: - stream_url = match.groupdict()["stream_url"] + stream_url = match.group("stream_url") if stream_url: if "_adp" in stream_url:
TVCatchup addon not working anymore root@ovh2:/data# streamlink http://tvcatchup.com/watch/channel4 [cli][info] streamlink is running as root! Be careful! [cli][info] Found matching plugin tvcatchup for URL http://tvcatchup.com/watch/channel4 error: No streams found on this URL: http://tvcatchup.com/watch/channel4 root@ovh2:/data# streamlink --plugins [cli][info] streamlink is running as root! Be careful! Loaded plugins: adultswim, afreeca, afreecatv, aftonbladet, alieztv, antenna, ard_live, ard_mediathek, artetv, atresplayer, azubutv, bambuser, beam, beattv, bigo, bilibili, bliptv, chaturbate, cinergroup, connectcast, crunchyroll, cybergame, dailymotion, dingittv, disney_de, dmcloud, dmcloud_embed, dogan, dogus, dommune, douyutv, dplay, drdk, euronews, expressen, filmon, filmon_us, foxtr, furstream, gaminglive, gomexp, goodgame, hitbox, itvplayer, kanal7, letontv, livecodingtv, livestation, livestream, media_ccc_de, mediaklikk, meerkat, mips, mlgtv, nhkworld, nineanime, nos, npo, nrk, oldlivestream, openrectv, orf_tvthek, pandatv, periscope, picarto, piczel, powerapp, rtlxl, rtve, ruv, seemeplay, servustv, speedrunslive, sportschau, ssh101, stream, streamboat, streamingvideoprovider, streamlive, streamme, streamupcom, svtplay, tga, tigerdile, trt, turkuvaz, tv360, tv3cat, tv4play, tv8, tvcatchup, tvplayer, twitch, ustreamtv, vaughnlive, veetle, vgtv, viagame, viasat, viasat_embed, vidio, wattv, webtv, weeb, younow, youtube, zdf_mediathek
Looks like they have changed the site a bit. Unfortunately I can't look at it at the moment, I'm on holiday, but I'll take a look next week. Maybe someone else will have time to fix it before that. Sorry :-) No hurry, enjoy your holiday :)
2016-12-30T14:53:24
streamlink/streamlink
389
streamlink__streamlink-389
[ "376" ]
d45ec8ff5e02ccb2c29ed2eb1fe1581cda81c94b
diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py --- a/src/streamlink/plugins/tf1.py +++ b/src/streamlink/plugins/tf1.py @@ -11,9 +11,9 @@ class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) - api_url = "http://www.wat.tv/get/androidlive{0}/591997" - swf_url = "http://www.wat.tv/images/v70/PlayerWat.swf?rev=04.00.861" - hds_channel_remap = {"tf1": "connect"} + api_url = "http://www.wat.tv/get/{0}/591997" + swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" + hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod @@ -21,13 +21,15 @@ def can_handle_url(cls, url): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): - channel = self.hds_channel_remap.get(channel, channel) + channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), - params={"getURL": 1}).text + params={"getURL": 1}, + headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, - pvswf=self.swf_url).items(): + pvswf=self.swf_url, + headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): @@ -41,8 +43,11 @@ def _get_hls_streams(self, channel): if m: hls_stream_url = m.group(1) - for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): - yield s + try: + for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): + yield s + except: + self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) diff --git a/src/streamlink/stream/hds.py b/src/streamlink/stream/hds.py --- a/src/streamlink/stream/hds.py +++ b/src/streamlink/stream/hds.py @@ -2,8 +2,10 @@ import base64 import hmac +import random import re import os.path +import string from binascii import unhexlify from collections import namedtuple @@ -68,11 +70,15 @@ def fetch(self, fragment, retries=None): return try: + request_params = self.stream.request_params.copy() + params = request_params.pop("params", {}) + params.pop("g", None) return self.session.http.get(fragment.url, stream=True, timeout=self.timeout, exception=StreamError, - **self.stream.request_params) + params=params, + **request_params) except StreamError as err: self.logger.error("Failed to open fragment {0}-{1}: {2}", fragment.segment, fragment.fragment, err) @@ -442,6 +448,7 @@ def parse_manifest(cls, session, url, timeout=60, pvswf=None, is_akamai=False, if "akamaihd" in url or is_akamai: request_params["params"]["hdcore"] = HDCORE_VERSION + request_params["params"]["g"] = cls.cache_buster_string(12) res = session.http.get(url, exception=IOError, **request_params) manifest = session.http.xml(res, "manifest XML", ignore_ns=True, @@ -586,3 +593,7 @@ def _pv_params(cls, session, pvswf, pv, **request_params): params.extend(parse_qsl(hdntl, keep_blank_values=True)) return params + + @staticmethod + def cache_buster_string(length): + return "".join([random.choice(string.ascii_uppercase) for i in range(length)])
Mytf1.fr : TF 1, TMC, NT 1, HD 1, LCI http://www.tf1.fr/direct Channels on TF 1 site require only a free login and French proxy. They use HDS and HLS. LCi doesn't require login just proxy : http://www.lci.fr/direct/ But it would be of course better if you can bypass login.
Can take a look, do you know any good proxy for lci? I can use unlocator for tf1 but I don't know any good http proxies for France. You can try here : http://spys.ru/free-proxy-list/FR/ http://www.freeproxylists.net/?c=FR&pt=&pr=&a%5B%5D=0&a%5B%5D=1&a%5B%5D=2&u=0 https://www.proxynova.com/proxy-server-list/country-fr/ @karlo2105 wrote: > LCi doesn't require login, just proxy: > http://www.lci.fr/direct/ @beardypig wrote: > do you know any good proxy for lci? I am not inside France, but I find accessing the live (direct) stream from Greece does not need a French proxy; the "HDS Link detector" Firefox addon reveals the following HDS manifest: `http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=st=1483822658~exp=1483824458~acl=/*~hmac=1bd7f429b37a778f80a7654e2f2db1d7a813fe5c0d050acb5279451fbd108c82&hdcore=2.11.3&g=MHIRXZLQFQZI` which, of course, has a limited lifespan; it contains five quality variants, with bitrates: 240k, 496k, 896k, 1296k & 2596k @beardypig I've been meaning to ask, you, of course, are not obliged in any way to reply, but what is your physical location? Regards I think through HLS, they provide 720p stream. @karlo2105 wrote: > I think through HLS, they provide 720p stream The 2596k AdobeHDS stream is **720p**, too. But I have stumbled upon a problem; AdobeHDS.php would download streams from the manifest fine, but streamlink fails to, citing: `error: This manifest requires the 'pvswf' parameter to verify the SWF` ``` streamlink "hds://http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=st=1483827331~exp=1483829131~acl=/*~hmac=d0f781049713946d9ce00371c599a0abec582cb6b86ab0466971958d408aeb0d&hdcore=2.11.3&g=VXPKOBLDFCWY pvswf=http://www.wat.tv/images/v70/PlayerWat.swf?rev=04.00.861" best ``` Works for me :) @beardypig Thanks! Where exactly in streamlink's documentation is the `pvswf parameter` detailed? I've searched, but to no avail :-( BTW, this HDS parameter reminds me of the `--swfUrl` one used in RTMP streams... @Vangelis66 it's not really documented, there is a section about passing extra parameters to streams here https://streamlink.github.io/cli.html#playing-built-in-streaming-protocols-directly. There is an example for rtmp but it works for everything I think. You have to know the `pvswf` parameter though... LCI is only sometimes geo locked, it should be quite straightforward to make a plugin :-) @Vangelis66 HDS is successor of RTMP. Source for HDS : http://www.wat.tv/get/androidliveconnect/591997?getURL=1 http://www.wat.tv/get/androidlivelci/591997?getURL=1 http://www.wat.tv/get/androidlivent1/591997?getURL=1 http://www.wat.tv/get/androidlivehd1/591997?getURL=1 http://www.wat.tv/get/androidlivetmc/591997?getURL=1 @karlo2105 wrote: > Source for HDS : > (snip) > http://www.wat.tv/get/androidlivelci/591997?getURL=1 Hello Karlo :smile: I have only tested LCI on a desktop browser, the manifest URIs sniffed either via Firefox's web console or (more easily) via "HDS Link Detector" addon are of the form `http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=st=1483843039~exp=1483844839~acl=/*~hmac=2afc34bd7b2a0c8c1782d4f2b48eb2732f0e99a3cb8dd7701e9e2102f727daf6&hdcore=2.11.3&g=TTSHPFEMNPXT` Those are very short-lived (less than 30mins), but for as long as they are valid they are downloadable either via AdobeHDS.php script or via livestreamer/streamlink (the pvswf value must be supplied as per previous post in this thread). I don't have an android device to test, but opening http://www.wat.tv/get/androidlivelci/591997?getURL=1 in a desktop browser tab yields a manifest of this form: `http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=st=1483844264~exp=1483846064~acl=/*~hmac=e5b561cc06a10cfde5fffe135f6e16c225ce34fe6338c692cd4aa7b87c3725cc` These ALWAYS get an **Access Denied** response when a download is attempted well within the manifest's validity; probably because the manifests generated by the link you posted are missing the final part of the form: `&hdcore=2.11.3&g=TTSHPFEMNPXT` But if you modify a bit the manifest URI generated by your link, you get a valid (and downloadable) AppleHLS master playlist: http://www.wat.tv/get/androidlivelci/591997?getURL=1 => `http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=st=1483845377~exp=1483847177~acl=/*~hmac=095e53624d9d3cc9d07d9cceaf92379724fbcab66c7fab75bf76c81d370c2475` (403 Access Denied) If modified to `http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/master.m3u8?hdnea=st=1483845377~exp=1483847177~acl=/*~hmac=095e53624d9d3cc9d07d9cceaf92379724fbcab66c7fab75bf76c81d370c2475` => Valid playlist ``` #EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=240000,RESOLUTION=416x234,CODECS="avc1.66.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_240_av-p.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=264000,RESOLUTION=416x234,CODECS="avc1.66.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_240_av-b.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=496000,RESOLUTION=416x234,CODECS="avc1.66.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_496_av-p.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=464000,RESOLUTION=416x234,CODECS="avc1.66.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_496_av-b.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=896000,RESOLUTION=640x360,CODECS="avc1.77.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_896_av-p.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=896000,RESOLUTION=640x360,CODECS="avc1.66.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_896_av-b.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1296000,RESOLUTION=1080x576,CODECS="avc1.77.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_1296_av-p.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1296000,RESOLUTION=1024x576,CODECS="avc1.77.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_1296_av-b.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2595000,RESOLUTION=1280x720,CODECS="avc1.77.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_2596_av-p.m3u8?sd=10&rebase=on #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2595000,RESOLUTION=1280x720,CODECS="avc1.77.30, mp4a.40.2" http://lcilivhlshdslive-lh.akamaihd.net/i/lci_1@301585/index_2596_av-b.m3u8?sd=10&rebase=on ``` As you can see, for each resolution there exist two (or more) streams: 234p: 240k, 264k, 464k, 496k 360p: 896k-1, 896k-2 576p: 1296k-1, 1296k-2 720p: 2595k-1, 2595k-2 so this could present a small problem in creating the plugin... But I am sure @beardypig knows already all this info you and I are posting, probably feeling a bit amused at us newbies trying to figure out how things work... 😺 All have a nice Sunday (deep-freeze over here at -8 Celsius) Thanks for plugins. Some HDS streams are not working with proxy. TMC ``` livestreamer "http://www.tf1.fr/nt1/direct" 840k_hds [cli][info] Found matching plugin tf1 for URL http://www.tf1.fr/tmc/direct [cli][info] Available streams: 440k_hds, 840k_hds, 64k (worst), 440k, 640k, 840k, 1240k (best) [cli][info] Opening stream: 840k_hds (hds) [stream.hds][error] Failed to open fragment 1-23649054: Unable to open URL: http://tmchdslive-f.akamaihd.net/z/live_1@72268/840_bf2d3ed44cf2b891-p_Seg1-Frag23649054 (403 Client Error: Forbidden) ``` NT 1 ``` livestreamer "http://www.tf1.fr/nt1/direct" 840k_hds [cli][info] Found matching plugin tf1 for URL http://www.tf1.fr/nt1/direct [cli][info] Available streams: 440k_hds, 840k_hds, 64k (worst), 440k, 640k, 840k, 1240k (best) [cli][info] Opening stream: 840k_hds (hds) [stream.hds][error] Failed to open fragment 1-23649136: Unable to open URL: http ://nt1hdslive-f.akamaihd.net/z/live_1@72464/840_487251dc402e69b8-p_Seg1-Frag2364 9136 (403 Client Error: Forbidden) ``` HD 1 ``` livestreamer "http://www.tf1.fr/hd1/direct" best [cli][info] Found matching plugin tf1 for URL http://www.tf1.fr/hd1/direct error: Unable to open URL: http://hd1livhdsandliv-lh.akamaihd.net/z/andlive_1@90 743/manifest.f4m?hdnea=st=1483915819~exp=1483917619~acl=/*~hmac=3c8731afcfae9226 e48bffa438b86cec873bb554af367c12e33d811b3fb85108 (404 Client Error: Not Found) ``` Do the stream work in a browser with the proxy? Yes it does. Take a look. http://www.wat.tv/images/v70/PlayerLite.swf?videoId=L_TMC `http://tmclivhdsweblive-lh.akamaihd.net/z/live_1@91207/manifest.f4m?hdnea=st=1483918400~exp=1483920200~acl=/*~hmac=228208d07495af8c38d7e84f2d1cb744a2ed3909ffabd1c0cf169280c2106216&`hdcore=2.11.3&g=PVHIWKMOGQRH http://www.wat.tv/images/v70/PlayerLite.swf?videoId=L_NT1 `http://nt1livhdsweb-lh.akamaihd.net/z/live_1@90590/manifest.f4m?hdnea=st=1483918281~exp=1483920081~acl=/*~hmac=b7944375268a2d6e717d93e3b8788fed7e41d26b4948887e60be039210d40d9f&hdcore=2.11.3&g=VVQMAMHFJBVH&hdcore=3.1.0` http://www.wat.tv/images/v70/PlayerLite.swf?videoId=L_HD1 `http://hd1livhdsweblive-lh.akamaihd.net/z/weblive_1@90467/manifest.f4m?hdnea=st=1483918423~exp=1483920223~acl=/*~hmac=f8e5823edc3e82247a523c35921a1a5809815061bc6072bc0edb8e7c10807007&hdcore=2.11.3&g=WOKQQUMWRNDO` I guess you miss that part "&hdcore=2.11.3&g=WOKQQUMWRNDO" You can also add that parameter on TF 1 and LCI in case they add it to their HDS address. Looks like there is some extra verification some of the time for some of the streams. Need to work out how the `g` argument is calculated...
2017-01-09T13:22:19
streamlink/streamlink
405
streamlink__streamlink-405
[ "370" ]
6cce32a58d2bd5e3cea5f21a6673fe810500188c
diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py --- a/src/streamlink/stream/hls.py +++ b/src/streamlink/stream/hls.py @@ -320,8 +320,17 @@ def parse_variant_playlist(cls, session_, url, name_key="name", stream_name = (names.get(name_key) or names.get("name") or names.get("pixels") or names.get("bitrate")) - if not stream_name or stream_name in streams: + if not stream_name: continue + if stream_name in streams: # rename duplicate streams + stream_name = "{0}_alt".format(stream_name) + num_alts = len(list(filter(lambda n: n.startswith(stream_name), streams.keys()))) + + # We shouldn't need more than 2 alt streams + if num_alts >= 2: + continue + elif num_alts > 0: + stream_name = "{0}{1}".format(stream_name, num_alts + 1) if check_streams: try:
Adult Swim doesn't play any streams. https://www.adultswim.com/videos/streams https://www.adultswim.com/videos/streams/toonami https://www.adultswim.com/videos/streams/williams-stream
Can you please provide the command you're running, as well as what the error output looks like? @gravyboat ``` $ streamlink -p mpv https://www.adultswim.com/videos/streams/toonami error: No plugin can handle URL: https://www.adultswim.com/videos/streams/toonami ``` What version of Streamlink are you running? Your command (minus passing the player variable) works fine for me on `0.2.0`. @stepshal that is a bug, if you drop the `s` from `https` it should work. I'm preparing a PR to fix it right now :) @beardypig That's weird, it worked fine for me with `https`. @gravyboat agreed, very weird... @stepshal this should be fixed if you update to the latest nightly. @stepshal is this working with the latest nightly? @beardypig I have this: `[cli][error] Could not open stream: Unable to open URL: http://adultswimhls-i.akamaihd.net/hls/live/249295/adultswim_6/main/1/stream_Layer4.m3u8 (403 Client Error: Forbidden for url: http://adultswimhls-i.akamaihd.net/hls/live/249295/adultswim_6/main/1/stream_Layer4.m3u8)` So it's geo-restricted? But i can watch it in browser. Which URL are you trying to watch? I think some if not all are geo-restricted to the US. @beardypig i can watch all of them in browser without proxy. And do they all give the same error with streamlink? @beardypig Seems that all streams work except Toonami. But i can still watch it in browser. OK. I get same error when trying from outside the US. I'll try and correct it. @beardypig and all vods from archive doesn't work. It's showing live stream instead. VOD is not currently supported. The toonami stream is slightly weird, might take a little while to fix. @beardypig so pycryptodome is needed only for VODs, that are not yet supported? I can't remember if they were just encrypted or also had DRM. I'll take a look when I fix the toonami bug...
2017-01-12T09:23:20
streamlink/streamlink
415
streamlink__streamlink-415
[ "413" ]
8b710ba7f642e0906413157e60e602ce41cfe1cf
diff --git a/src/streamlink/plugins/rtve.py b/src/streamlink/plugins/rtve.py --- a/src/streamlink/plugins/rtve.py +++ b/src/streamlink/plugins/rtve.py @@ -1,59 +1,86 @@ +import base64 import re -from streamlink.plugin import Plugin, PluginError +from Crypto.Cipher import Blowfish +from streamlink.compat import bytes, is_py3 +from streamlink.plugin import Plugin from streamlink.plugin.api import http +from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate from streamlink.stream import HLSStream +from streamlink.utils import parse_xml -# The last four channel_paths repsond with 301 and provide -# a redirect location that corresponds to a channel_path above. -_url_re = re.compile(r""" - https?://www\.rtve\.es/ - (?P<channel_path> - directo/la-1| - directo/la-2| - directo/teledeporte| - directo/canal-24h| - - noticias/directo-la-1| - television/la-2-directo| - deportes/directo/teledeporte| - noticias/directo/canal-24h - ) - /? -""", re.VERBOSE) -_id_map = { - "directo/la-1": "LA1", - "directo/la-2": "LA2", - "directo/teledeporte": "TDP", - "directo/canal-24h": "24H", - "noticias/directo-la-1": "LA1", - "television/la-2-directo": "LA2", - "deportes/directo/teledeporte": "TDP", - "noticias/directo/canal-24h": "24H", -} +class ZTNRClient(object): + base_url = "http://ztnr.rtve.es/ztnr/res/" + block_size = 16 + + def __init__(self, key): + self.cipher = Blowfish.new(key, Blowfish.MODE_ECB) + + def pad(self, data): + n = self.block_size - len(data) % self.block_size + return data + bytes(chr(self.block_size - len(data) % self.block_size), "utf8") * n + + def unpad(self, data): + if is_py3: + return data[0:-data[-1]] + else: + return data[0:-ord(data[-1])] + + def encrypt(self, data): + return base64.b64encode(self.cipher.encrypt(self.pad(bytes(data, "utf-8"))), altchars=b"-_").decode("ascii") + + def decrypt(self, data): + return self.unpad(self.cipher.decrypt(base64.b64decode(data, altchars=b"-_"))) + + def request(self, data, *args, **kwargs): + res = http.get(self.base_url+self.encrypt(data), *args, **kwargs) + return self.decrypt(res.content) + + def get_cdn_list(self, vid, manager="apedemak", vtype="video", lang="es", schema=None): + data = self.request("{id}_{manager}_{type}_{lang}".format(id=vid, manager=manager, type=vtype, lang=lang)) + if schema: + return schema.validate(data) + else: + return data class Rtve(Plugin): + secret_key = base64.b64decode("eWVMJmRhRDM=") + channel_id_re = re.compile(r'<span.*?id="iniIDA">(\d+)</span>') + url_re = re.compile(r""" + https?://(?:www\.)?rtve\.es/(?:noticias|television|deportes)/.*?/? + """, re.VERBOSE) + cdn_schema = validate.Schema( + validate.transform(parse_xml), + validate.xml_findtext(".//url") + ) + @classmethod def can_handle_url(cls, url): - return _url_re.match(url) + return cls.url_re.match(url) is not None def __init__(self, url): Plugin.__init__(self, url) - match = _url_re.match(url).groupdict() - self.channel_path = match["channel_path"] + self.zclient = ZTNRClient(self.secret_key) + http.headers = {"User-Agent": useragents.SAFARI_8} + + def _get_channel_id(self): + res = http.get(self.url) + m = self.channel_id_re.search(res.text) + return m and int(m.group(1)) def _get_streams(self): - stream_id = _id_map[self.channel_path] - hls_url = "http://iphonelive.rtve.es/{0}_LV3_IPH/{0}_LV3_IPH.m3u8".format(stream_id) + channel_id = self._get_channel_id() - # Check if the stream is available - res = http.head(hls_url, raise_for_status=False) - if res.status_code == 404: - raise PluginError("The program is not available due to rights restrictions") + if channel_id: + self.logger.debug("Found channel with id: {0}", channel_id) + hls_url = self.zclient.get_cdn_list(channel_id, schema=self.cdn_schema) + self.logger.debug("Got stream URL: {0}", hls_url) + return HLSStream.parse_variant_playlist(self.session, hls_url) - return HLSStream.parse_variant_playlist(self.session, hls_url) + return __plugin__ = Rtve
RTVE.es plugin broken Spanish public TV RTVE recently changed broadcasting address and servers which made plugin broken. `livestreamer -p "C:\Users\Ddr\Downloads\VLCPortable\App\vlc\vlc" "http://www.rtve.es/noticias/mas-24/" best error: No plugin can handle URL: http://www.rtve.es/noticias/mas-24/` Below are direct addresses to channels : - La 1 : http://www.rtve.es/noticias/directo-la-1/ - La 2 : http://www.rtve.es/television/la-2-directo/ - TDP : http://www.rtve.es/deportes/directo/teledeporte/ - 24H : http://www.rtve.es/noticias/mas-24/ 24H is not geoblocked.
2017-01-13T13:58:04
streamlink/streamlink
427
streamlink__streamlink-427
[ "337" ]
8d73f62dccba7c5f7fe4a04badf2656e15910d10
diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -931,16 +931,14 @@ def main(): # Close output if output: output.close() - - # Make sure current stream gets properly cleaned up + console.msg("Interrupted! Exiting...") + finally: if stream_fd: - console.msg("Interrupted! Closing currently open stream...") try: + console.logger.info("Closing currently open stream...") stream_fd.close() except KeyboardInterrupt: sys.exit() - else: - console.msg("Interrupted! Exiting...") elif args.twitch_oauth_authenticate: authenticate_twitch_oauth() elif args.help:
python interpreter crash Environment: windows 8.1 x64 streamlink: latest nightly build for windows - First, i get a message "rtmpdump.exe has stopped working" Like this: ![error img](http://thewindowsclub.thewindowsclubco.netdna-cdn.com/wp-content/uploads/2014/02/sqlstoped2.png) - Then "Python has stopped working" streamlink output: ``` [cli][info] Opening stream: high (rtmp) [cli][debug] Pre-buffering 8192 bytes [cli][error] Failed to read data from stream: Read timeout Fatal Python error: could not acquire lock for <_io.BufferedReader name=5> at in terpreter shutdown, possibly due to daemon threads Thread 0x000014bc (most recent call first): File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\stream\wrappers.py", line 67 in run File "threading.py", line 914 in _bootstrap_inner File "threading.py", line 882 in _bootstrap Current thread 0x000012f8 (most recent call first): File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\stream\wrappers.py", line 85 in stop File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\stream\wrappers.py", line 105 in close File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\stream\streamprocess.py", line 27 in close ``` I also have windows 7 x32 and error sometimes reproduced on win 8 only.
Does this only occur on the latest nightly build or the stable build as well? Also what site is this happening on? What does the command you are running look like? - I never used stable build, can't say. - I used my plugin from here: https://raw.githubusercontent.com/xkbd/streamlink/4271aa099ae10a66e6c74b825907f2f3737b10ac/src/streamlink/plugins/bongacams.py (copied it to pkgs\streamlink\plugins) - streamlink https://site_name.domain/streampath Plus in the config: default-stream=best I don't think that this is due to some specific plug-in. With any which use RTMPStream. another reproduce: `streamlink url --player="not-exists-file"` The url should process plugin which will run rtmpdump. @xkbd In my case is not reproducible: ![streamlink_player_not_found](https://cloud.githubusercontent.com/assets/13382316/21955299/3e85cf12-da47-11e6-88cd-9a9c6a5e4b87.JPG) UPD: The url should process plugin which will run rtmpdump. In my case: ``` [cli][info] Opening stream: live (rtmp) [cli][debug] Pre-buffering 8192 bytes [cli][info] Starting player: none error: Failed to start player: none ([WinError 2] Не удается найти указанный файл) Fatal Python error: could not acquire lock for <_io.BufferedReader name=5> at interpreter shutdown, possibly due to daemon threads Thread 0x00001630 (most recent call first): File "c:\python35\lib\site-packages\streamlink\stream\wrappers.py", line 67 in run File "c:\python35\lib\threading.py", line 914 in _bootstrap_inner File "c:\python35\lib\threading.py", line 882 in _bootstrap Current thread 0x00000b20 (most recent call first): File "c:\python35\lib\site-packages\streamlink\stream\wrappers.py", line 85 in stop File "c:\python35\lib\site-packages\streamlink\stream\wrappers.py", line 105 in close File "c:\python35\lib\site-packages\streamlink\stream\streamprocess.py", line 30 in close ``` @xkbd ![streamlink_player_not_found_rtmp](https://cloud.githubusercontent.com/assets/13382316/21955450/33224f9e-da4a-11e6-924a-1a1ac5a08a79.JPG) Edit: If you use `Streamlink.exe "vaughnlive.tv/MEGA_SIMPSON" best --player="not-exists-file"` what happens in your case? streamlink from nightly build - OK Streamlink from C:\Python35\Scripts\: ``` [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/MEGA_SIMPSON [plugin.vaughnlive][debug] Using swf url: http://vaughnlive.tv/4451818440/swf/VaughnSoftPlayer.swf [plugin.vaughnlive][debug] Loading info url: http://mvn.vaughnsoft.net/video/edge/soon_depricated_Q2_2017-live_mega_simpson?0.1.1.782_661-661-0.6530276332369996 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (rtmp) [cli][debug] Pre-buffering 8192 bytes [cli][info] Starting player: not-exists-file error: Failed to start player: not-exists-file ([WinError 2] Не удается найти указанный файл) Fatal Python error: could not acquire lock for <_io.BufferedReader name=5> at interpreter shutdown, possibly due to daemon threads Thread 0x000018a0 (most recent call first): File "c:\python35\lib\site-packages\streamlink\stream\wrappers.py", line 67 in run File "c:\python35\lib\threading.py", line 914 in _bootstrap_inner File "c:\python35\lib\threading.py", line 882 in _bootstrap Current thread 0x00001e74 (most recent call first): File "c:\python35\lib\site-packages\streamlink\stream\wrappers.py", line 85 in stop File "c:\python35\lib\site-packages\streamlink\stream\wrappers.py", line 105 in close File "c:\python35\lib\site-packages\streamlink\stream\streamprocess.py", line 30 in close ``` ``` C:\Python35\Scripts>python --version Python 3.5.2 C:\Python35\Scripts>streamlink.exe -V streamlink.exe 0.2.0 ``` @RosadinTV, can you try run streamlink.exe from python_dir\scripts? ``` C:\Users\user>python -c "from streamlink_cli.main import main;main()" "vaughnlive.tv/MEGA_SIMPSON" best --player="not-exists-file" [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/MEGA_SIMPSON [plugin.vaughnlive][debug] Using swf url: http://vaughnlive.tv/4451818440/swf/VaughnSoftPlayer.swf [plugin.vaughnlive][debug] Loading info url: http://mvn.vaughnsoft.net/video/edge/soon_depricated_Q2_2017-live_mega_simpson?0.1.1.782_685-68 5-0.8773321155576378 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (rtmp) [cli][debug] Pre-buffering 8192 bytes [cli][info] Starting player: not-exists-file error: Failed to start player: not-exists-file ([WinError 2] Не удается найти указанный файл) Fatal Python error: could not acquire lock for <_io.BufferedReader name=5> at interpreter shutdown, possibly due to daemon threads Thread 0x000017d4 (most recent call first): File "C:\Python35\lib\site-packages\streamlink\stream\wrappers.py", line 67 in run File "C:\Python35\lib\threading.py", line 914 in _bootstrap_inner File "C:\Python35\lib\threading.py", line 882 in _bootstrap Current thread 0x00001074 (most recent call first): File "C:\Python35\lib\site-packages\streamlink\stream\wrappers.py", line 85 in stop File "C:\Python35\lib\site-packages\streamlink\stream\wrappers.py", line 105 in close File "C:\Python35\lib\site-packages\streamlink\stream\streamprocess.py", line 30 in close ``` When i use script all is well: ``` C:\Users\user>type test.py from streamlink_cli.main import main main() C:\Users\user>python test.py "vaughnlive.tv/MEGA_SIMPSON" best --player="not-exists-file" [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/MEGA_SIMPSON [plugin.vaughnlive][debug] Using swf url: http://vaughnlive.tv/4451818440/swf/VaughnSoftPlayer.swf [plugin.vaughnlive][debug] Loading info url: http://mvn.vaughnsoft.net/video/edge/soon_depricated_Q2_2017-live_mega_simpson?0.1.1.782_974-97 4-0.23589034015397992 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (rtmp) [cli][debug] Pre-buffering 8192 bytes [cli][info] Starting player: not-exists-file error: Failed to start player: not-exists-file ([WinError 2] Не удается найти указанный файл) ``` @xkbd the error doesn't occur with the streamlink.exe that is installed by the nightly? Doesn't occur [in last case]. In case when rtmpdump crashes (my first message ) - occur. streamlink.exe from windows installer package - runner streamlink-script.py. In my case when i run streamlink from python-script also all is well. But if i run `python.exe -c` [code from streamlink-script.py]: ``` C:\Program Files\Streamlink>Python\python.exe -c "import sys, os;installdir = os.path.dirname('bin');pkgdir = os.path.join(installdir, 'pkgs');sys.path.insert(0, pkgdir);os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '');from streamlink_cli.main import main;main()" "vaughnlive.tv/MEGA_SIMPSON" best --player="not-exists-file" ``` I get 'python fatal error' ``` C:\Program Files\Streamlink>Python\python.exe -c "import sys, os;installdir = os.path.dirname('bin');pkgdir = os.path.join(installdir, 'pkgs ');sys.path.insert(0, pkgdir);os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '');from streamlink_cli.main imp ort main;main()" "vaughnlive.tv/MEGA_SIMPSON" best --player="not-exists-file" Failed to load plugin viagame: File "imp.py", line 234, in load_module File "imp.py", line 172, in load_source File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "pkgs\streamlink\plugins\viagame.py", line 7, in <module> from streamlink.plugin.api.support_plugin import viasat File "pkgs\streamlink\plugin\api\__init__.py", line 27, in __getattr__ return load_support_plugin(name) File "pkgs\streamlink\plugin\api\support_plugin.py", line 39, in load_support_plugin raise ImportError("No module named '{0}'".format(name)) ImportError: No module named 'viasat' [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/MEGA_SIMPSON [plugin.vaughnlive][debug] Using swf url: http://vaughnlive.tv/4451818440/swf/VaughnSoftPlayer.swf [plugin.vaughnlive][debug] Loading info url: http://mvn.vaughnsoft.net/video/edge/soon_depricated_Q2_2017-live_mega_simpson?0.1.1.782_501-50 1-0.07308929867030278 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (rtmp) [cli][debug] Pre-buffering 8192 bytes [cli][info] Starting player: not-exists-file error: Failed to start player: not-exists-file ([WinError 2] Не удается найти указанный файл) Fatal Python error: could not acquire lock for <_io.BufferedReader name=5> at interpreter shutdown, possibly due to daemon threads Thread 0x000010ec (most recent call first): File "pkgs\streamlink\stream\wrappers.py", line 67 in run File "threading.py", line 914 in _bootstrap_inner File "threading.py", line 882 in _bootstrap Current thread 0x00001d54 (most recent call first): File "pkgs\streamlink\stream\wrappers.py", line 85 in stop File "pkgs\streamlink\stream\wrappers.py", line 105 in close File "pkgs\streamlink\stream\streamprocess.py", line 30 in close ``` ``` #foo.py from streamlink_cli.main import main main() ``` What's the difference between `python -c "from streamlink_cli.main import main;main()"` and `python foo.py` ? Why in the first case the interpreter was falling and the second not? @xkbd You are right, when i run Streamlink.exe (Located in Scripts folder after installing via pip) the crash occurs: ![streamlink_player_not_found_rtmp_error](https://cloud.githubusercontent.com/assets/13382316/21958626/3eb23a76-da91-11e6-9d33-7b0b4367d4de.JPG) Are you using the most up go date version of pip? ``` >pip -V pip 9.0.1 from c:\python35\lib\site-packages (python 3.5) ``` pip is not to blame @beardypig Yes, but the crash only occurs in rtmp streams with a "not-exist" player I tested in both portable and installable builds, no crash ocurred, only reproducible in pip. I got another crash with streamlink.exe from windows package :) ``` C:\Program Files\Streamlink\bin>streamlink.exe "vaughnlive.tv/MEGA_SIMPSON" best [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/MEGA_SIMPSON [plugin.vaughnlive][debug] Using swf url: http://vaughnlive.tv/4451818440/swf/VaughnSoftPlayer.swf [plugin.vaughnlive][debug] Loading info url: http://mvn.vaughnsoft.net/video/edge/soon_depricated_Q2_2017-live_mega_simpson?0.1.1.782_530-53 0-0.6985136105910077 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (rtmp) [cli][debug] Pre-buffering 8192 bytes [cli][error] Failed to read data from stream: Read timeout Fatal Python error: could not acquire lock for <_io.BufferedReader name=5> at interpreter shutdown, possibly due to daemon threads Thread 0x000017f8 (most recent call first): File "C:\Program Files\Streamlink\pkgs\streamlink\stream\wrappers.py", line 67 in run File "threading.py", line 914 in _bootstrap_inner File "threading.py", line 882 in _bootstrap Current thread 0x000017a8 (most recent call first): File "C:\Program Files\Streamlink\pkgs\streamlink\stream\wrappers.py", line 85 in stop File "C:\Program Files\Streamlink\pkgs\streamlink\stream\wrappers.py", line 105 in close File "C:\Program Files\Streamlink\pkgs\streamlink\stream\streamprocess.py", line 30 in close ``` Steps to reproduce: - `streamlink.exe "vaughnlive.tv/MEGA_SIMPSON" best` - To obtain `read timeout` suspend rtmpdump.exe process
2017-01-15T08:21:17
streamlink/streamlink
453
streamlink__streamlink-453
[ "276" ]
7f3d947807045c758d01f4d1c8608eb5471125e5
diff --git a/src/streamlink_cli/output.py b/src/streamlink_cli/output.py --- a/src/streamlink_cli/output.py +++ b/src/streamlink_cli/output.py @@ -67,6 +67,8 @@ def _write(self, data): class PlayerOutput(Output): + PLAYER_TERMINATE_TIMEOUT = 10.0 + def __init__(self, cmd, args=DEFAULT_PLAYER_ARGUMENTS, filename=None, quiet=True, kill=True, call=False, http=False, namedpipe=None): super(PlayerOutput, self).__init__() @@ -160,7 +162,15 @@ def _close(self): if self.kill: with ignored(Exception): - self.player.kill() + self.player.terminate() + if not is_win32: + t, timeout = 0.0, self.PLAYER_TERMINATE_TIMEOUT + while not self.player.poll() and t < timeout: + sleep(0.5) + t += 0.5 + + if not self.player.returncode: + self.player.kill() self.player.wait() def _write(self, data):
Less violent way of closing player when stream ends Currently streamlink uses SIGKILL to close the player when a stream ends. This prevents the player from doing its own cleanup. For example, mpv leaves DPMS/screensaver disabled because of this. I know there is --player-no-close option, but that has an unwanted side-effect of not closing the player immediately in some situations. I suggest fixing it by using SIGTERM instead: ```diff diff -bur streamlink-0.1.0-orig/src/streamlink_cli/output.py streamlink-0.1.0/src/streamlink_cli/output.py --- streamlink-0.1.0-orig/src/streamlink_cli/output.py 2016-11-21 21:56:29.000000000 +0200 +++ streamlink-0.1.0/src/streamlink_cli/output.py 2016-12-08 22:08:23.000000000 +0200 @@ -161,7 +161,7 @@ if self.kill: with ignored(Exception): - self.player.kill() + self.player.terminate() self.player.wait() def _write(self, data): ```
Could check to see that the player has terminated after a short while, and possibly kill it after a timeout? @beardypig This sounds like a more reasonable solution. Sending `SIGTERM` doesn't guarantee that the player will shutdown. (eg. see VLC and the `--play-and-exit` parameter) Something like this, with a 5 second time out to kill it... maybe there is a nicer way though. ```diff diff --git a/src/streamlink_cli/output.py b/src/streamlink_cli/output.py index 7488f99..7f36c5f 100644 --- a/src/streamlink_cli/output.py +++ b/src/streamlink_cli/output.py @@ -161,7 +162,15 @@ class PlayerOutput(Output): if self.kill: with ignored(Exception): - self.player.kill() + self.player.terminate() + if not is_win32: + t, timeout = 0.0, 5.0 + while not self.player.poll() and t < timeout: + sleep(0.5) + t += 0.5 + if not self.player.returncode: + self.player.kill() ```
2017-01-20T18:04:09
streamlink/streamlink
469
streamlink__streamlink-469
[ "403" ]
26bcb3039183081bcbef1c3fa7ac0badc6206a22
diff --git a/src/streamlink/compat.py b/src/streamlink/compat.py --- a/src/streamlink/compat.py +++ b/src/streamlink/compat.py @@ -21,14 +21,15 @@ def bytes(b, enc="ascii"): try: from urllib.parse import ( - urlparse, urlunparse, urljoin, quote, unquote, parse_qsl + urlparse, urlunparse, urljoin, quote, unquote, parse_qsl, urlencode ) import queue except ImportError: from urlparse import urlparse, urlunparse, urljoin, parse_qsl - from urllib import quote, unquote + from urllib import quote, unquote, urlencode import Queue as queue + __all__ = ["is_py2", "is_py3", "is_py33", "is_win32", "str", "bytes", "urlparse", "urlunparse", "urljoin", "parse_qsl", "quote", - "unquote", "queue", "range"] + "unquote", "queue", "range", "urlencode"] diff --git a/src/streamlink/plugins/srgssr.py b/src/streamlink/plugins/srgssr.py --- a/src/streamlink/plugins/srgssr.py +++ b/src/streamlink/plugins/srgssr.py @@ -1,32 +1,46 @@ from __future__ import print_function + import re +from streamlink.compat import urlparse, parse_qsl from streamlink.plugin import Plugin from streamlink.plugin.api import http from streamlink.plugin.api import validate -from streamlink.stream import HDSStream from streamlink.stream import HLSStream -from streamlink.compat import urlparse, parse_qsl class SRGSSR(Plugin): - url_re = re.compile(r"https?://(?:www\.)?(srf|rts|rsi|rtr)\.ch/play/tv") + url_re = re.compile(r"""https?://(?:www\.)? + (srf|rts|rsi|rtr)\.ch/ + (?: + play/tv| + livestream/player| + live-streaming| + sport/direct/(\d+)- + )""", re.VERBOSE) api_url = "http://il.srgssr.ch/integrationlayer/1.0/ue/{site}/video/play/{id}.json" - video_id_re = re.compile(r'urn:(srf|rts|rsi|rtr):(?:ais:)?video:([^&"]+)') + token_url = "http://tp.srgssr.ch/akahd/token" + video_id_re = re.compile(r'urn(?:%3A|:)(srf|rts|rsi|rtr)(?:%3A|:)(?:ais(?:%3A|:))?video(?:%3A|:)([^&"]+)') video_id_schema = validate.Schema(validate.transform(video_id_re.search)) api_schema = validate.Schema( - {"Video": - {"Playlists": - {"Playlist": [{ - "@protocol": validate.text, - "url": [{"@quality": validate.text, "text": validate.url()}] - }] + { + "Video": + { + "Playlists": + { + "Playlist": [{ + "@protocol": validate.text, + "url": [{"@quality": validate.text, "text": validate.url()}] + }] + } } - } }, validate.get("Video"), validate.get("Playlists"), validate.get("Playlist")) + token_schema = validate.Schema({"token": {"authparams": validate.text}}, + validate.get("token"), + validate.get("authparams")) @classmethod def can_handle_url(cls, url): @@ -37,11 +51,14 @@ def get_video_id(self): qinfo = dict(parse_qsl(parsed.query or parsed.fragment.lstrip("?"))) site, video_id = None, None + url_m = self.url_re.match(self.url) # look for the video id in the URL, otherwise find it in the page if "tvLiveId" in qinfo: video_id = qinfo["tvLiveId"] - site = self.url_re.match(self.url).group(1) + site = url_m.group(1) + elif url_m.group(2): + site, video_id = url_m.group(1), url_m.group(2) else: video_id_m = http.get(self.url, schema=self.video_id_schema) if video_id_m: @@ -49,8 +66,16 @@ def get_video_id(self): return site, video_id + def get_authparams(self, url): + parsed = urlparse(url) + path, _ = parsed.path.rsplit("/", 1) + token_res = http.get(self.token_url, params=dict(acl=path + "/*")) + authparams = http.json(token_res, schema=self.token_schema) + self.logger.debug("Found authparams: {0}", authparams) + return dict(parse_qsl(authparams)) + def _get_streams(self): - video_id, site = self.get_video_id() + site, video_id = self.get_video_id() if video_id and site: self.logger.debug("Found {0} video ID {1}", site, video_id) @@ -59,11 +84,9 @@ def _get_streams(self): for stream_info in http.json(res, schema=self.api_schema): for url in stream_info["url"]: - if stream_info["@protocol"] == "HTTP-HDS": - for s in HDSStream.parse_manifest(self.session, url["text"]).items(): - yield s if stream_info["@protocol"] == "HTTP-HLS": - for s in HLSStream.parse_variant_playlist(self.session, url["text"]).items(): + params = self.get_authparams(url["text"]) + for s in HLSStream.parse_variant_playlist(self.session, url["text"], params=params).items(): yield s diff --git a/src/streamlink/plugins/swisstxt.py b/src/streamlink/plugins/swisstxt.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/swisstxt.py @@ -0,0 +1,45 @@ +from __future__ import print_function + +import re + +from streamlink.compat import urlparse, parse_qsl, urlunparse +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.stream import HLSStream + + +class Swisstxt(Plugin): + url_re = re.compile(r"""https?://(?: + live\.(rsi)\.ch/| + (?:www\.)?(srf)\.ch/sport/resultcenter + )""", re.VERBOSE) + api_url = "http://event.api.swisstxt.ch/v1/stream/{site}/byEventItemIdAndType/{id}/HLS" + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None and cls.get_event_id(url) + + @classmethod + def get_event_id(cls, url): + return dict(parse_qsl(urlparse(url).query.lower())).get("eventid") + + def get_stream_url(self, event_id): + url_m = self.url_re.match(self.url) + site = url_m.group(1) or url_m.group(2) + api_url = self.api_url.format(id=event_id, site=site.upper()) + self.logger.debug("Calling API: {0}", api_url) + + stream_url = http.get(api_url).text.strip("\"'") + + parsed = urlparse(stream_url) + query = dict(parse_qsl(parsed.query)) + return urlunparse(parsed._replace(query="")), query + + def _get_streams(self): + stream_url, params = self.get_stream_url(self.get_event_id(self.url)) + return HLSStream.parse_variant_playlist(self.session, + stream_url, + params=params) + + +__plugin__ = Swisstxt
diff --git a/tests/test_plugin_srgssr.py b/tests/test_plugin_srgssr.py --- a/tests/test_plugin_srgssr.py +++ b/tests/test_plugin_srgssr.py @@ -3,7 +3,7 @@ from streamlink.plugins.srgssr import SRGSSR -class TestPluginCrunchyroll(unittest.TestCase): +class TestPluginSRGSSR(unittest.TestCase): def test_can_handle_url(self): # should match self.assertTrue(SRGSSR.can_handle_url("http://srf.ch/play/tv/live")) @@ -13,6 +13,8 @@ def test_can_handle_url(self): self.assertTrue(SRGSSR.can_handle_url("http://rtr.ch/play/tv/live")) self.assertTrue(SRGSSR.can_handle_url("http://rts.ch/play/tv/direct#?tvLiveId=3608506")) self.assertTrue(SRGSSR.can_handle_url("http://www.srf.ch/play/tv/live#?tvLiveId=c49c1d64-9f60-0001-1c36-43c288c01a10")) + self.assertTrue(SRGSSR.can_handle_url("http://www.rts.ch/sport/direct/8328501-tennis-open-daustralie.html")) + self.assertTrue(SRGSSR.can_handle_url("http://www.rts.ch/play/tv/tennis/video/tennis-open-daustralie?id=8328501")) # shouldn't match self.assertFalse(SRGSSR.can_handle_url("http://www.crunchyroll.com/gintama")) diff --git a/tests/test_plugin_swisstxt.py b/tests/test_plugin_swisstxt.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_swisstxt.py @@ -0,0 +1,28 @@ +import unittest + +from streamlink.plugins.swisstxt import Swisstxt + + +class TestPluginSwisstxt(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Swisstxt.can_handle_url("http://www.srf.ch/sport/resultcenter/tennis?eventId=338052")) + self.assertTrue(Swisstxt.can_handle_url("http://live.rsi.ch/tennis.html?eventId=338052")) + self.assertTrue(Swisstxt.can_handle_url("http://live.rsi.ch/sport.html?eventId=12345")) + + # shouldn't match + # regular srgssr sites + self.assertFalse(Swisstxt.can_handle_url("http://srf.ch/play/tv/live")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rsi.ch/play/tv/live#?tvLiveId=livestream_La1")) + self.assertFalse(Swisstxt.can_handle_url("http://rsi.ch/play/tv/live?tvLiveId=livestream_La1")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rtr.ch/play/tv/live")) + self.assertFalse(Swisstxt.can_handle_url("http://rtr.ch/play/tv/live")) + self.assertFalse(Swisstxt.can_handle_url("http://rts.ch/play/tv/direct#?tvLiveId=3608506")) + self.assertFalse(Swisstxt.can_handle_url("http://www.srf.ch/play/tv/live#?tvLiveId=c49c1d64-9f60-0001-1c36-43c288c01a10")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rts.ch/sport/direct/8328501-tennis-open-daustralie.html")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rts.ch/play/tv/tennis/video/tennis-open-daustralie?id=8328501")) + + # other sites + self.assertFalse(Swisstxt.can_handle_url("http://www.crunchyroll.com/gintama")) + self.assertFalse(Swisstxt.can_handle_url("http://www.crunchyroll.es/gintama")) + self.assertFalse(Swisstxt.can_handle_url("http://www.youtube.com/"))
SRG SSR plugin Hello Another challenge for beardypig. ;) Swiss public TV includes channels in : - German : SRF 1, SRF 2, SRF Info : `http://www.srf.ch/play/tv/live` - French : RTS Un, RTS Deux, RTS Info : `http://www.rts.ch/play/tv/direct` - Italian : RSI La 1, RSI La 2 : `http://www.rsi.ch/play/tv/live` Sometimes they air live sports events exclusively online on their website. Channels are of course geoblocked to CH but it can be resolved with proxy. Example address source for RTS Un can be found here : `http://il.srgssr.ch/integrationlayer/1.0/ue/rts/video/play/3608506.json` They propose HDS and HLS.
I'll take a look, if I can find a decent Swiss proxy :-) @karlo2105 I had a go, I wasn't able to test it as I couldn't find a working Swiss proxy ... This is added, if you could test it @karlo2105 and confirm we can close this. Thanks very much I will give a try and let you known if i manage with working proxy. ;) When I use proxy, it buffers a bit but with streamlink I got error on all channels. Take a look : `[cli][info] Found matching plugin srgssr for URL http://www.srf.ch/play/tv/live# ?tvLiveId=c4927fcf-e1a0-0001-7edd-1ef01d441651 error: Unable to open URL: http://il.srgssr.ch/integrationlayer/1.0/ue/c4927fcf- e1a0-0001-7edd-1ef01d441651/video/play/srf.json (404 Client Error: Not Found for url: http://il.srgssr.ch/integrationlayer/1.0/ue/c4927fcf-e1a0-0001-7edd-1ef01d 441651/video/play/srf.json) [End of Streamlink for Windows]` Some additional addresses : ---------------------------- SRF.ch ------ `http://www.srf.ch/livestream/player/srf-1` `http://www.srf.ch/livestream/player/srf-2` `http://www.srf.ch/livestream/player/srf-info` Live sports events : you can find below events marked with small cam which will be broadcasted on their website `http://www.srf.ch/sport/resultcenter/results` RTS.ch ------ Live sports events `http://www.rts.ch/sport/programmes/` RSI.ch ------ Live sports events `http://live.rsi.ch/results.html` Live streaming `http://www.rsi.ch/live-streaming/` I send you proxy on PM. Cheers.
2017-01-23T17:27:35
streamlink/streamlink
477
streamlink__streamlink-477
[ "476" ]
5035b696e1b12d43703c288196e29fec5729309d
diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py --- a/src/streamlink/plugins/twitch.py +++ b/src/streamlink/plugins/twitch.py @@ -496,7 +496,10 @@ def _get_hls_streams(self, stream_type="live"): return {} try: - streams = HLSStream.parse_variant_playlist(self.session, url) + # If the stream is a VOD that is still being recorded the stream should start at the + # beginning of the recording + streams = HLSStream.parse_variant_playlist(self.session, url, + force_restart=not stream_type == "live") except IOError as err: err = str(err) if "404 Client Error" in err or "Failed to parse playlist" in err: diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py --- a/src/streamlink/stream/hls.py +++ b/src/streamlink/stream/hls.py @@ -189,7 +189,7 @@ def process_sequences(self, playlist, sequences): self.playlist_end = last_sequence.num if self.playlist_sequence < 0: - if self.playlist_end is None: + if self.playlist_end is None and not self.stream.force_restart: edge_index = -(min(len(sequences), max(int(self.live_edge), 1))) edge_sequence = sequences[edge_index] self.playlist_sequence = edge_sequence.num @@ -252,8 +252,9 @@ class HLSStream(HTTPStream): __shortname__ = "hls" - def __init__(self, session_, url, **args): + def __init__(self, session_, url, force_restart=False, **args): HTTPStream.__init__(self, session_, url, **args) + self.force_restart = force_restart def __repr__(self): return "<HLSStream({0!r})>".format(self.url) @@ -276,6 +277,7 @@ def open(self): @classmethod def parse_variant_playlist(cls, session_, url, name_key="name", name_prefix="", check_streams=False, + force_restart=False, **request_params): """Attempts to parse a variant playlist and return its streams. @@ -283,6 +285,7 @@ def parse_variant_playlist(cls, session_, url, name_key="name", :param name_key: Prefer to use this key as stream name, valid keys are: name, pixels, bitrate. :param name_prefix: Add this prefix to the stream names. + :param force_restart: Start at the first segment even for a live stream :param check_streams: Only allow streams that are accesible. """ @@ -338,7 +341,7 @@ def parse_variant_playlist(cls, session_, url, name_key="name", except Exception: continue - stream = HLSStream(session_, playlist.uri, **request_params) + stream = HLSStream(session_, playlist.uri, force_restart=force_restart, **request_params) streams[name_prefix + stream_name] = stream return streams
Twitch: Playing vods of still recording streams dont start at the beginning Hi. Basicially when you want to watch a vod via streamlink twitch.tv/someguy/v/12344321 high and the vod you are referencing is still getting recorded aka the streamer is still live and the stream is recorded to that vod ( 12344321 ) streamlink will just stream whatever is currently streamed by the streamer. I expected that streamlink would start from the vod beginning tho. If I wanted to watch the current stream, i wouldnt specifiy the vod.
The `HLSStream` class assumes that it's a live stream if the stream is incomplete. As the VOD is still recording it looks the same as a live stream to streamlink, and so plays it from the end. This is normally what you want, except of course, in this case where you are requesting a VOD and you reasonably expect it to start from the beginning. I'll put together a PR to offer a solution.
2017-01-24T16:09:38
streamlink/streamlink
508
streamlink__streamlink-508
[ "507" ]
1d8ba08a061f038bbc4f7980298df921f35a16c7
diff --git a/src/streamlink/plugins/filmon.py b/src/streamlink/plugins/filmon.py --- a/src/streamlink/plugins/filmon.py +++ b/src/streamlink/plugins/filmon.py @@ -1,150 +1,137 @@ import re -from streamlink.compat import urlparse +import time + +from streamlink import StreamError from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate -from streamlink.stream import HLSStream, RTMPStream - -CHINFO_URL = "http://www.filmon.com/ajax/getChannelInfo" -SWF_URL = "http://www.filmon.com/tv/modules/FilmOnTV/files/flashapp/filmon/FilmonPlayer.swf" -VODINFO_URL = "http://www.filmon.com/vod/info/{0}" - -AJAX_HEADERS = { - "Referer": "http://www.filmon.com", - "X-Requested-With": "XMLHttpRequest", - "User-Agent": "Mozilla/5.0" -} -QUALITY_WEIGHTS = { - "high": 720, - "low": 480 -} -STREAM_TYPES = ("hls", "rtmp") - -_url_re = re.compile(r"http(s)?://(\w+\.)?filmon.com/(channel|tv|vod)/") -_channel_id_re = re.compile(r"/channels/(\d+)/extra_big_logo.png") -_vod_id_re = re.compile(r"movie_id=(\d+)") - -_channel_schema = validate.Schema({ - "streams": [{ - "name": validate.text, +from streamlink.stream import HLSStream + + +class FilmOnHLS(HLSStream): + __shortname__ = "hls-filmon" + + def __init__(self, session_, channel=None, vod_id=None, quality="high", **args): + super(FilmOnHLS, self).__init__(session_, None, **args) + self.logger = self.session.logger.new_module("stream.hls-filmon") + self.channel = channel + self.vod_id = vod_id + if self.channel is None and self.vod_id is None: + raise ValueError("channel or vod_id must be set") + self.quality = quality + self.api = FilmOnAPI() + self._url = None + self.watch_timeout = 0 + + def _get_stream_data(self): + if self.channel: + self.logger.debug("Reloading FilmOn channel playlist: {0}", self.channel) + data = self.api.channel(self.channel) + for stream in data["streams"]: + yield stream + elif self.vod_id: + self.logger.debug("Reloading FilmOn VOD playlist: {0}", self.vod_id) + data = self.api.vod(self.vod_id) + for _, stream in data["streams"].items(): + yield stream + + @property + def url(self): + # If the watch timeout has passed then refresh the playlist from the API + if int(time.time()) >= self.watch_timeout: + for stream in self._get_stream_data(): + if stream["quality"] == self.quality: + self.watch_timeout = int(time.time()) + stream["watch-timeout"] + self._url = stream["url"] + return self._url + raise StreamError("cannot refresh FilmOn HLS Stream playlist") + else: + return self._url + + +class FilmOnAPI(object): + channel_url = "http://www.filmon.com/api-v2/channel/{0}?protocol=hls" + vod_url = "http://www.filmon.com/vod/info/{0}" + + stream_schema = { "quality": validate.text, - "url": validate.url(scheme=validate.any("http", "rtmp")) - }] -}) -_vod_schema = validate.Schema( - { - "data": { - "streams": { - validate.text: { - "name": validate.text, - "url": validate.url(scheme=validate.any("http", "rtmp")) - } + "url": validate.url(), + "watch-timeout": int + } + api_schema = validate.Schema( + { + "data": { + "streams": validate.any( + {validate.text: stream_schema}, + [stream_schema] + ) } - } - }, - validate.get("data") -) + }, + validate.get("data") + ) + def channel(self, channel): + res = http.get(self.channel_url.format(channel)) + return http.json(res, schema=self.api_schema) -def ajax(*args, **kwargs): - kwargs["headers"] = AJAX_HEADERS - return http.post(*args, **kwargs) + def vod(self, vod_id): + res = http.get(self.vod_url.format(vod_id)) + return http.json(res, schema=self.api_schema) class Filmon(Plugin): + url_re = re.compile(r"""https?://(?:\w+\.)?filmon.(?:tv|com)/ + (?: + (tv|channel)/(?P<channel>[^/]+)| + vod/view/(?P<vod_id>\d+)-| + group/ + ) + """, re.VERBOSE) + + _channel_id_re = re.compile(r'channel_id\s*?=\s*"(\d+)"') + _channel_id_schema = validate.Schema( + validate.transform(_channel_id_re.search), + validate.any(None, validate.get(1)) + ) + + quality_weights = { + "high": 720, + "low": 480 + } + + def __init__(self, url): + super(Filmon, self).__init__(url) + self.api = FilmOnAPI() + @classmethod def can_handle_url(cls, url): - return _url_re.match(url) + return cls.url_re.match(url) is not None @classmethod def stream_weight(cls, key): - weight = QUALITY_WEIGHTS.get(key) + weight = cls.quality_weights.get(key) if weight: return weight, "filmon" return Plugin.stream_weight(key) - def _create_rtmp_stream(self, stream, live=True): - rtmp = stream["url"] - playpath = stream["name"] - parsed = urlparse(rtmp) - if parsed.query: - app = "{0}?{1}".format(parsed.path[1:], parsed.query) - else: - app = parsed.path[1:] - - if playpath.endswith(".mp4"): - playpath = "mp4:" + playpath - - params = { - "rtmp": rtmp, - "pageUrl": self.url, - "swfUrl": SWF_URL, - "playpath": playpath, - "app": app, - } - if live: - params["live"] = True - - return RTMPStream(self.session, params) - - def _get_live_streams(self, channel_id): - params = {"channel_id": channel_id} - for stream_type in STREAM_TYPES: - cookies = {"flash-player-type": stream_type} - res = ajax(CHINFO_URL, cookies=cookies, data=params) - channel = http.json(res, schema=_channel_schema) - - # TODO: Replace with "yield from" when dropping Python 2. - for stream in self._parse_live_streams(channel): - yield stream - - def _parse_live_streams(self, channel): - for stream in channel["streams"]: - name = stream["quality"] - scheme = urlparse(stream["url"]).scheme - - if scheme == "http": - try: - streams = HLSStream.parse_variant_playlist(self.session, stream["url"]) - for __, stream in streams.items(): - yield name, stream - - except IOError as err: - self.logger.error("Failed to extract HLS stream '{0}': {1}", name, err) - - elif scheme == "rtmp": - yield name, self._create_rtmp_stream(stream) - - def _get_vod_streams(self, movie_id): - for stream_type in STREAM_TYPES: - cookies = {"flash-player-type": stream_type} - res = ajax(VODINFO_URL.format(movie_id), cookies=cookies) - vod = http.json(res, schema=_vod_schema) - - # TODO: Replace with "yield from" when dropping Python 2. - for stream in self._parse_vod_streams(vod): - yield stream - - def _parse_vod_streams(self, vod): - for name, stream in vod["streams"].items(): - scheme = urlparse(stream["url"]).scheme - - if scheme == "http": - yield name, HLSStream(self.session, stream["url"]) - elif scheme == "rtmp": - yield name, self._create_rtmp_stream(stream, live=False) - def _get_streams(self): - res = http.get(self.url) + url_m = self.url_re.match(self.url) - match = _vod_id_re.search(res.text) - if match: - return self._get_vod_streams(match.group(1)) + channel = url_m and url_m.group("channel") + vod_id = url_m and url_m.group("vod_id") - match = _channel_id_re.search(res.text) - if match: - return self._get_live_streams(match.group(1)) + if vod_id: + data = self.api.vod(vod_id) + for _, stream in data["streams"].items(): + yield stream["quality"], FilmOnHLS(self.session, vod_id=vod_id, quality=stream["quality"]) + + else: + if not channel: + channel = http.get(self.url, schema=self._channel_id_schema) + data = self.api.channel(channel) + for stream in data["streams"]: + yield stream["quality"], FilmOnHLS(self.session, channel=channel, quality=stream["quality"]) __plugin__ = Filmon
FilmOn: "no streams found"? Possible plugin "bug" report? (or new user problem! - no other reports?) FilmOn failed using Livestreamer a week ago. Discovered Streamlink! No change! FilmOn plugin is found but "no streams found" for *any* channels like http://www.filmon.com/channel/bbc-one Windows 7 / Streamlink Win install 0.3.0 29/1/17 C:\Users\jb\xD\Portbl\FilmOnHack>"C:\Program Files (x86)\Streamlink\bin\streamlink.exe" http://www.filmon.com/channel/bbc-one high [cli][info] Found matching plugin filmon for URL http://www.filmon.com/channel/bbc-one error: No streams found on this URL: http://www.filmon.com/channel/bbc-one No problems with TVPlayer
Looks like they might have changed the page or streaming URLs or something similar. I'll take a look at it now.
2017-01-30T13:12:49
streamlink/streamlink
535
streamlink__streamlink-535
[ "505" ]
de5439953db92235b0399b3fe52fcba0a507bada
diff --git a/src/streamlink/plugins/crunchyroll.py b/src/streamlink/plugins/crunchyroll.py --- a/src/streamlink/plugins/crunchyroll.py +++ b/src/streamlink/plugins/crunchyroll.py @@ -205,7 +205,8 @@ class Crunchyroll(Plugin): "username": None, "password": None, "purge_credentials": None, - "locale": None + "locale": None, + "session_id": None, }) @classmethod @@ -281,13 +282,14 @@ def _create_api(self): if self.options.get("purge_credentials"): self.cache.set("session_id", None, 0) self.cache.set("auth", None, 0) + self.cache.set("session_id", None, 0) current_time = datetime.datetime.utcnow() device_id = self._get_device_id() # use the crunchyroll locale as an override, for backwards compatibility locale = self.get_option("locale") or self.session.localization.language_code api = CrunchyrollAPI( - self.cache.get("session_id"), self.cache.get("auth"), locale + self.options.get("session_id") or self.cache.get("session_id"), self.cache.get("auth"), locale ) self.logger.debug("Creating session with locale: {0}", locale) diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -1023,6 +1023,14 @@ def keyvalue(value): and reauthenticate. """ ) +plugin.add_argument( + "--crunchyroll-session-id", + metavar="SESSION_ID", + help=""" + Set a specific session ID for crunchyroll, can be used to bypass + region restrictions + """ +) plugin.add_argument( "--livestation-email", metavar="EMAIL", diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -814,6 +814,9 @@ def setup_plugin_options(): if args.crunchyroll_purge_credentials: streamlink.set_plugin_option("crunchyroll", "purge_credentials", args.crunchyroll_purge_credentials) + if args.crunchyroll_session_id: + streamlink.set_plugin_option("crunchyroll", "session_id", + args.crunchyroll_session_id) if args.crunchyroll_locale: streamlink.set_plugin_option("crunchyroll", "locale",
Support providing a custom Crunchyroll session ID The documentation suggests using an HTTP proxy to access region-locked content in Crunchyroll. However this isn't necessary, as all you need to do so is a session ID belonging to the region you want. Now I'm not asking for streamlink to generate one for you, as nice as that would be -- simply that it lets you specify it with an argument (it's only a 32 character string).
How do you set the token? In a cookie? Could that be done like this? [http://www.crunblocker.com/sess_id.php](http://www.crunblocker.com/sess_id.php) [https://github.com/jerryteps/Crunchyroll-Unblocker/tree/master/Crunchyroll%20Unblocker](https://github.com/jerryteps/Crunchyroll-Unblocker/tree/master/Crunchyroll%20Unblocker) > [https://chrome.google.com/webstore/detail/crunchyroll-unblocker/dldddkdajilplfikaadakojgjocbnjim](https://chrome.google.com/webstore/detail/crunchyroll-unblocker/dldddkdajilplfikaadakojgjocbnjim) > This extension works by opening a http connection to a php script which obtains a us session id. The extension then copies the id so Crunchyroll believes you are from the US. > > In case the extension no longer works, you can manually access the US site instead, just find a proxy, clear your cookies (reloading your browser will do), since it saves a US session id, you can just quit out of the proxy and you'll still remain on the US site, even on your own connection, since you still have the US cookies. <del>You can do that already using the command line arguments in streamlink adding something like `--http-cookie "sess_id=rthgyx5gg3lwlcfr2zj5gueooloxxy0u"` should do it. </del> Or not... looks like it would need a special option.
2017-02-05T11:56:00
streamlink/streamlink
543
streamlink__streamlink-543
[ "537" ]
9df6196f7cc572e86cc77db56da5eeba5d3278f2
diff --git a/src/streamlink/utils/l10n.py b/src/streamlink/utils/l10n.py --- a/src/streamlink/utils/l10n.py +++ b/src/streamlink/utils/l10n.py @@ -117,7 +117,10 @@ def language_code(self): @language_code.setter def language_code(self, language_code): if language_code is None: - language_code, _ = locale.getdefaultlocale() + try: + language_code, _ = locale.getdefaultlocale() + except ValueError: + language_code = None if language_code is None or language_code == "C": # cannot be determined language_code = DEFAULT_LANGUAGE_CODE
error: unknown locale: UTF-8 ### Checklist - [x] This is a bug report. ### Description When I run streamlink, and see this error ``` [cli][info] Found matching plugin twitch for URL twitch.tv/dota2ruhub error: unknown locale: UTF-8 ``` Fixed after adding .bash_profile/.zshrc ``` export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ``` ### Reproduction steps / Stream URLs to test 1. Install latest streamlink 0.3.1 2. run streamlink ### Environment details (operating system, python version, etc.) MacOS, Python 2.7.11, system lang eng
2017-02-06T10:09:33
streamlink/streamlink
545
streamlink__streamlink-545
[ "531" ]
9df6196f7cc572e86cc77db56da5eeba5d3278f2
diff --git a/src/streamlink/stream/ffmpegmux.py b/src/streamlink/stream/ffmpegmux.py --- a/src/streamlink/stream/ffmpegmux.py +++ b/src/streamlink/stream/ffmpegmux.py @@ -5,6 +5,8 @@ import subprocess import sys + +from streamlink import StreamError from streamlink.stream import Stream from streamlink.stream.stream import StreamIO from streamlink.utils import NamedPipe @@ -61,7 +63,7 @@ def __init__(self, session, *streams, **options): self.logger = session.logger.new_module("stream.mp4mux-ffmpeg") self.streams = streams - self.pipes = [NamedPipe("foo-{}-{}".format(os.getpid(), random.randint(0, 1000))) for _ in self.streams] + self.pipes = [NamedPipe("ffmpeg-{0}-{1}".format(os.getpid(), random.randint(0, 1000))) for _ in self.streams] self.pipe_threads = [threading.Thread(target=self.copy_to_pipe, args=(self, stream, np)) for stream, np in zip(self.streams, self.pipes)] diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py --- a/src/streamlink/stream/hls.py +++ b/src/streamlink/stream/hls.py @@ -226,7 +226,7 @@ def __init__(self, session, video, audio, force_restart=False, ffmpeg_options=No substreams = map(lambda url: HLSStream(session, url, force_restart=force_restart, **args), [video, audio]) ffmpeg_options = ffmpeg_options or {} - super(MuxedHLSStream, self).__init__(session, *substreams, **ffmpeg_options) + super(MuxedHLSStream, self).__init__(session, *substreams, format="mpegts", **ffmpeg_options) class HLSStream(HTTPStream): @@ -297,6 +297,7 @@ def parse_variant_playlist(cls, session_, url, name_key="name", streams = {} for playlist in filter(lambda p: not p.is_iframe, parser.playlists): names = dict(name=None, pixels=None, bitrate=None) + fallback_audio = None default_audio = None preferred_audio = None @@ -304,15 +305,16 @@ def parse_variant_playlist(cls, session_, url, name_key="name", if media.type == "VIDEO" and media.name: names["name"] = media.name elif media.type == "AUDIO": - if media.default: - default_audio = media + if not fallback_audio and media.default: + fallback_audio = media + # if the media is "audoselect" and it better matches the users preferences, use that # instead of default - if media.autoselect and locale.equivalent(language=media.language): + if not default_audio and (media.autoselect and locale.equivalent(language=media.language)): default_audio = media # select the first audio stream that matches the users explict language selection - if not preferred_audio and locale.explicit and locale.equivalent(language=media.language): + if (not preferred_audio or media.default) and locale.explicit and locale.equivalent(language=media.language): preferred_audio = media if playlist.stream_info.resolution: @@ -350,11 +352,11 @@ def parse_variant_playlist(cls, session_, url, name_key="name", except Exception: continue - external_audio = preferred_audio or default_audio + external_audio = preferred_audio or default_audio or fallback_audio if external_audio and external_audio.uri and FFMPEGMuxer.is_usable(session_): - logger.debug("Using external audio track for stream {0} (language={1})".format( + logger.debug("Using external audio track for stream {0} (language={1}, name={2})".format( name_prefix + stream_name, - external_audio.language)) + external_audio.language, external_audio.name or "N/A")) stream = MuxedHLSStream(session_, video=playlist.uri,
No audio stream is parsed from some hlsvariant playlists *Thanks for reporting an issue!* *Please read the contribution guidelines first!* *Feel free to use the following template. Be as detailed as possible.* *Don't forget to remove this text before submitting.* ---- ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description streamlink parses a playlist but only identifies the video streams. It does not identify or list the audio streams from the playlist ... ### Expected / Actual behavior When passing an m3u8 playlist to streamlink, I would expect it to do 1 of 2 things. 1. Identify the relevant audio stream and pass both the video and audio through 2. If it is incapable of passing 2 individual streams, then the audio stream should be selectable separately from the video so we can pull and mux them manually ... ### Reproduction steps / Stream URLs to test 1. This requires you to be in Canada or be on a VPN in Canada. streamlink "hlsvariant://http://v.watch.cbc.ca/p//38e815a-0099a76a62b//CBC_MR_D_SEASON_01_S01E01-8626003/CBC_MR_D_SEASON_01_S01E01-8626003__desktop.m3u8?cbcott=st=1486012428~exp=1486098828~acl=/*~hmac=a4adc1fd286adec16084a193e0317a92699f71ba23afae73543675eb8e9262dd" streamlink only identifies the video streams. If you select one, no audio will be passed through. ### Environment details (operating system, python version, etc.) Windows 10 64bit Utilizing the latest windows installer build ... ### Comments, logs, screenshots, etc. Attached is the actual m3u8 playlist from the website. [CBC_MR_D_SEASON_01_S01E02-8626777__desktop.txt](https://github.com/streamlink/streamlink/files/751328/CBC_MR_D_SEASON_01_S01E02-8626777__desktop.txt)
Are you using 0.3.1? It should support separate audio streams, what if you run it with `-l debug` and report the output here? When I was testing this last night 0.3.0 was the latest. I see the new 0.3.1 release but I don't see the windows installer available. Does someone build that and add it later? Can I use the portable tool to build the .exe automatically and just replace the one I have? The installer will be fixed soon :-) Can you get the debug log an post it here? `streamlink -l debug "hlsvariant://http://v.watch.cbc.ca/p//38e815a-0099a76a62b//CBC_MR_D_SEASON_01_S01E01-8626003/CBC_MR_D_SEASON_01_S01E01-8626003__desktop.m3u8?cbcott=st=1486012428~exp=1486098828~acl=/*~hmac=a4adc1fd286adec16084a193e0317a92699f71ba23afae73543675eb8e9262dd"` I just finished building the newest release from source and it now recognizes the audio tracks! Unfortunately, the stream ends after only a few seconds of playback. Debug logging below. ```[cli][info] Found matching plugin stream for URL hlsvariant://http://v.watch.cbc.ca/p//38e815a-0099a76a62b//CBC_MR_D_SEASON_01_S01E01-8626003/CBC_MR_D_SEASON_01_S01E01-8626003__desktop.m3u8?cbcott=st=1486012428~exp=1486098828~acl=/*~hmac=a4adc1fd286adec16084a193e0317a92699f71ba23afae73543675eb8e9262dd [hls.parse_variant_playlist][debug] Using external audio track for stream 720p (language=eng) [hls.parse_variant_playlist][debug] Using external audio track for stream 720p_alt (language=eng) [hls.parse_variant_playlist][debug] Using external audio track for stream 540p (language=eng) [hls.parse_variant_playlist][debug] Using external audio track for stream 360p (language=eng) [hls.parse_variant_playlist][debug] Using external audio track for stream 360p_alt (language=eng) [hls.parse_variant_playlist][debug] Using external audio track for stream 234p (language=eng) [cli][info] Available streams: 720p_alt, 360p_alt, 234p (worst), 360p, 540p, 720p (best) [cli][info] Opening stream: 720p (hls-multi) [stream.hls][debug] Reloading playlist [stream.hls][debug] Segments in this playlist are encrypted [stream.hls][debug] Adding segment 0 to queue [stream.hls][debug] Reloading playlist [stream.hls][debug] Adding segment 1 to queue [stream.hls][debug] Adding segment 2 to queue [stream.hls][debug] Adding segment 3 to queue [stream.hls][debug] Adding segment 4 to queue [stream.hls][debug] Adding segment 5 to queue [stream.hls][debug] Adding segment 6 to queue [stream.hls][debug] Adding segment 7 to queue [stream.hls][debug] Adding segment 8 to queue [stream.hls][debug] Adding segment 9 to queue [stream.hls][debug] Adding segment 10 to queue [stream.hls][debug] Adding segment 11 to queue [stream.hls][debug] Adding segment 12 to queue [stream.hls][debug] Adding segment 13 to queue [stream.hls][debug] Adding segment 14 to queue [stream.hls][debug] Adding segment 15 to queue [stream.hls][debug] Adding segment 16 to queue [stream.hls][debug] Adding segment 17 to queue [stream.hls][debug] Adding segment 18 to queue [stream.hls][debug] Adding segment 19 to queue [stream.hls][debug] Adding segment 20 to queue [stream.hls][debug] Adding segment 21 to queue [stream.hls][debug] Adding segment 0 to queue [stream.hls][debug] Adding segment 1 to queue [stream.hls][debug] Adding segment 2 to queue [stream.hls][debug] Adding segment 3 to queue [stream.hls][debug] Adding segment 4 to queue [stream.hls][debug] Adding segment 5 to queue [stream.hls][debug] Adding segment 6 to queue [stream.hls][debug] Adding segment 7 to queue [stream.hls][debug] Adding segment 8 to queue [stream.hls][debug] Adding segment 9 to queue [stream.hls][debug] Adding segment 10 to queue [stream.hls][debug] Adding segment 11 to queue [stream.hls][debug] Adding segment 12 to queue [stream.hls][debug] Adding segment 13 to queue [stream.hls][debug] Adding segment 14 to queue [stream.hls][debug] Adding segment 15 to queue [stream.hls][debug] Adding segment 16 to queue [stream.hls][debug] Adding segment 17 to queue [stream.hls][debug] Adding segment 18 to queue [stream.hls][debug] Adding segment 19 to queue [stream.hls][debug] Adding segment 20 to queue [stream.hls][debug] Adding segment 21 to queue [stream.mp4mux-ffmpeg][debug] ffmpeg command: C:\Program Files (x86)\Streamlink\ffmpeg\ffmpeg.exe -nostats -y -i \\.\pipe\foo-7432-561 -i \\.\pipe\foo-7432-79 -c:v copy -c:a copy -f matroska pipe:1 [stream.mp4mux-ffmpeg][debug] Starting copy to pipe: \\.\pipe\foo-7432-561 [stream.mp4mux-ffmpeg][debug] Starting copy to pipe: \\.\pipe\foo-7432-79 [cli][debug] Pre-buffering 8192 bytes [stream.hls][debug] Download of segment 0 complete [stream.hls][debug] Adding segment 22 to queue [cli][debug] Checking file output [stream.hls][debug] Download of segment 1 complete [stream.hls][debug] Adding segment 23 to queue [stream.hls][debug] Download of segment 2 complete [stream.hls][debug] Adding segment 24 to queue [stream.hls][debug] Download of segment 0 complete [stream.hls][debug] Adding segment 22 to queue [stream.hls][debug] Download of segment 3 complete [stream.hls][debug] Adding segment 25 to queue [stream.hls][debug] Download of segment 4 complete [stream.hls][debug] Adding segment 26 to queue [stream.hls][debug] Download of segment 5 complete [stream.hls][debug] Adding segment 27 to queue [stream.hls][debug] Download of segment 6 complete [stream.hls][debug] Adding segment 28 to queue [stream.hls][debug] Download of segment 7 complete [stream.hls][debug] Adding segment 29 to queue [stream.hls][debug] Download of segment 8 complete [stream.hls][debug] Adding segment 30 to queue [stream.hls][debug] Download of segment 9 complete [stream.hls][debug] Adding segment 31 to queue [stream.hls][debug] Download of segment 10 complete [stream.hls][debug] Adding segment 32 to queue [stream.hls][debug] Download of segment 11 complete [stream.hls][debug] Adding segment 33 to queue [stream.hls][debug] Download of segment 12 complete [stream.hls][debug] Adding segment 34 to queue [stream.hls][debug] Download of segment 13 complete [stream.hls][debug] Adding segment 35 to queue [stream.hls][debug] Download of segment 14 complete [stream.hls][debug] Adding segment 36 to queue [stream.hls][debug] Download of segment 15 complete [stream.hls][debug] Adding segment 37 to queue [cli][debug] Writing stream to output [stream.mp4mux-ffmpeg][debug] Closing ffmpeg thread [stream.hls][debug] Closing worker thread [stream.hls][debug] Closing writer thread [stream.mp4mux-ffmpeg][debug] Pipe copy complete: \\.\pipe\foo-7432-561 [stream.hls][debug] Download of segment 16 complete [stream.hls][debug] Adding segment 38 to queue [stream.hls][debug] Download of segment 17 complete [stream.hls][debug] Adding segment 39 to queue [stream.hls][debug] Download of segment 18 complete [stream.hls][debug] Adding segment 40 to queue [stream.hls][debug] Download of segment 19 complete [stream.hls][debug] Adding segment 41 to queue [stream.hls][debug] Download of segment 20 complete [stream.hls][debug] Adding segment 42 to queue [stream.hls][debug] Download of segment 21 complete [stream.hls][debug] Adding segment 43 to queue [stream.hls][debug] Download of segment 22 complete [stream.hls][debug] Adding segment 44 to queue [stream.hls][debug] Download of segment 23 complete [stream.hls][debug] Adding segment 45 to queue [stream.hls][debug] Download of segment 24 complete [stream.hls][debug] Adding segment 46 to queue [stream.hls][debug] Download of segment 25 complete [stream.hls][debug] Adding segment 47 to queue [stream.hls][debug] Download of segment 26 complete [stream.hls][debug] Adding segment 48 to queue [stream.hls][debug] Download of segment 27 complete [stream.hls][debug] Adding segment 49 to queue [stream.hls][debug] Download of segment 28 complete [stream.hls][debug] Adding segment 50 to queue [stream.hls][debug] Download of segment 29 complete [stream.hls][debug] Adding segment 51 to queue [stream.hls][debug] Download of segment 30 complete [stream.hls][debug] Adding segment 52 to queue [stream.hls][debug] Download of segment 31 complete [stream.hls][debug] Adding segment 53 to queue [stream.hls][debug] Download of segment 32 complete [stream.hls][debug] Adding segment 54 to queue [stream.hls][debug] Download of segment 33 complete [stream.hls][debug] Adding segment 55 to queue [stream.hls][debug] Download of segment 34 complete [stream.hls][debug] Adding segment 56 to queue [stream.hls][debug] Download of segment 35 complete [stream.hls][debug] Adding segment 57 to queue [stream.hls][debug] Download of segment 36 complete [stream.hls][debug] Adding segment 58 to queue [stream.hls][debug] Download of segment 37 complete [stream.hls][debug] Adding segment 59 to queue [stream.hls][debug] Download of segment 38 complete [stream.hls][debug] Adding segment 60 to queue [stream.hls][debug] Download of segment 39 complete [stream.hls][debug] Adding segment 61 to queue [stream.hls][debug] Download of segment 40 complete [stream.hls][debug] Adding segment 62 to queue [stream.hls][debug] Download of segment 41 complete [stream.hls][debug] Adding segment 63 to queue [stream.hls][debug] Download of segment 42 complete [stream.hls][debug] Adding segment 64 to queue [stream.hls][debug] Download of segment 43 complete [stream.hls][debug] Adding segment 65 to queue [stream.hls][debug] Download of segment 44 complete [stream.hls][debug] Adding segment 66 to queue [stream.hls][debug] Download of segment 45 complete [stream.hls][debug] Adding segment 67 to queue [stream.hls][debug] Download of segment 46 complete [stream.hls][debug] Adding segment 68 to queue [stream.hls][debug] Download of segment 47 complete [stream.hls][debug] Adding segment 69 to queue [stream.hls][debug] Download of segment 48 complete [stream.hls][debug] Adding segment 70 to queue [stream.hls][debug] Download of segment 49 complete [stream.hls][debug] Adding segment 71 to queue [stream.hls][debug] Download of segment 50 complete [stream.hls][debug] Adding segment 72 to queue [stream.hls][debug] Download of segment 51 complete [stream.hls][debug] Adding segment 73 to queue [stream.hls][debug] Download of segment 1 complete [stream.hls][debug] Closing worker thread [stream.hls][debug] Closing writer thread [stream.mp4mux-ffmpeg][debug] Pipe copy complete: \\.\pipe\foo-7432-79 [stream.hls][debug] Download of segment 52 complete [stream.mp4mux-ffmpeg][debug] Closed all the substreams [cli][info] Stream ended [cli][info] Closing currently open stream... [stream.mp4mux-ffmpeg][debug] Closing ffmpeg thread [stream.mp4mux-ffmpeg][debug] Closed all the substreams [stream.mp4mux-ffmpeg][debug] Closing ffmpeg thread [stream.mp4mux-ffmpeg][debug] Closed all the substreams``` Interesting, I will take a look. What page did you extract through stream URL from? This is the URL. http://watch.cbc.ca/mr-d/season-1/episode-1/38e815a-0099a76a62b OK, thanks. I'll take a look at it in next couple of days :-)
2017-02-06T12:34:09
streamlink/streamlink
551
streamlink__streamlink-551
[ "547" ]
0a61f6a1f3a75d610e07c1b3e05af290e7b262e9
diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py --- a/src/streamlink/stream/hls.py +++ b/src/streamlink/stream/hls.py @@ -39,6 +39,7 @@ def create_decryptor(self, key, sequence): if self.key_uri != key.uri: res = self.session.http.get(key.uri, exception=StreamError, + retries=self.retries, **self.reader.request_params) self.key_data = res.content self.key_uri = key.uri
Recurring issue with live streams Hi, I successfully make working some live streams but i experienced an issue and i can't show everything and even if i post a link of a master .m3u8, it will not work because it needs an authentication as well. (cookies with sensitive stuff) I try this way : livestreamer --http-header "User-Agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" --http-cookie "cookie=###########" --player-continuous-http -- "hlsvariant://https://ncdn.***.sfr.fr/iphone/tf1_no_vmst_hd.m3u8?msisdn=*-9****V&transid=er_error&ServiceId=pctv&gt=1*******0&loginterval=0&media=pctv&life=3600&tokenname=SFRPLAY3&key=**********" best Everything work but after one minute, sometimes a bit more the stream stops and i got this on the shell : ``` [cli][info] Available streams: 180p (worst), 360p, 576p, 720p (best) [cli][info] Starting player: /usr/bin/vlc [cli][info] Got HTTP request from VLC/2.2.4 LibVLC/2.2.4 [cli][info] Opening stream: 720p (hls) Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/usr/lib/python2.7/dist-packages/livestreamer/stream/segmented.py", line 160, in run self.write(segment, result) File "/usr/lib/python2.7/dist-packages/livestreamer/stream/hls.py", line 89, in write sequence.num) File "/usr/lib/python2.7/dist-packages/livestreamer/stream/hls.py", line 46, in create_decryptor **self.reader.request_params) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 469, in get return self.request('GET', url, **kwargs) File "/usr/lib/python2.7/dist-packages/livestreamer/plugin/api/http_session.py", line 128, in request *args, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 569, in send r = adapter.send(request, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 362, in send timeout=timeout File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 516, in urlopen body=body, headers=headers) File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 331, in _make_request httplib_response = conn.getresponse(buffering=True) File "/usr/lib/python2.7/httplib.py", line 1111, in getresponse response.begin() File "/usr/lib/python2.7/httplib.py", line 444, in begin version, status, reason = self._read_status() File "/usr/lib/python2.7/httplib.py", line 400, in _read_status line = self.fp.readline(_MAXLINE + 1) File "/usr/lib/python2.7/socket.py", line 476, in readline data = self._sock.recv(self._rbufsize) File "/usr/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 200, in recv return self.recv(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 188, in recv data = self.connection.recv(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 995, in recv self._raise_ssl_error(self._ssl, result) File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 862, in _raise_ssl_error raise SysCallError(errno, errorcode[errno]) SysCallError: (104, 'ECONNRESET') [cli][error] Error when reading from stream: Read timeout [cli][info] Stream ended [cli][info] Got HTTP request from VLC/2.2.4 LibVLC/2.2.4 [cli][info] Opening stream: 720p (hls) ``` It does that indefinitely. it is a loop ! I have to wait 20-30 seconds before the live stream restarts. I hope there is an easy workaround to fix this issue. I tried this from Debian 8 Thanks.
Here is an example of a master m3u8 ``` #EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=363878,RESOLUTION=320x180,CODECS="mp4a.40.5,avc1.42c01e" http://ncdn-sr.adam.sfr.fr/iphone/bfm_sport_299968/bfm_sport.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=663910,RESOLUTION=640x360,CODECS="mp4a.40.5,avc1.42c01e" http://ncdn-sr.adam.sfr.fr/iphone/bfm_sport_600000/bfm_sport.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1063910,RESOLUTION=640x360,CODECS="mp4a.40.5,avc1.42c01e" http://ncdn-sr.adam.sfr.fr/iphone/bfm_sport_1000000/bfm_sport.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2063910,RESOLUTION=1024x576,CODECS="mp4a.40.5,avc1.4d401f" http://ncdn-sr.adam.sfr.fr/iphone/bfm_sport_2000000/bfm_sport.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=3063910,RESOLUTION=1280x720,CODECS="mp4a.40.5,avc1.640028" http://ncdn-sr.adam.sfr.fr/iphone/bfm_sport_3000000/bfm_sport.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=4063910,RESOLUTION=1280x720,CODECS="mp4a.40.5,avc1.640028" http://ncdn-sr.adam.sfr.fr/iphone/bfm_sport_4000000/bfm_sport.m3u8 ``` And this... ``` #EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:26877 #EXT-X-VERSION:4 #EXT-X-KEY:METHOD=AES-128,URI="https://ncdn.adam.sfr.fr/iphone/bfm_sport_4000000/key4479" #EXTINF:9.96, http://abv1-ncdn-edge-video00.cdn.sfr.fr/ncdn-sr.adam.sfr.fr/iphone/bfm_sport_4000000/bfm_sport00026877.ts #EXTINF:9.96, http://abv1-ncdn-edge-video00.cdn.sfr.fr/ncdn-sr.adam.sfr.fr/iphone/bfm_sport_4000000/bfm_sport00026878.ts #EXTINF:9.96, http://abv1-ncdn-edge-video00.cdn.sfr.fr/ncdn-sr.adam.sfr.fr/iphone/bfm_sport_4000000/bfm_sport00026879.ts #EXT-X-KEY:METHOD=AES-128,URI="https://ncdn.adam.sfr.fr/iphone/bfm_sport_4000000/key4480" #EXTINF:9.96, http://abv1-ncdn-edge-video00.cdn.sfr.fr/ncdn-sr.adam.sfr.fr/iphone/bfm_sport_4000000/bfm_sport00026880.ts #EXTINF:9.96, http://abv1-ncdn-edge-video00.cdn.sfr.fr/ncdn-sr.adam.sfr.fr/iphone/bfm_sport_4000000/bfm_sport00026881.ts ``` I noticed on the browser console that a key is requested every minute. Thanks for any suggestion.
2017-02-08T09:44:50
streamlink/streamlink
562
streamlink__streamlink-562
[ "562" ]
5c7fcdf559d84fc2b0fe1695c509c8bc5b130bfd
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -46,7 +46,7 @@ sys_path.insert(0, srcdir) setup(name="streamlink", - version="0.3.1", + version="0.3.2", description="Streamlink is command-line utility that extracts streams " "from various services and pipes them into a video player of " "choice.", diff --git a/src/streamlink/__init__.py b/src/streamlink/__init__.py --- a/src/streamlink/__init__.py +++ b/src/streamlink/__init__.py @@ -12,7 +12,7 @@ __title__ = "streamlink" -__version__ = "0.3.1" +__version__ = "0.3.2" __license__ = "Simplified BSD" __author__ = "Streamlink" __copyright__ = "Copyright 2016 Streamlink"
0.3.2 Release Closes #562
2017-02-10T15:16:08
streamlink/streamlink
579
streamlink__streamlink-579
[ "576" ]
f76b1fc7b0adf6d9d4d7ed7a1b1376d301a5f0bd
diff --git a/src/streamlink/plugins/ard_mediathek.py b/src/streamlink/plugins/ard_mediathek.py --- a/src/streamlink/plugins/ard_mediathek.py +++ b/src/streamlink/plugins/ard_mediathek.py @@ -2,7 +2,7 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate -from streamlink.stream import HTTPStream, HDSStream, RTMPStream +from streamlink.stream import HTTPStream, HDSStream, HLSStream MEDIA_URL = "http://www.ardmediathek.de/play/media/{0}" SWF_URL = "http://www.ardmediathek.de/ard/static/player/base/flash/PluginFlash.swf" @@ -16,7 +16,7 @@ } _url_re = re.compile(r"http(s)?://(\w+\.)?ardmediathek.de/tv") -_media_id_re = re.compile(r"/play/config/(\d+)") +_media_id_re = re.compile(r"/play/(?:media|config)/(\d+)") _media_schema = validate.Schema({ "_mediaArray": [{ "_mediaStreamArray": [{ @@ -33,6 +33,10 @@ validate.get("base"), validate.url(scheme="http") ), + "cdn": validate.all( + validate.xml_find("head/meta"), + validate.get("cdn") + ), "videos": validate.all( validate.xml_findall("body/seq/video"), [validate.get("src")] @@ -61,17 +65,8 @@ def _get_hds_streams(self, info): url = info["_stream"] + HDCORE_PARAMETER return HDSStream.parse_manifest(self.session, url, pvswf=SWF_URL).items() - def _get_rtmp_streams(self, info): - name = QUALITY_MAP.get(info["_quality"], "live") - params = { - "rtmp": info["_server"].strip(), - "playpath": info["_stream"], - "pageUrl": self.url, - "swfVfy": SWF_URL, - "live": True - } - stream = RTMPStream(self.session, params) - yield name, stream + def _get_hls_streams(self, info): + return HLSStream.parse_variant_playlist(self.session, info["_stream"]).items() def _get_smil_streams(self, info): res = http.get(info["_stream"]) @@ -79,7 +74,7 @@ def _get_smil_streams(self, info): for video in smil["videos"]: url = "{0}/{1}{2}".format(smil["base"], video, HDCORE_PARAMETER) - streams = HDSStream.parse_manifest(self.session, url, pvswf=SWF_URL) + streams = HDSStream.parse_manifest(self.session, url, pvswf=SWF_URL, is_akamai=smil["cdn"] == "akamai") # TODO: Replace with "yield from" when dropping Python 2. for stream in streams.items(): @@ -93,6 +88,8 @@ def _get_streams(self): else: return + self.logger.debug("Found media id: {0}", media_id) + res = http.get(MEDIA_URL.format(media_id)) media = http.json(res, schema=_media_schema) @@ -104,25 +101,23 @@ def _get_streams(self): if not stream_: continue stream_ = stream_[0] - stream_ = stream_.strip() - if server.startswith("rtmp://"): - parser = self._get_rtmp_streams - parser_name = "RTMP" - elif stream_.endswith(".f4m"): + if stream_.endswith(".f4m"): parser = self._get_hds_streams parser_name = "HDS" elif stream_.endswith(".smil"): parser = self._get_smil_streams parser_name = "SMIL" + elif stream_.endswith(".m3u8"): + parser = self._get_hls_streams + parser_name = "HLS" elif stream_.startswith("http"): parser = self._get_http_streams parser_name = "HTTP" try: - # TODO: Replace with "yield from" when dropping Python 2. - for stream in parser(stream): - yield stream + for s in parser(stream): + yield s except IOError as err: self.logger.error("Failed to extract {0} streams: {1}", parser_name, err)
ard_mediathek plugin fails with 403 error ### Description Whenever I try to watch the ARD livestream I can use neither of the available plugins. However, the most promising solutions seems to be the `ard_mediathek` plugin. Unfortunately, I'm getting a `403 Client error` when trying to use it. ### Reproduction steps / Stream URLs to test ``` $ streamlink http://www.ardmediathek.de/tv/Das-Erste/live?kanal=208 best [cli][info] Found matching plugin ard_mediathek for URL http://www.ardmediathek.de/tv/Das-Erste/live?kanal=208 [plugin.ard_mediathek][error] Failed to extract SMIL streams: Unable to open URL: http://live-lh.daserste.de/z//daserste_de@446299/manifest.f4m?hdcore?hdcore=3.3.0 (403 Client Error: Forbidden for url: http://live-lh.daserste.de/z//daserste_de@446299/manifest.f4m?hdcore?hdcore=3.3.0) [cli][info] Available streams: auto (worst, best) [cli][info] Opening stream: auto (http) [cli][info] Starting player: mpv [cli][info] Stream ended [cli][info] Closing currently open stream... $ ``` Opening the URL in any modern browser (Firefox, Chrome et al) works out of the box. ### Environment details (operating system, python version, etc.) - Ubuntu 16.10 - Streamlink 0.3.2 ``` $ cat .config/streamlink/config twitch-oauth-token=secret player=mpv hls-live-edge=60 hds-live-edge=60 hls-segment-attempts=10 hds-segment-attempts=10 hls-segment-threads=4 hds-segment-threads=4 ``` ### Comments, logs, screenshots, etc. Notice how I wouldn't be be able to use the `ard_live` plugin either since its URL schema (`live.daserste.de`) redirects to `http://www.daserste.de/live/index.html`, which the plugin doesn't recognize. Additionally, the redirection URL (`http://live-lh.daserste.de`) is not covered by any plugin at all yet.
2017-02-13T11:37:26
streamlink/streamlink
597
streamlink__streamlink-597
[ "595" ]
57d699b719fa8825e53c79c72a565597c3d8dcdc
diff --git a/src/streamlink_cli/utils/http_server.py b/src/streamlink_cli/utils/http_server.py --- a/src/streamlink_cli/utils/http_server.py +++ b/src/streamlink_cli/utils/http_server.py @@ -23,6 +23,7 @@ def send_error(self, code, message): class HTTPServer(object): def __init__(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.conn = self.host = self.port = None self.bound = False @@ -111,4 +112,5 @@ def close(self, client_only=False): self.conn.close() if not client_only: + self.socket.shutdown(2) self.socket.close()
Address already in use Is there a way to unbind the port once streamlink is stopped? It takes sometimes up to a minute before the port can be used by some other process.
How are you exiting Streamlink? CTRL+c or kill -9 PID I take it you mean when using the http player option? Correct.
2017-02-16T23:10:21
streamlink/streamlink
608
streamlink__streamlink-608
[ "604" ]
8ff8c2caf4dcebca45bfe928db886b4d73b6c23f
diff --git a/src/streamlink_cli/utils/http_server.py b/src/streamlink_cli/utils/http_server.py --- a/src/streamlink_cli/utils/http_server.py +++ b/src/streamlink_cli/utils/http_server.py @@ -112,5 +112,8 @@ def close(self, client_only=False): self.conn.close() if not client_only: - self.socket.shutdown(2) + try: + self.socket.shutdown(2) + except OSError: + pass self.socket.close()
When I close VLC I get this error ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description ``` [cli][info] Player closed [cli][info] Stream ended [cli][info] Closing currently open stream... Traceback (most recent call last): File "d:\Program Files (x86)\Streamlink\bin\streamlink-script.py", line 12, in <module> main() File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 952 , in main handle_url() File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 499 , in handle_url handle_stream(plugin, streams, stream_name) File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 381 , in handle_stream success = output_stream(stream) File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 270 , in output_stream read_stream(stream_fd, output, prebuffer) File "contextlib.py", line 159, in __exit__ File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\output.py", line 2 8, in close self._close() File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\output.py", line 1 58, in _close self.http.close() File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\utils\http_server. py", line 115, in close self.socket.shutdown(2) OSError: [WinError 10057] A request to send or receive data was disallowed becau se the socket is not connected and (when sending on a datagram socket using a se ndto call) no address was supplied ``` ### Expected / Actual behavior Not to happen ### Reproduction steps / Stream URLs to test just close vlc when watching a twitch stream ### Environment details (operating system, python version, etc.) Win7 64bit latest nightly ### Comments, logs, screenshots, etc. @gravyboat @beardypig do you get this error too?
2017-02-20T09:06:34
streamlink/streamlink
647
streamlink__streamlink-647
[ "342" ]
66d256c9ee4778111c55e2ddf43329ad1066e210
diff --git a/src/streamlink/plugins/earthcam.py b/src/streamlink/plugins/earthcam.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/earthcam.py @@ -0,0 +1,100 @@ +from __future__ import print_function + +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream, RTMPStream +from streamlink.utils import parse_json + + +class EarthCam(Plugin): + url_re = re.compile(r"https?://(?:www.)?earthcam.com/.*") + playpath_re = re.compile(r"(?P<folder>/.*/)(?P<file>.*?\.flv)") + swf_url = "http://static.earthcam.com/swf/streaming/stream_viewer_v3.swf" + json_base_re = re.compile(r"""var[ ]+json_base[^=]+=.*?(\{.*?});""", re.DOTALL) + cam_name_re = re.compile(r"""var[ ]+currentName[^=]+=[ \t]+(?P<quote>["'])(?P<name>\w+)(?P=quote);""", re.DOTALL) + cam_data_schema = validate.Schema( + validate.transform(json_base_re.search), + validate.any( + None, + validate.all( + validate.get(1), + validate.transform(lambda d: d.replace("\\/", "/")), + validate.transform(parse_json), + ) + ) + ) + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _get_streams(self): + res = http.get(self.url) + m = self.cam_name_re.search(res.text) + cam_name = m and m.group("name") + json_base = self.cam_data_schema.validate(res.text) + + cam_data = json_base["cam"][cam_name] + + self.logger.debug("Found cam for {0} - {1}", cam_data["group"], cam_data["title"]) + + is_live = (cam_data["liveon"] == "true" and cam_data["defaulttab"] == "live") + + # HLS data + hls_domain = cam_data["html5_streamingdomain"] + hls_playpath = cam_data["html5_streampath"] + + # RTMP data + rtmp_playpath = "" + if is_live: + n = "live" + rtmp_domain = cam_data["streamingdomain"] + rtmp_path = cam_data["livestreamingpath"] + rtmp_live = cam_data["liveon"] + + if rtmp_path: + match = self.playpath_re.search(rtmp_path) + rtmp_playpath = match.group("file") + rtmp_url = rtmp_domain + match.group("folder") + else: + n = "vod" + rtmp_domain = cam_data["archivedomain"] + rtmp_path = cam_data["archivepath"] + rtmp_live = cam_data["archiveon"] + + if rtmp_path: + rtmp_playpath = rtmp_path + rtmp_url = rtmp_domain + + # RTMP stream + if rtmp_playpath: + self.logger.debug("RTMP URL: {0}{1}", rtmp_url, rtmp_playpath) + + params = { + "rtmp": rtmp_url, + "playpath": rtmp_playpath, + "pageUrl": self.url, + "swfUrl": self.swf_url, + "live": rtmp_live + } + + yield n, RTMPStream(self.session, params) + + # HLS stream + if hls_playpath and is_live: + hls_url = hls_domain + hls_playpath + + self.logger.debug("HLS URL: {0}", hls_url) + + for s in HLSStream.parse_variant_playlist(self.session, hls_url).items(): + yield s + + if not (rtmp_playpath or hls_playpath): + self.logger.error("This cam stream appears to be in offline or " + "snapshot mode and not live stream can be played.") + return + +__plugin__ = EarthCam
Earthcam plugin on streamlink Happy new year streamlink team! Listen I want everyone to make a plugin for earthcam so I can look at the live camera around NYC and the world thanks.
Can you please provide details regarding what the URL looks like for specific cameras/streaming?
2017-03-02T00:16:28
streamlink/streamlink
684
streamlink__streamlink-684
[ "681" ]
b89d4a0af636244834e5aa959e37e78a2686cc1a
diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py --- a/src/streamlink/stream/hls.py +++ b/src/streamlink/stream/hls.py @@ -289,6 +289,7 @@ def parse_variant_playlist(cls, session_, url, name_key="name", # Backwards compatibility with "namekey" and "nameprefix" params. name_key = request_params.pop("namekey", name_key) name_prefix = request_params.pop("nameprefix", name_prefix) + audio_select = session_.options.get("hls-audio-select") res = session_.http.get(url, exception=IOError, **request_params) @@ -321,8 +322,10 @@ def parse_variant_playlist(cls, session_, url, name_key="name", default_audio = media # select the first audio stream that matches the users explict language selection - if (not preferred_audio or media.default) and locale.explicit and locale.equivalent( - language=media.language): + if ((media.language == audio_select or media.name == audio_select) or + ((not preferred_audio or media.default) and + locale.explicit and + locale.equivalent(language=media.language))): preferred_audio = media # final fallback on the first audio stream listed diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -652,6 +652,15 @@ def boolean(value): Default is 60.0. """) +transport.add_argument( + "--hls-audio-select", + type=str, + metavar="CODE", + help=""" + Selects a specific audio source, by language code, when multiple audio sources are available. + + Note: This is only useful in special circumstances where the regular locale option fails. + """) transport.add_argument( "--http-stream-timeout", type=num(float, min=0), diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -718,6 +718,9 @@ def setup_options(): if args.hls_timeout: streamlink.set_option("hls-timeout", args.hls_timeout) + if args.hls_audio_select: + streamlink.set_option("hls-audio-select", args.hls_audio_select) + if args.hds_live_edge: streamlink.set_option("hds-live-edge", args.hds_live_edge)
Question about multi audio streams (hls live streams) ### Checklist - [ ] This is a bug report. - [ ] This is a plugin request. - [x] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description When i try to play a live stream with more than one audio stream, i can't. This issue is exactly what i need #485 In my case, the english audio stream is named "qaa" and the french one "fra" However i can play separately the "qaa" and "qad" audio streams. Thanks ### Expected / Actual behavior Playing any audio stream when it is possible. ### Reproduction steps / Stream URLs to test ``` #EXTM3U #EXT-X-VERSION:4 #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",LANGUAGE="fra",NAME="fra",AUTOSELECT=YES,DEFAULT=YES #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",LANGUAGE="qaa",NAME="qaa",AUTOSELECT=NO,DEFAULT=NO,URI="http://ncdn-sr.adam.sfr.fr/iphone/tf1_audio_qaa/tf1.m3u8" #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",LANGUAGE="qad",NAME="qad",AUTOSELECT=NO,DEFAULT=NO,URI="http://ncdn-sr.adam.sfr.fr/iphone/tf1_audio_qad/tf1.m3u8" #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=364050,RESOLUTION=320x180,CODECS="mp4a.40.5,avc1.42c01e",AUDIO="audio" http://ncdn-sr.adam.sfr.fr/iphone/tf1_299968/tf1.m3u8 ``` ### Environment details (operating system, python version, etc.) Python 2.7 on Debian 8 ### Comments, logs, screenshots, etc.
2017-03-09T13:26:48
streamlink/streamlink
693
streamlink__streamlink-693
[ "690" ]
4f49822e7cdf5c20a871ccd34c145108ba5e19aa
diff --git a/src/streamlink/plugins/vaughnlive.py b/src/streamlink/plugins/vaughnlive.py --- a/src/streamlink/plugins/vaughnlive.py +++ b/src/streamlink/plugins/vaughnlive.py @@ -4,9 +4,9 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate from streamlink.stream import RTMPStream +from streamlink.utils import swfdecompress -PLAYER_VERSION = "0.1.1.782" -INFO_URL = "http://mvn.vaughnsoft.net/video/edge/soon__depricated_Q2_2017-{domain}_{channel}?{version}_{ms}-{ms}-{random}" +INFO_URL = "http://{site}{path}{domain}_{channel}?{version}_{ms}-{ms}-{random}" DOMAIN_MAP = { "breakers": "btv", @@ -60,46 +60,63 @@ def _get_streams(self): match = _swf_player_re.search(res.text) if match is None: return - swfUrl = "http://vaughnlive.tv" + match.group(1) - self.logger.debug("Using swf url: {0}", swfUrl) - - match = _url_re.match(self.url) - params = {} - params["channel"] = match.group("channel").lower() - params["domain"] = DOMAIN_MAP.get(match.group("domain"), match.group("domain")) - params["version"] = PLAYER_VERSION - params["ms"] = random.randint(0, 999) - params["random"] = random.random() - info_url = INFO_URL.format(**params) - self.logger.debug("Loading info url: {0}", INFO_URL.format(**params)) - info = http.get(info_url, schema=_schema) - if not info: - self.logger.info("This stream is currently available") - return + swf_url = "http://vaughnlive.tv" + match.group(1) + self.logger.debug("Using swf url: {0}", swf_url) + + swfres = http.get(swf_url) + swfdata = swfdecompress(swfres.content).decode("latin1") + + player_version_m = re.search(r"0\.\d+\.\d+\.\d+", swfdata) + info_url_domain_m = re.search(r"\w+\.vaughnsoft\.net", swfdata) + info_url_path_m = re.search(r"/video/edge/[a-zA-Z0-9_]+-", swfdata) + + player_version = player_version_m and player_version_m.group(0) + info_url_domain = info_url_domain_m and info_url_domain_m.group(0) + info_url_path = info_url_path_m and info_url_path_m.group(0) + + if player_version and info_url_domain and info_url_path: + self.logger.debug("Found player_version={0}, info_url_domain={1}, info_url_path={2}", + player_version, info_url_domain, info_url_path) + match = _url_re.match(self.url) + params = {"channel": match.group("channel").lower(), + "domain": DOMAIN_MAP.get(match.group("domain"), match.group("domain")), + "version": player_version, + "ms": random.randint(0, 999), + "random": random.random(), + "site": info_url_domain, + "path": info_url_path} + info_url = INFO_URL.format(**params) + self.logger.debug("Loading info url: {0}", INFO_URL.format(**params)) + + info = http.get(info_url, schema=_schema) + if not info: + self.logger.info("This stream is currently unavailable") + return + + app = "live" + self.logger.debug("Streaming server is: {0}", info["server"]) + if info["server"].endswith(":1337"): + app = "live-{0}".format(info["ingest"].lower()) + + stream = RTMPStream(self.session, { + "rtmp": "rtmp://{0}/live".format(info["server"]), + "app": "{0}?{1}".format(app, info["token"]), + "swfVfy": swf_url, + "pageUrl": self.url, + "live": True, + "playpath": "{domain}_{channel}".format(**params), + }) - app = "live" - if info["server"] in ["198.255.17.18:1337", "198.255.17.66:1337", "50.7.188.2:1337"]: - if info["ingest"] == "SJC": - app = "live-sjc" - elif info["ingest"] == "NYC": - app = "live-nyc" - elif info["ingest"] == "ORD": - app = "live-ord" - elif info["ingest"] == "AMS": - app = "live-ams" - elif info["ingest"] == "DEN": - app = "live-den" - - stream = RTMPStream(self.session, { - "rtmp": "rtmp://{0}/live".format(info["server"]), - "app": "{0}?{1}".format(app, info["token"]), - "swfVfy": swfUrl, - "pageUrl": self.url, - "live": True, - "playpath": "{domain}_{channel}".format(**params), - }) - - return dict(live=stream) + return dict(live=stream) + else: + self.logger.info("Found player_version={0}, info_url_domain={1}, info_url_path={2}", + player_version, info_url_domain, info_url_path) + if not player_version: + self.logger.error("Could not detect player_version") + if not info_url_domain: + self.logger.error("Could not detect info_url_domain") + if not info_url_path: + self.logger.error("Could not detect info_url_path") __plugin__ = VaughnLive
vaughnlive error: Unable to validate response text: '' does not equal '<error></error>' or Minimum length is 3 but value is 1 Using latest nightly and this plugin https://github.com/streamlink/streamlink/pull/383/files/4f7d4f683ce61c0d10908d71603e8df40d744a27..0de2ede40755ee4b76fac8b2d9c8d3204f649b0a Thank you
2017-03-10T16:50:33
streamlink/streamlink
694
streamlink__streamlink-694
[ "688" ]
4f49822e7cdf5c20a871ccd34c145108ba5e19aa
diff --git a/src/streamlink/plugins/beam.py b/src/streamlink/plugins/beam.py --- a/src/streamlink/plugins/beam.py +++ b/src/streamlink/plugins/beam.py @@ -1,66 +1,109 @@ import re +from streamlink.compat import urlparse, parse_qsl, urljoin from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate +from streamlink.stream import HLSStream +from streamlink.stream import HTTPStream from streamlink.stream import RTMPStream -_url_re = re.compile(r"http(s)?://(\w+.)?beam.pro/(?P<channel>[^/]+)") - -CHANNEL_INFO = "https://beam.pro/api/v1/channels/{0}" -CHANNEL_MANIFEST = "https://beam.pro/api/v1/channels/{0}/manifest.smil" - -_assets_schema = validate.Schema( - validate.union({ - "base": validate.all( - validate.xml_find("./head/meta"), - validate.get("base"), - validate.url(scheme="rtmp") - ), - "videos": validate.all( - validate.xml_findall(".//video"), - [ - validate.union({ - "src": validate.all( - validate.get("src"), - validate.text - ), - "height": validate.all( - validate.get("height"), - validate.text, - validate.transform(int) - ) - }) - ] - ) - }) -) +_url_re = re.compile(r"http(s)?://(\w+.)?beam.pro/(?P<channel>[^/?]+)") class Beam(Plugin): + api_url = "https://beam.pro/api/v1/{type}/{id}" + channel_manifest = "https://beam.pro/api/v1/channels/{id}/manifest.{type}" + + _vod_schema = validate.Schema({ + "state": "AVAILABLE", + "vods": [{ + "baseUrl": validate.url(), + "data": validate.any(None, { + "Height": int + }), + "format": validate.text + }] + }, + validate.get("vods"), + validate.filter(lambda x: x["format"] in ("raw", "hls")), + [validate.union({ + "url": validate.get("baseUrl"), + "format": validate.get("format"), + "height": validate.all(validate.get("data"), validate.get("Height")) + })]) + _assets_schema = validate.Schema( + validate.union({ + "base": validate.all( + validate.xml_find("./head/meta"), + validate.get("base"), + validate.url(scheme="rtmp") + ), + "videos": validate.all( + validate.xml_findall(".//video"), + [ + validate.union({ + "src": validate.all( + validate.get("src"), + validate.text + ), + "height": validate.all( + validate.get("height"), + validate.text, + validate.transform(int) + ) + }) + ] + ) + }) + ) + @classmethod - def can_handle_url(self, url): + def can_handle_url(cls, url): return _url_re.match(url) - def _get_streams(self): - match = _url_re.match(self.url) - channel = match.group("channel") - res = http.get(CHANNEL_INFO.format(channel)) + def _get_vod_stream(self, vod_id): + res = http.get(self.api_url.format(type="recordings", id=vod_id)) + for sdata in http.json(res, schema=self._vod_schema): + if sdata["format"] == "hls": + hls_url = urljoin(sdata["url"], "manifest.m3u8") + yield "{0}p".format(sdata["height"]), HLSStream(self.session, hls_url) + elif sdata["format"] == "raw": + raw_url = urljoin(sdata["url"], "source.mp4") + yield "{0}p".format(sdata["height"]), HTTPStream(self.session, raw_url) + + def _get_live_stream(self, channel): + res = http.get(self.api_url.format(type="channels", id=channel)) channel_info = http.json(res) if not channel_info["online"]: return - res = http.get(CHANNEL_MANIFEST.format(channel_info["id"])) - assets = http.xml(res, schema=_assets_schema) - streams = {} + res = http.get(self.channel_manifest.format(id=channel_info["id"], type="smil")) + assets = http.xml(res, schema=self._assets_schema) + for video in assets["videos"]: name = "{0}p".format(video["height"]) stream = RTMPStream(self.session, { "rtmp": "{0}/{1}".format(assets["base"], video["src"]) }) - streams[name] = stream + yield name, stream + + for s in HLSStream.parse_variant_playlist(self.session, + self.channel_manifest.format(id=channel_info["id"], type="m3u8")).items(): + yield s + + def _get_streams(self): + params = dict(parse_qsl(urlparse(self.url).query)) + vod_id = params.get("vod") + match = _url_re.match(self.url) + channel = match.group("channel") - return streams + if vod_id: + self.logger.debug("Looking for VOD {0} from channel: {1}", vod_id, channel) + return self._get_vod_stream(vod_id) + else: + self.logger.debug("Looking for channel: {0}", channel) + return self._get_live_stream(channel) __plugin__ = Beam
[0.4.0] beam.pro VODs don't work ### Checklist - [ ] This is a bug report. - [ ] This is a plugin request. - [x] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description When inputting a beam.pro VOD link into streamlink, you get a 404 Client Error. API problem? ### Expected / Actual behavior The VOD plays as normal. ### Environment details (operating system, python version, etc.) Windows 8.1 64bit, MPC-HC, Streamlink 0.4.0. ### Comments, logs, screenshots, etc. `````` 'streamlink.exe --player-passthrough hls https://vodcdn.beam.pro/content_e613c2b1-c3b3-4bb9-9014-7a73b60f8f75/16845301-5961-4442-aeb7-82214480fa71/ best' [cli][info] Found matching plugin beam for URL https://vodcdn.beam.pro/content_e613c2b1-c3b3-4bb9-9014-7a73b60f8f75/16845301-5961-4442-aeb7-82214480fa71/ error: Unable to open URL: https://beam.pro/api/v1/channels/content_e613c2b1-c3b3-4bb9-9014-7a73b60f8f75 (404 Client Error: Not Found for url: https://beam.pro/api/v1/channels/content_e613c2b1-c3b3-4bb9-9014-7a73b60f8f75) `````` Going by the straight URL from beam.pro website, I get: `````` 'streamlink.exe --player-passthrough hls https://beam.pro/revocane?vod=1079377 best' [cli][info] Found matching plugin beam for URL https://beam.pro/revocane?vod=1079377 error: No playable streams found on this URL: https://beam.pro/revocane?vod=1079377 ``````
Did this work previously? From what I recall beam.pro has never worked (VODs or livestreams) because they use WebRTC which is a lot of work to implement and we don't support it currently. We had some discussion on it here: https://github.com/streamlink/streamlink/issues/497 and closed it out, it's just too big to tackle right now. I'm honestly not sure. I just saw the 'matching plugin' line and assumed that it was supposed to. Livestreams from beam.pro work by the way, using rmtp and with the best quality possible. Tested with 1080p. @Tharn I'm thinking of the low latency streams. My bad.
2017-03-10T17:55:19
streamlink/streamlink
696
streamlink__streamlink-696
[ "695" ]
192571b8ab4e4ebc1c7391257825e5347fcb2645
diff --git a/src/streamlink/plugins/alieztv.py b/src/streamlink/plugins/aliez.py similarity index 94% rename from src/streamlink/plugins/alieztv.py rename to src/streamlink/plugins/aliez.py --- a/src/streamlink/plugins/alieztv.py +++ b/src/streamlink/plugins/aliez.py @@ -8,13 +8,8 @@ from streamlink.stream import HTTPStream, RTMPStream _url_re = re.compile(r""" - http(s)?://(\w+\.)?aliez.tv - (?: - /live/[^/]+ - )? - (?: - /video/\d+/[^/]+ - )? + https?://(\w+\.)?aliez.\w+/ + (?:live/[^/]+|video/\d+/[^/]+) """, re.VERBOSE) _file_re = re.compile(r"\"?file\"?:\s+['\"]([^'\"]+)['\"]") _swf_url_re = re.compile(r"swfobject.embedSWF\(\"([^\"]+)\",")
Plugin request: Aliez.tv to Aliez.me ### Checklist - [x] This is a bug report. - [x] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description Aliez.tv does not exist anymore there is Aliez.me which is actually the same streaming site. ### Reproduction steps / Stream URLs to test 1. http://aliez.me/live/fkpev212/ link im trying to open in player
Maybe it would be interesting to include in plugin aliez.* instead of aliez.me. That way once they change domain name it won't be required to adapt plugin.
2017-03-11T23:37:55
streamlink/streamlink
724
streamlink__streamlink-724
[ "722" ]
951edb3ef8127598ec518e5ebab7dedf5e00f68c
diff --git a/src/streamlink/plugins/bigo.py b/src/streamlink/plugins/bigo.py --- a/src/streamlink/plugins/bigo.py +++ b/src/streamlink/plugins/bigo.py @@ -47,7 +47,7 @@ def close(self): class Bigo(Plugin): - _url_re = re.compile(r"https?://(live.bigo.tv/\d+|bigoweb.co/show/\d+)") + _url_re = re.compile(r"https?://(?:www\.)?(bigo\.tv/\d+|bigoweb\.co/show/\d+)") _flashvars_re = flashvars = re.compile( r'''^\s*(?<!<!--)<param.*value="tmp=(\d+)&channel=(\d+)&srv=(\d+\.\d+\.\d+\.\d+)&port=(\d+)"''', re.M)
diff --git a/tests/test_plugin_bigo.py b/tests/test_plugin_bigo.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_bigo.py @@ -0,0 +1,31 @@ +import unittest + +from streamlink.plugins.bigo import Bigo + + +class TestPluginBongacams(unittest.TestCase): + def test_can_handle_url(self): + # Correct urls + self.assertTrue(Bigo.can_handle_url("http://www.bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("https://www.bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("http://bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("https://bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("http://bigo.tv/00000000")) + self.assertTrue(Bigo.can_handle_url("https://bigo.tv/00000000")) + self.assertTrue(Bigo.can_handle_url("https://www.bigo.tv/00000000")) + self.assertTrue(Bigo.can_handle_url("http://www.bigo.tv/00000000")) + + # Old URLs don't work anymore + self.assertFalse(Bigo.can_handle_url("http://live.bigo.tv/00000000")) + self.assertFalse(Bigo.can_handle_url("https://live.bigo.tv/00000000")) + + # Wrong URL structure + self.assertFalse(Bigo.can_handle_url("ftp://www.bigo.tv/00000000")) + self.assertFalse(Bigo.can_handle_url("https://www.bigo.tv/show/00000000")) + self.assertFalse(Bigo.can_handle_url("http://www.bigo.tv/show/00000000")) + self.assertFalse(Bigo.can_handle_url("http://bigo.tv/show/00000000")) + self.assertFalse(Bigo.can_handle_url("https://bigo.tv/show/00000000")) + + +if __name__ == "__main__": + unittest.main()
bigoweb.co / bigolive.tv plugin no longer works ---- ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description error: No plugin can handle bigoweb.co addressess as of 10 minutes ago ### Expected / Actual behavior 10 minutes ago it worked fine and now it gives an error. ... ### Reproduction steps / Stream URLs to test 1. ...http://www.bigoweb.co/ (any stream) 2. ... 3. ... ### Environment details (operating system, python version, etc.) ... ### Comments, logs, screenshots, etc. ...
2017-03-21T09:08:18
streamlink/streamlink
726
streamlink__streamlink-726
[ "704" ]
8ba8044528b4b6e75899776e696e14f1a9f1af36
diff --git a/src/streamlink/plugins/garena.py b/src/streamlink/plugins/garena.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/garena.py @@ -0,0 +1,69 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream + +_url_re = re.compile(r"https?\:\/\/garena\.live\/(?:(?P<channel_id>\d+)|(?P<alias>\w+))") + + +class Garena(Plugin): + API_INFO = "https://garena.live/api/channel_info_get" + API_STREAM = "https://garena.live/api/channel_stream_get" + + _info_schema = validate.Schema( + { + "reply": validate.any({ + "channel_id": int, + }, None), + "result": validate.text + } + ) + _stream_schema = validate.Schema( + { + "reply": validate.any({ + "streams": [ + { + "url": validate.text, + "resolution": int, + "bitrate": int, + "format": int + } + ] + }, None), + "result": validate.text + } + ) + + @classmethod + def can_handle_url(self, url): + return _url_re.match(url) + + def _post_api(self, api, payload, schema): + res = http.post(api, json=payload) + data = http.json(res, schema=schema) + + if data["result"] == "success": + post_data = data["reply"] + return post_data + + def _get_streams(self): + match = _url_re.match(self.url) + if match.group("alias"): + payload = {"alias": match.group("alias")} + info_data = self._post_api(self.API_INFO, payload, self._info_schema) + channel_id = info_data["channel_id"] + elif match.group("channel_id"): + channel_id = int(match.group("channel_id")) + + if channel_id: + payload = {"channel_id": channel_id} + stream_data = self._post_api(self.API_STREAM, payload, self._stream_schema) + for stream in stream_data["streams"]: + n = "{0}p".format(stream["resolution"]) + if stream["format"] == 3: + s = HLSStream(self.session, stream["url"]) + yield n, s + +__plugin__ = Garena
diff --git a/tests/test_plugin_garena.py b/tests/test_plugin_garena.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_garena.py @@ -0,0 +1,86 @@ +import json +import unittest + +from streamlink import Streamlink + +try: + from unittest.mock import patch, Mock +except ImportError: + from mock import patch, Mock + +from streamlink.plugins.garena import Garena + + +class TestPluginGarena(unittest.TestCase): + def setUp(self): + self.session = Streamlink() + + def test_can_handle_url(self): + # should match + self.assertTrue(Garena.can_handle_url("https://garena.live/LOLTW")) + self.assertTrue(Garena.can_handle_url("https://garena.live/358220")) + + # shouldn't match + self.assertFalse(Garena.can_handle_url("http://local.local/")) + self.assertFalse(Garena.can_handle_url("http://localhost.localhost/")) + + @patch('streamlink.plugins.garena.http') + def test_post_api_info(self, mock_http): + API_INFO = Garena.API_INFO + schema = Garena._info_schema + + api_data = { + "reply": { + "channel_id": 358220, + }, + "result": "success" + } + + api_resp = Mock() + api_resp.text = json.dumps(api_data) + mock_http.post.return_value = api_resp + mock_http.json.return_value = api_data + + payload = {"alias": "LOLTW"} + + plugin = Garena("https://garena.live/LOLTW") + + info_data = plugin._post_api(API_INFO, payload, schema) + + self.assertEqual(info_data["channel_id"], 358220) + + mock_http.post.assert_called_with(API_INFO, json=dict(alias="LOLTW")) + + @patch('streamlink.plugins.garena.http') + def test_post_api_stream(self, mock_http): + API_STREAM = Garena.API_STREAM + schema = Garena._stream_schema + + api_data = { + "reply": { + "streams": [ + { + "url": "https://test.se/stream1", + "bitrate": 0, + "resolution": 1080, + "format": 3 + }, + ] + }, + "result": "success" + } + + api_resp = Mock() + api_resp.text = json.dumps(api_data) + mock_http.post.return_value = api_resp + mock_http.json.return_value = api_data + + payload = {"channel_id": 358220} + + plugin = Garena("https://garena.live/358220") + + stream_data = plugin._post_api(API_STREAM, payload, schema) + + self.assertEqual(stream_data["streams"], api_data["reply"]["streams"]) + + mock_http.post.assert_called_with(API_STREAM, json=dict(channel_id=358220))
Plugin request: https://garena.live ### Checklist - [ ] This is a bug report. - [x] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description Ability to grab livestreams from https://garena.live
Could you provide some more details regarding what requests look like when pulling a live stream from this site? streamlink.exe https://garena.live/xxx best ``` https://garena.live/391550 API_URL = https://garena.live/api/channel_stream_get data = {"channel_id": 391550} res = { "reply": { "streams": [{ "url": "https://twdatagarenatv-a.akamaihd.net/hls/162142/391550.m3u8", "bitrate": 2000, "resolution": 720, "format": 3 }, { "url": "rtmp://124.108.162.142/live/391550", "bitrate": 2000, "resolution": 720, "format": 1 }] }, "result": "success" } ```
2017-03-21T16:36:43
streamlink/streamlink
774
streamlink__streamlink-774
[ "685" ]
3ff628463d1eadfab7c4b7ca37f2ee4e98aaa777
diff --git a/src/streamlink/plugins/chaturbate.py b/src/streamlink/plugins/chaturbate.py --- a/src/streamlink/plugins/chaturbate.py +++ b/src/streamlink/plugins/chaturbate.py @@ -1,37 +1,53 @@ import re +import uuid from streamlink.plugin import Plugin -from streamlink.plugin.api import http, validate +from streamlink.plugin.api import http +from streamlink.plugin.api import validate from streamlink.stream import HLSStream -_url_re = re.compile(r"http(s)?://(\w+.)?chaturbate.com/[^/?&]+") -_playlist_url_re = re.compile(r"var hlsSource\w+ = '(?P<url>[^']+)';") -_schema = validate.Schema( - validate.transform(_playlist_url_re.search), - validate.any( - None, - validate.all( - validate.get("url"), - validate.url( - scheme="http", - path=validate.endswith(".m3u8") - ) - ) - ) +API_HLS = "https://chaturbate.com/get_edge_hls_url_ajax/" + +_url_re = re.compile(r"https?://(\w+\.)?chaturbate\.com/(?P<username>\w+)") + +_post_schema = validate.Schema( + { + "url": validate.text, + "room_status": validate.text, + "success": int + } ) class Chaturbate(Plugin): @classmethod - def can_handle_url(self, url): + def can_handle_url(cls, url): return _url_re.match(url) def _get_streams(self): - playlist_url = http.get(self.url, schema=_schema) - if not playlist_url: - return + match = _url_re.match(self.url) + username = match.group("username") + + CSRFToken = str(uuid.uuid4().hex.upper()[0:32]) + + headers = { + "Content-Type": "application/x-www-form-urlencoded", + "X-CSRFToken": CSRFToken, + "X-Requested-With": "XMLHttpRequest", + "Referer": self.url, + } + + cookies = { + "csrftoken": CSRFToken, + } + + post_data = "room_slug={0}&bandwidth=high".format(username) - return HLSStream.parse_variant_playlist(self.session, playlist_url) + res = http.post(API_HLS, headers=headers, cookies=cookies, data=post_data) + data = http.json(res, schema=_post_schema) + if data["success"] is True and data["room_status"] == "public": + for s in HLSStream.parse_variant_playlist(self.session, data["url"]).items(): + yield s __plugin__ = Chaturbate
diff --git a/tests/test_plugin_chaturbate.py b/tests/test_plugin_chaturbate.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_chaturbate.py @@ -0,0 +1,15 @@ +import unittest + +from streamlink.plugins.chaturbate import Chaturbate + + +class TestPluginChaturbate(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Chaturbate.can_handle_url("https://chaturbate.com/username")) + self.assertTrue(Chaturbate.can_handle_url("https://m.chaturbate.com/username")) + self.assertTrue(Chaturbate.can_handle_url("https://www.chaturbate.com/username")) + + # shouldn't match + self.assertFalse(Chaturbate.can_handle_url("http://local.local/")) + self.assertFalse(Chaturbate.can_handle_url("http://localhost.localhost/"))
Issue Capturing Some Chaturbate Models ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description Issue when recording some models from Chaturbate. I can view models just fine but when trying to use streamlink I get an error(in the logs section). Doing a bit of playing around I have noticed that if I try from the US it does work fine. I believe this is due to CB using a different edge server. All models that I have an issue with seem to be on the edge55 server. Not sure if this is a CB issue, but due to the fact that I can view the same models as normal i think this may be an issue with the plugin. ### Expected / Actual behavior Models don't record when they should. ### Reproduction steps / Stream URLs to test 1. http://chaturbate.com/ellieleen/ 2. http://chaturbate.com/squirtbetty/ 3. http://chaturbate.com/caylin/ ### Environment details (operating system, python version, etc.) Tried on Debian and Server 2012 with the same result. Also tried with python 2.7 and 3.5 ### Comments, logs, screenshots, etc. [Streamlink for Windows v0.3.2 - Git b89d4a0] [cli][info] Found matching plugin chaturbate for URL https://chaturbate.com/elli eleen/ error: Unable to open URL: https://edge55.stream.highwebmedia.com/live-edge/elli eleen-sd-59241ab9b0a5237d2885fb6d5786a58c87ab56e07868db0e2e17ccc97451f0af_fast_a ac/playlist.m3u8 (502 Server Error: Bad Gateway for url: https://edge55.stream.h ighwebmedia.com/live-edge/ellieleen-sd-59241ab9b0a5237d2885fb6d5786a58c87ab56e07 868db0e2e17ccc97451f0af_fast_aac/playlist.m3u8) [End of Streamlink for Windows]
Why not to add support to rtmp by priority and to ship K-S-V rtmpdump along with all Windows builds ? @karlo, I suggest other solution: set your own path, no need to pack extras with streamlink. C:\>path PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\P\STREAMLINK \bin;C:\AP;C:\AP\CURL;C:\AP\7Z;C:\AP\FF;C:\AP\RDUMP;C:\P\M;C:\P\VLC There are number of ways to do that, one is making registry patch ( restart PC after applying the patch ): Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\Environment] "PATH"="C:\\AP;C:\\AP\\CURL;C:\\AP\\7Z;C:\\AP\\FF;C:\\AP\\RDUMP;C:\\P\\M;C:\\P\\VLC" support to rtmp by priority is already there, the problem is streamlink still does not see rtmp stream on filmon.com. Stream options: --stream-types TYPES, --stream-priority TYPES A comma-delimited list of stream types to allow. The order will be used to separate streams when there are multiple streams with the same name but different stream types. Default is "rtmp,hls,hds,http,akamaihd". C:\>streamlink --stream-url http://www.filmon.com/channel/bbc-news best http://edge-1273-de-fr.filmon.com/live/27.high.stream/playlist.m3u8?id=035bca1a71b11fce016d28acd3dbea51cbc96ddfe5b9ed3f8 fe3286df6a738d3e46fd0aa6eb035753c5b95150828ac01628b2b6d0d9ff1702708aa24b7987ec409b485865e24cb2636dd43dacaa8a18e4f7310fd1 6202b81b5d6e49766403d988a3f15f8a45b0929dc2c491239fc328584074ceaf5a3ef8b1bf64714c3b909047a541e472ea179cb41a90c5847362d83a 328519b78b1da92 C:\>curl -s http://www.filmon.com/api-v2/channel/27?protocol=rtmp {"code":200,"message":"OK","data":{"id":27,"title":"BBC News","alias":"bbc-news","description":"The BBC's 24-hour news a nd information channel that features the most up-to-date news, interviews, business reports, sports results, and weather . Plus, catch the best of the BBC's award-winning current affairs, documentary, and lifestyle programming. ","group":"UK LIVE TV","group_id":5,"group_alias":"uk-live-tv","type":"standard","is_free":false,"is_free_sd_mode":true,"is_adult":fa lse,"is_interactive":false,"is_vod":false,"is_vox":false,"is360":false,"watch_free_time":45,"is_local":true,"seekable":f alse,"user_subscribed":false,"streams":[{"is_free":false,"name":"27.low.stream","quality":"low","url":"rtmp://edge-1273- de-fr.filmon.com/live/?id=035bca1a71b11fce016d28acd3dbea51cbc96ddfe5b9ed3f8fe3286df6a738d3cc97988679340a507e7113071aa75d 35ecdded9a4949e9d75f11bd6f8eb3b37ae5d5c362e41d05eb1e91dbf293480410f63f2adbb3a2fb11c24633d1954868d0ab8e524a8bb4296d78218c 69eb8f4dd1a8c7596d1f2d0fcb295f3ad0cc0f993e031c860fae51d9105e4c37c12b99b3fa6cd2b56bf7acc109","watch-timeout":86500},{"is_ free":false,"name":"27.high.stream","quality":"high","url":"rtmp://edge-1273-de-fr.filmon.com/live/?id=035bca1a71b11fce0 16d28acd3dbea51cbc96ddfe5b9ed3f8fe3286df6a738d3e46fd0aa6eb0357551234ab847df915bad61fe60c83cc2e4767786d1e2d78f22d0cb25a9f aafd92b16e14e2e74e5864208dc5fab7b01a6fb0bab35dedc912c2537f67020381d2fef21751e9dadaf6c3d67b073854beaad0e8b41e2fe98796c27e d9954a003f60a96a54623dc8aa05d08eb8d33350013bb6c","watch-timeout":45}],"server_time":1489671692,"jwplatform_media_id":"Tc NjQJcg","is_favorite":false}} C:\> @rykorb http://stream-recorder.com/forum/showpost.php?p=90361&postcount=20
2017-04-07T12:50:31
streamlink/streamlink
783
streamlink__streamlink-783
[ "782" ]
4ecde12286104f05003258b8dbab782d2f7d1ed5
diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py --- a/src/streamlink/plugins/twitch.py +++ b/src/streamlink/plugins/twitch.py @@ -247,7 +247,7 @@ def hosted_channel(self, **params): return self.call_subdomain("tmi", "/hosts", format="", **params) def clip_status(self, channel, clip_name, schema): - return http.json(self.call_subdomain("clips", "/api/v1/clips/" + channel + "/" + clip_name + "/status", format=""), schema=schema) + return http.json(self.call_subdomain("clips", "/api/v2/clips/" + clip_name + "/status", format=""), schema=schema) # Unsupported/Removed private API calls @@ -282,19 +282,36 @@ def can_handle_url(cls, url): def __init__(self, url): Plugin.__init__(self, url) - match = _url_re.match(url).groupdict() - self._channel = match.get("channel") and match.get("channel").lower() - self._channel_id = None - self.subdomain = match.get("subdomain") - self.video_type = match.get("video_type") - if match.get("videos_id"): - self.video_type = "v" - self.video_id = match.get("video_id") or match.get("videos_id") - self.clip_name = match.get("clip_name") self._hosted_chain = [] - + match = _url_re.match(url).groupdict() parsed = urlparse(url) self.params = parse_query(parsed.query) + self.subdomain = match.get("subdomain") + self.video_id = None + self.video_type = None + self._channel_id = None + self._channel = None + self.clip_name = None + + if self.subdomain == "player": + # pop-out player + if self.params.get("video"): + try: + self.video_type = self.params["video"][0] + self.video_id = self.params["video"][1:] + except IndexError: + self.logger.debug("Invalid video param: {0}", self.params["video"]) + self._channel = self.params.get("channel") + elif self.subdomain == "clips": + # clip share URL + self.clip_name = match.get("channel") + else: + self._channel = match.get("channel") and match.get("channel").lower() + self.video_type = match.get("video_type") + if match.get("videos_id"): + self.video_type = "v" + self.video_id = match.get("video_id") or match.get("videos_id") + self.clip_name = match.get("clip_name") self.api = TwitchAPI(beta=self.subdomain == "beta", version=5) self.usher = UsherService() @@ -596,7 +613,7 @@ def _get_streams(self): return self._get_video_streams() elif self.clip_name: return self._get_clips() - else: + elif self._channel: return self._get_hls_streams("live")
Twitch Videos do not work - [x] This is a bug report. ### Description Streamlink cannot parse these kind of URLs form Twitch Viedeos / past broadcasts example: http://player.twitch.tv/?video=v133805360 ### Expected / Actual behavior Opening VLC player and running the streamvideo ### Reproduction steps / Stream URLs to test streamlink http://player.twitch.tv/?video=v133805360 best ### Environment details (operating system, python version, etc.) Win7 SP1 x64, VLC 2.2.4, Streamlink 0.5.0 ### logs error: Unable to open URL: https://api.twitch.tv/kraken/users.json (400 Client Error: Bad Request for url: https://api.twitch.tv/kraken/users.json?as3=t&oauth_t oken=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&login=%3Fvideo%3Dv133805360) _token was hidden_
Was this a token generated by `livestreamer` or are you a new user? If you were using `livestreamer` before you may have an old token - try updating your token using: ``` streamlink --twitch-oauth-authenticate ``` And then follow the instructions on streamlink documentation page you are redirected to. The issue here is that the URL is being interpreted as a regular stream URL (see the login parameter: `login=%3Fvideo%3Dv133805360`). The VOD URL from above is from Twitch's "popout player" window. The regular URLs work flawlessly: https://www.twitch.tv/videos/133805360
2017-04-11T11:31:22
streamlink/streamlink
785
streamlink__streamlink-785
[ "781" ]
4ecde12286104f05003258b8dbab782d2f7d1ed5
diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -244,14 +244,17 @@ def output_stream(stream): """Open stream, create output and finally write the stream to output.""" global output + success_open = False for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) + success_open = True break except StreamError as err: - console.logger.error("{0}", err) - else: - return + console.logger.error("Try {0}/{1}: Could not open stream {2} ({3})", i+1, args.retry_open, stream, err) + + if not success_open: + console.exit("Could not open stream {0}, tried {1} times, exiting", stream, args.retry_open) output = create_output() @@ -307,14 +310,14 @@ def read_stream(stream, output, prebuffer, chunk_size=8192): elif is_http and err.errno in ACCEPTABLE_ERRNO: console.logger.info("HTTP connection closed") else: - console.logger.error("Error when writing to output: {0}", err) + console.exit("Error when writing to output: {0}, exiting", err) break except IOError as err: - console.logger.error("Error when reading from stream: {0}", err) - - stream.close() - console.logger.info("Stream ended") + console.exit("Error when reading from stream: {0}, exiting", err) + finally: + stream.close() + console.logger.info("Stream ended") def handle_stream(plugin, streams, stream_name):
[cli][error] Could not open stream doesn't exit with code 1, but with 0 ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description When streamlink finds a stream, but can not (for whatever reason) open it, the exit code is 0 (success) and not 1 (error). ### Expected / Actual behavior streamlink should exit with exit code 1 (error). ### Reproduction steps / Stream URLs to test 1. streamlink streamurl best 2. wait for it to open the stream 3. wait for error that it can not open the stream 4. wait for it to exit 5. echo $? 0 ### Environment details (operating system, python version, etc.) Linux, Python 3.6 ### Comments, logs, screenshots, etc. ```bash # streamlink hlsvariant://example/*.m3u8 best [cli][info] Found matching plugin stream for URL hlsvariant://example/*.m3u8 [cli][info] Available streams: 240p (worst), 480p (best) [cli][info] Opening stream: 480p (hls) [cli][error] Could not open stream: Unable to open URL: http://example/*.m3u8 (404 Client Error: Not Found for url: http://example/*.m3u8) ``` ```bash # echo $? 0 ```
2017-04-11T12:47:07
streamlink/streamlink
809
streamlink__streamlink-809
[ "777" ]
b09e2ac74619161f97673f5766b6298cdf43c6ef
diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -166,6 +166,7 @@ def boolean(value): A URL to attempt to extract streams from. If it's a HTTP URL then "http://" can be omitted. + The URL can also be specified using the --url option. """ ) positional.add_argument( @@ -466,6 +467,18 @@ def boolean(value): ) stream = parser.add_argument_group("Stream options") +stream.add_argument( + "--url", + dest="url_param", + metavar="URL", + help=""" + A URL to attempt to extract streams from. + + If it's a HTTP URL then "http://" can be omitted. + + This is an alternative to setting the URL using a positional argument. + """ +) stream.add_argument( "--default-stream", type=comma_list, diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -577,6 +577,9 @@ def setup_args(config_files=[]): if args.stream: args.stream = [stream.lower() for stream in args.stream] + if not args.url and args.url_param: + args.url = args.url_param + def setup_config_args(): config_files = []
Feature request: Personal "channels" - [ ] This is a bug report. - [ ] This is a plugin request. - [x] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description I've been browsing the information on the configuration pages, but I can't find a way to achieve something I want to do. I would like to have the ability to save streams I frequently watch and reload them with a simpler command, like "streamlink one" for instance. It would save users a lot of time, since longer/weirder links can't be memorized easily and have to be sought out or kept as a bookmark. On lower-spec PCs running Linux, opening a browser and waiting for a bookmark to load can require a lot of time and CPU usage. Excuse me if there's already a way of doing this, I was unable to find it.
This could be cool. While we do support https://streamlink.github.io/cli.html#cmdoption-default-stream we don't have any options like this. Let's see what other people think. Maybe there's a way to do this that I haven't used, but I'm not aware of one. I'd say that this doesn't belong into Streamlink and should be implemented in a wrapper shell script that replaces the input with a previously defined stream url. I know that this is what I usually suggest for those kind of feature requests, but it's not Streamlink's job to be a bookmark manager (or something like that). If we added a new parameter `--url` (or something) that could be used instead of the usual `URL` argument then you could just use the existing config loading syntax (`@config.cfg`). The config loader uses the same syntax as the main `streamlinkrc` file. Then you would be able to do `streamlink @bookmark.cfg` (with `--url` and `--default-stream`, plus any other options you need.) @beardypig - I based this on the idea that this would be useful in general, especially if somebody wanted to automate streamlink. Like using IFTTT to lock in on your GPS, send a command to your TV that's linked up with a raspberry pi to start up a twitch stream when you're almost home :) With this patch: ```diff diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py index 49e4eaf..14f00a8 100644 --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -467,6 +467,15 @@ output.add_argument( stream = parser.add_argument_group("Stream options") stream.add_argument( + "--url", + dest="url_param", + metavar="URL", + help=""" + Alternative parameter to specify a URL to attempt to + extract streams from. + """ +) +stream.add_argument( "--default-stream", type=comma_list, metavar="STREAM", diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py index dffbfc2..e259381 100644 --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -577,6 +577,9 @@ def setup_args(config_files=[]): if args.stream: args.stream = [stream.lower() for stream in args.stream] + if not args.url and args.url_param: + args.url = args.url_param + def setup_config_args(): config_files = [] ``` You could create a file `pokerstars.cfg`: ```cfg url=www.twitch.tv/pokerstars # almost always online default-stream=best ``` and load it using ``` streamlink @pokerstars.cfg ``` @beardypig - I'm guessing I'd have to personally place this patch into the code (running on a Windows PC as my main computer, only my travelling laptop is Linux-based), but would it be overwritten during nightly updates? The idea is elegant enough to work well. If I leave out "default-stream" for quality, I'd have to add the quality after the cfg, correct? I'm guessing there's no easy way to instruct streamlink to always check a subfolder named "channels" for cfg files and load them with a simpler command like I mentioned before. Correct in both cases, the changes would be overwritten and if you left out `default-stream` you'd have to add it to the command line. There is no easy way to have the channels directory, but you could do with a bash/bat script. I'm not super familiar with bat files, but in bash it would be simple: ```bash # streamlink-channel.sh #!/bin/bash CHANNEL_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/streamlink/channels" cfg_file="${CHANNEL_DIR}/${1}" streamlink "@$cfg_file" ``` Then it would look in `~/.config/streamlink/channels` for the config files, `streamlink-channel.sh foo` would look for `~/.config/streamlink/channels/foo`.
2017-04-18T13:08:11
streamlink/streamlink
831
streamlink__streamlink-831
[ "817" ]
8bfae3d86f3e4e51c00868b49d172cd54ddfe5b8
diff --git a/src/streamlink/stream/hds.py b/src/streamlink/stream/hds.py --- a/src/streamlink/stream/hds.py +++ b/src/streamlink/stream/hds.py @@ -224,7 +224,6 @@ def fragment_url(self, segment, fragment): def fragment_count(self): table = self.fragmentruntable.payload.fragment_run_entry_table first_fragment, end_fragment = None, None - max_end_fragment = 0 for i, fragmentrun in enumerate(table): if fragmentrun.discontinuity_indicator is not None: @@ -240,16 +239,11 @@ def fragment_count(self): fragment_duration = (fragmentrun.first_fragment_timestamp + fragmentrun.fragment_duration) - max_end_fragment = max(fragmentrun.first_fragment, max_end_fragment) - if self.timestamp > fragment_duration: offset = ((self.timestamp - fragment_duration) / fragmentrun.fragment_duration) end_fragment += int(offset) - # don't go past the last fragment - end_fragment = min(max_end_fragment, end_fragment) - if first_fragment is None: first_fragment = 1
Failed to read HDS stream http://www.rte.ie/manifests/newsnow.f4m ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Streamlink cannot read the HDS stream http://www.rte.ie/manifests/newsnow.f4m. ### Reproduction steps / Explicit stream URLs to test ``` $ streamlink "hds://http://www.rte.ie/manifests/newsnow.f4m" [cli][info] Found matching plugin stream for URL hds://http://www.rte.ie/manifests/newsnow.f4m Available streams: 256k (worst), 512k, 1024k, 2048k (best) $ streamlink "hds://http://www.rte.ie/manifests/newsnow.f4m" best [cli][info] Found matching plugin stream for URL hds://http://www.rte.ie/manifests/newsnow.f4m [cli][info] Available streams: 256k (worst), 512k, 1024k, 2048k (best) [cli][info] Opening stream: 2048k (hds) [stream.hds][error] Failed to open fragment 1-2: Unable to open URL: http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576Seg1-Frag2 (404 Client Error: Not found. for url: http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576Seg1-Frag2) [stream.hds][error] Failed to open fragment 1-2: Unable to open URL: http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576Seg1-Frag2 (404 Client Error: Not found. for url: http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576Seg1-Frag2) [stream.hds][error] Failed to open fragment 1-2: Unable to open URL: http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576Seg1-Frag2 (404 Client Error: Not found. for url: http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576Seg1-Frag2) [cli][error] Try 1/1: Could not open stream <HDSStream('http://cdn.rasset.ie/hds-live/_definst_/newsnow/', '../../streams/events/_definst_/newsnow/newsnow-576', 'http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576.bootstrap', metadata=<ScriptData name=onMetaData value=ScriptDataECMAArray([('duration', 8.014), ('width', 1024.0), ('height', 576.0), ('videocodecid', 'H264'), ('audiocodecid', 'mp4a'), ('avcprofile', 77.0), ('avclevel', 31.0), ('aacaot', 0.0), ('videoframerate', nan), ('audiosamplerate', 48000.0), ('audiochannels', 2.0), ('trackinfo', [ScriptDataObject([('length', 0.0), ('timescale', 1000.0), ('language', 'eng')]), ScriptDataObject([('length', 0.0), ('timescale', 1000.0), ('language', 'eng')]), ScriptDataObject([('length', 0.0), ('timescale', 1000.0), ('language', 'eng')])])])>, timeout=60)> (Failed to read data from stream: Read timeout) error: Could not open stream <HDSStream('http://cdn.rasset.ie/hds-live/_definst_/newsnow/', '../../streams/events/_definst_/newsnow/newsnow-576', 'http://cdn.rasset.ie/hds-live/streams/events/_definst_/newsnow/newsnow-576.bootstrap', metadata=<ScriptData name=onMetaData value=ScriptDataECMAArray([('duration', 8.014), ('width', 1024.0), ('height', 576.0), ('videocodecid', 'H264'), ('audiocodecid', 'mp4a'), ('avcprofile', 77.0), ('avclevel', 31.0), ('aacaot', 0.0), ('videoframerate', nan), ('audiosamplerate', 48000.0), ('audiochannels', 2.0), ('trackinfo', [ScriptDataObject([('length', 0.0), ('timescale', 1000.0), ('language', 'eng')]), ScriptDataObject([('length', 0.0), ('timescale', 1000.0), ('language', 'eng')]), ScriptDataObject([('length', 0.0), ('timescale', 1000.0), ('language', 'eng')])])])>, timeout=60)>, tried 1 times, exiting [cli][info] Closing currently open stream... ``` ### Environment details Operating system and version: Fedora 25 Streamlink version: https://github.com/streamlink/streamlink/commit/93b64363c33eca9a212203db070e63fd115555e0 (latest snapshot today) Python version: 3.5.3 Tested with both pycryptodome and pycrypto. ### Comments, logs, screenshots, etc. Thanks to `git bissect`, it looks like this bug happens since commit https://github.com/streamlink/streamlink/commit/fddc80310def855efbbd6b12406980b8533c6dad; for all previous commits, as welle as the 0.5.0 release, reading the stream works fine.
Should probably revert 80eeba095c5a0a27f4c371c22a292b1d2f7656b4. The issue appears to be more subtle that I first realised :) Meanwhile you can watch here : ``` streamlink "hlsvariant://http://wmsrtsp1.rte.ie/live/android.sdp/playlist.m3u8" best [cli][info] Found matching plugin stream for URL hlsvariant://http://wmsrtsp1.rt e.ie/live/android.sdp/playlist.m3u8 [cli][info] Available streams: 576p (worst, best) [cli][info] Opening stream: 576p (hls) [cli][info] Starting player: "C:\Program Files\VideoLAN\VLC\vlc.exe" [cli][info] Player closed [cli][info] Stream ended [cli][info] Closing currently open stream... streamlink "hlsvariant://http://cdn.rasset.ie/hls-live/_definst_/newsnow.m3u8" best [cli][info] Found matching plugin stream for URL hlsvariant://http://cdn.rasset. ie/hls-live/_definst_/newsnow.m3u8 [cli][info] Available streams: 300k (worst), 600k, 1200k, 2400k (best) [cli][info] Opening stream: 2400k (hls) [cli][info] Starting player: "C:\Program Files\VideoLAN\VLC\vlc.exe" [cli][info] Player closed [cli][info] Stream ended [cli][info] Closing currently open stream... ``` @karlo2105 how did you get those HLS streams? Android address I found on Internet and the second one comes from webplayer. Maybe you can get it through User Agent from android or ipad or iphone. @karlo2105 @back-to : good catch :)
2017-04-24T08:13:15
streamlink/streamlink
838
streamlink__streamlink-838
[ "825" ]
3ad3da008b189122cf37fe82fa58e7a3a1461728
diff --git a/src/streamlink/plugins/azubutv.py b/src/streamlink/plugins/azubutv.py deleted file mode 100644 --- a/src/streamlink/plugins/azubutv.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -import json -import requests - -import re - -from io import BytesIO -from time import sleep - -from streamlink.exceptions import PluginError - -from streamlink.plugin import Plugin -from streamlink.plugin.api import http, validate -from streamlink.stream import HLSStream - - -HTTP_HEADERS = { - "User-Agent": ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " - "(KHTML, like Gecko) Chrome/36.0.1944.9 Safari/537.36"), - 'Accept': 'application/json;pk=BCpkADawqM1gvI0oGWg8dxQHlgT8HkdE2LnAlWAZkOlznO39bSZX726u4JqnDsK3MDXcO01JxXK2tZtJbgQChxgaFzEVdHRjaDoxaOu8hHOO8NYhwdxw9BzvgkvLUlpbDNUuDoc4E4wxDToV' - -} - -_url_re = re.compile(r"http(s)?://(\w+\.)?azubu.tv/(?P<domain>\w+)") - -PARAMS_REGEX = r"(\w+)=({.+?}|\[.+?\]|\(.+?\)|'(?:[^'\\]|\\')*'|\"(?:[^\"\\]|\\\")*\"|\S+)" -stream_video_url = "http://api.azubu.tv/public/channel/{}/player" - - -class AzubuTV(Plugin): - @classmethod - def can_handle_url(cls, url): - return _url_re.match(url) - - @classmethod - def stream_weight(cls, stream): - if stream == "source": - weight = 1080 - else: - weight, group = Plugin.stream_weight(stream) - - return weight, "azubutv" - - def _parse_params(self, params): - rval = {} - matches = re.findall(PARAMS_REGEX, params) - - for key, value in matches: - try: - value = ast.literal_eval(value) - except Exception: - pass - - rval[key] = value - - return rval - - def _get_stream_url(self, o): - - match = _url_re.match(self.url) - channel = match.group('domain') - - channel_info = requests.get(stream_video_url.format(channel)) - j = json.loads(channel_info.text) - - if j["data"]["is_live"] is not True: - return "", False - else: - is_live = True - - stream_url = 'https://edge.api.brightcove.com/playback/v1/accounts/3361910549001/videos/ref:{0}' - - r = requests.get(stream_url.format(j["data"]["stream_video"]["reference_id"]), headers=HTTP_HEADERS) - t = json.loads(r.text) - - stream_url = t["sources"][0]["src"] - return stream_url, is_live - - def _get_streams(self): - hls_url, is_live = self._get_stream_url(self) - - if not is_live: - return - - split = self.url.split(" ") - params = (" ").join(split[1:]) - params = self._parse_params(params) - - try: - streams = HLSStream.parse_variant_playlist(self.session, hls_url, **params) - except IOError as err: - raise PluginError(err) - - return streams - - -__plugin__ = AzubuTV
azubu.tv: remove plugin http://www.azubu.tv/ `Soon a new future for Azubu and Hitbox, together as a single force in the world of eSports and competitive gaming, will be revealed. We will be launching a new brand, website, and mobile apps. There you will find the best offerings from both Azubu and Hitbox in one new place.`
Thanks for reporting this!
2017-04-25T13:54:39
streamlink/streamlink
853
streamlink__streamlink-853
[ "845" ]
517d3613c192538fec43394d935ee6893fbe0ee5
diff --git a/src/streamlink/plugins/facebook.py b/src/streamlink/plugins/facebook.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/facebook.py @@ -0,0 +1,24 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.stream import HLSStream + +_playlist_url = "https://www.facebook.com/video/playback/playlist.m3u8?v={0}" + +_url_re = re.compile(r"http(s)?://(www\.)?facebook\.com/[^/]+/videos/(?P<video_id>\d+)") + + +class Facebook(Plugin): + @classmethod + def can_handle_url(cls, url): + return _url_re.match(url) + + def _get_streams(self): + match = _url_re.match(self.url) + video = match.group("video_id") + + playlist = _playlist_url.format(video) + + return HLSStream.parse_variant_playlist(self.session, playlist) + +__plugin__ = Facebook
diff --git a/tests/test_plugin_facebook.py b/tests/test_plugin_facebook.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_facebook.py @@ -0,0 +1,14 @@ +import unittest + +from streamlink.plugins.facebook import Facebook + + +class TestPluginFacebook(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Facebook.can_handle_url("https://www.facebook.com/nos/videos/1725546430794241/")) + self.assertTrue(Facebook.can_handle_url("https://www.facebook.com/nytfood/videos/1485091228202006/")) + self.assertTrue(Facebook.can_handle_url("https://www.facebook.com/SporTurkTR/videos/798553173631138/")) + + # shouldn't match + self.assertFalse(Facebook.can_handle_url("https://www.facebook.com"))
Add already-created facebook plugin ### Checklist - [ ] This is a bug report. - [x] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Add an already-created plugin for facebook videos (non-Dash, 360p quality). A link can be found in #226, the original creator left if there and allowed anybody to work on it and use it. Since we have no way of viewing facebook videos, I think this would be a very good addition for the upcoming 0.6 version.
2017-04-26T19:55:52
streamlink/streamlink
868
streamlink__streamlink-868
[ "818" ]
d741a8c2f3f2374f7b0ea12a727d858fc90385c8
diff --git a/src/streamlink/plugins/tvnbg.py b/src/streamlink/plugins/tvnbg.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/tvnbg.py @@ -0,0 +1,38 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.compat import urljoin +from streamlink.stream import HLSStream + + +class TVNBG(Plugin): + url_re = re.compile(r"https?://(?:live\.)?tvn\.bg/(?:live)?") + iframe_re = re.compile(r'<iframe.*?src="([^"]+)".*?></iframe>') + src_re = re.compile(r'<source.*?src="([^"]+)".*?/>') + + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _get_streams(self): + base_url = self.url + res = http.get(self.url) + + # Search for the iframe in the page + iframe_m = self.iframe_re.search(res.text) + if iframe_m: + # If the iframe is found, load the embedded page + base_url = iframe_m.group(1) + res = http.get(iframe_m.group(1)) + + # Search the page (original or embedded) for the stream URL + src_m = self.src_re.search(res.text) + if src_m: + stream_url = urljoin(base_url, src_m.group(1)) + # There is no variant playlist, only a plain HLS Stream + yield "live", HLSStream(self.session, stream_url) + + +__plugin__ = TVNBG
Plugin request TVN.bg ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description A simple plugin to open the stream available at http://tvn.bg/live/
2017-05-02T09:56:54
streamlink/streamlink
909
streamlink__streamlink-909
[ "904" ]
9ad8bb2f20ea86aaefae89483af8a4f1015e561a
diff --git a/src/streamlink/plugins/hitbox.py b/src/streamlink/plugins/hitbox.py --- a/src/streamlink/plugins/hitbox.py +++ b/src/streamlink/plugins/hitbox.py @@ -8,16 +8,16 @@ from streamlink.stream import HLSStream, HTTPStream, RTMPStream from streamlink.utils import absolute_url -HLS_PLAYLIST_BASE = "http://www.hitbox.tv{0}" -LIVE_API = "http://www.hitbox.tv/api/media/live/{0}?showHidden=true" -PLAYER_API = "http://www.hitbox.tv/api/player/config/{0}/{1}?embed=false&showHidden=true" +HLS_PLAYLIST_BASE = "http://www.smashcast.tv{0}" +LIVE_API = "http://www.smashcast.tv/api/media/live/{0}?showHidden=true" +PLAYER_API = "http://www.smashcast.tv/api/player/config/{0}/{1}?embed=false&showHidden=true" SWF_BASE = "http://edge.vie.hitbox.tv/static/player/flowplayer/" SWF_URL = SWF_BASE + "flowplayer.commercial-3.2.16.swf" -VOD_BASE_URL = "http://www.hitbox.tv/" +VOD_BASE_URL = "http://www.smashcast.tv/" _quality_re = re.compile(r"(\d+p)$") _url_re = re.compile(r""" - http(s)?://(www\.)?hitbox.tv + http(s)?://(www\.)?(hitbox|smashcast).tv /(?P<channel>[^/]+) (?: /(?P<media_id>[^/]+) @@ -76,7 +76,7 @@ class Hitbox(Plugin): @classmethod - def can_handle_url(self, url): + def can_handle_url(cls, url): return _url_re.match(url) def _get_quality(self, label):
Plugin request for NEW SmashCast TV (merger of Azubu and Hitbox) This week finally came the result of the merger between Azubu and Hitbox. The new [Smashcast TV.](https://www.smashcast.tv/) Now, we need a plugin for this new platform. :) Thanks to all the Streamlink developers.
the old hitbox plugin still works, you just need change the current smashcast.tv link to hitbox.tv link, for example: from "https://www.smashcast.tv/aravingloon" to "https://www.hitbox.tv/aravingloon" It's true, I had not tried it, it really works. So I think it's easy to create a new plugin, basically swap the url from hitbox to smashcast in the plugin. I'll try to change that. DONE! 👍 [smashcast.zip](https://github.com/streamlink/streamlink/files/988560/smashcast.zip)
2017-05-11T08:52:52
streamlink/streamlink
925
streamlink__streamlink-925
[ "922" ]
13958e3a15856755c7582a37f6f91393f63e1aec
diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py --- a/src/streamlink/plugins/bbciplayer.py +++ b/src/streamlink/plugins/bbciplayer.py @@ -20,7 +20,7 @@ class BBCiPlayer(Plugin): live/(?P<channel_name>\w+) ) """, re.VERBOSE) - vpid_re = re.compile(r'"vpid"\s*:\s*"(\w+)"') + vpid_re = re.compile(r'"ident_id"\s*:\s*"(\w+)"') tvip_re = re.compile(r'event_master_brand=(\w+?)&') swf_url = "http://emp.bbci.co.uk/emp/SMPf/1.18.3/StandardMediaPlayerChromelessFlash.swf" hash = base64.b64decode(b"N2RmZjc2NzFkMGM2OTdmZWRiMWQ5MDVkOWExMjE3MTk5MzhiOTJiZg==")
BBC iPlayer plugin cannot find VPID ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description The BBC IPlayer plugin cannot find the VPID for valid urls. ### Reproduction steps / Explicit stream URLs to test The following command: `streamlink -l debug 'http://www.bbc.co.uk/iplayer/episode/b013pnv4/horizon-20112012-2-seeing-stars' best` produces this output: ``` [cli][info] Found matching plugin bbciplayer for URL http://www.bbc.co.uk/iplayer/episode/b013pnv4/horizon-20112012-2-seeing-stars [plugin.bbciplayer][debug] Loading streams for episode: b013pnv4 [plugin.bbciplayer][debug] Looking for vpid on http://www.bbc.co.uk/iplayer/episode/b013pnv4/horizon-20112012-2-seeing-stars [plugin.bbciplayer][error] Could not find VPID for episode b013pnv4 error: No playable streams found on this URL: http://www.bbc.co.uk/iplayer/episode/b013pnv4/horizon-20112012-2-seeing-stars ``` and the same goes for any other valid iplayer url. ### Environment details Operating system: arch linux Streamlink and Python versions: streamlink-0.6.0 and python-3.6.1 ### Comments, logs, screenshots, etc. AFAICS, the page downloaded from the iplayer url does not contain the string "vpid".
I'll take a look :-)
2017-05-16T08:04:05
streamlink/streamlink
928
streamlink__streamlink-928
[ "919" ]
13958e3a15856755c7582a37f6f91393f63e1aec
diff --git a/src/streamlink_cli/utils/http_server.py b/src/streamlink_cli/utils/http_server.py --- a/src/streamlink_cli/utils/http_server.py +++ b/src/streamlink_cli/utils/http_server.py @@ -114,6 +114,6 @@ def close(self, client_only=False): if not client_only: try: self.socket.shutdown(2) - except OSError: + except (OSError, socket.error): pass self.socket.close()
Socket is not connected error when closing currently open stream with VLC ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Every time I close a stream that was playing in VLC, I get the following error: ``` [cli][info] Closing currently open stream... Traceback (most recent call last): File "/usr/local/bin/streamlink", line 11, in <module> load_entry_point('streamlink==0.6.0', 'console_scripts', 'streamlink')() File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 1027, in main handle_url() File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 502, in handle_url handle_stream(plugin, streams, stream_name) File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 380, in handle_stream return output_stream_http(plugin, streams) File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 192, in output_stream_http server.close() File "/usr/local/lib/python2.7/site-packages/streamlink_cli/utils/http_server.py", line 116, in close self.socket.shutdown(2) File "/usr/local/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 57] Socket is not connected ``` This has been happening to me since 0.4.0, but I haven't had a chance to report it earlier. I've only been watching streams on Twtich so I have no idea if other services are affected by this too. Issue #604 might be something similar, but the error is quite different although some parts of the backtrace are similar. ### Expected / Actual behavior Expected: No error when closing the stream. Actual: The above error happens. ### Reproduction steps / Explicit stream URLs to test 1. Load a Twitch stream with VLC as the player. 2. Close VLC. This happens regardless of if the stream was still running when VLC is closed or if the stream already ended and VLC is not playing anything. ### Environment details Operating system and version: FreeBSD 11.0-RELEASE-p8 Streamlink and Python version: Streamlink 0.6.0, Python 2.7.13 VLC version: 2.2.5.1 My .streamlinkrc file contains the following (excluding my Twitch OAuth token): ``` player-continuous-http default-stream=best hls-segment-threads=10 ```
Hmm very strange, I wonder if this is a Python 2.7 issue. I'm running the Windows release on a Windows 10 machine with VLC 2.2.5.1, same settings and no errors when I close VLC directly, but that uses a more recent Python version. Can you try to spin a python 3X virtualenv locally, install Streamlink there, and then see if you encounter the same problem with these settings? Thanks for the detailed report by the way. Yeah, it might take me a bit to do that though. I'll try to get it done ASAP. I tested streamlink with python 3.6, and when I close an active Twitch stream, I do not get the backtrace like I do when using python 2.7. @CyberBotX Awesome thanks for confirming, I'll mark this as a bug. Confirmed. Affects Python 2.7 only; Python 3.3, 3.4, 3.5, 3.6, and 3.7-dev all behave as expected.
2017-05-16T14:51:52
streamlink/streamlink
967
streamlink__streamlink-967
[ "751" ]
125ac06e41f5835cb09cbd09bc7c1f6bdac9c2eb
diff --git a/docs/ext_argparse.py b/docs/ext_argparse.py --- a/docs/ext_argparse.py +++ b/docs/ext_argparse.py @@ -28,7 +28,7 @@ _block_re = re.compile(r":\n{2}\s{2}") _default_re = re.compile(r"Default is (.+)\.\n") -_note_re = re.compile(r"Note: (.*)\n\n", re.DOTALL) +_note_re = re.compile(r"Note: (.*)(?:\n\n|\n*$)", re.DOTALL) _option_re = re.compile(r"(?m)^((?!\s{2}).*)(--[\w-]+)") diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -163,8 +163,10 @@ def boolean(value): help=""" A URL to attempt to extract streams from. - If it's a HTTP URL then "http://" can be omitted. - The URL can also be specified using the --url option. + Usually, the protocol of http(s) URLs can be omitted ("https://"), + depending on the implementation of the plugin being used. + + Alternatively, the URL can also be specified by using the --url option. """ ) positional.add_argument( @@ -175,13 +177,13 @@ def boolean(value): help=""" Stream to play. - Use "best" or "worst" for highest or lowest quality available. + Use "best" or "worst" for selecting the highest or lowest available quality. Fallback streams can be specified by using a comma-separated list: "720p,480p,best" - If no stream is specified and --default-stream is not used then a + If no stream is specified and --default-stream is not used, then a list of available streams will be printed. """ ) @@ -224,7 +226,8 @@ def boolean(value): "--can-handle-url-no-redirect", metavar="URL", help=""" - Same as --can-handle-url but without following redirects when looking up the URL. + Same as --can-handle-url but without following redirects + when looking up the URL. """ ) general.add_argument( @@ -275,7 +278,7 @@ def boolean(value): help=""" Enable or disable the automatic check for a new version of Streamlink. - Default is no + Default is "no". """ ) general.add_argument( @@ -294,7 +297,7 @@ def boolean(value): subtitle and audio language. The locale is formatted as [language_code]_[country_code], - eg. eg. en_US or es_ES + eg. en_US or es_ES. Default is system locale. """ @@ -330,7 +333,7 @@ def boolean(value): streamlink --player "vlc --file-caching=5000" <url> <quality> As an alternative to this, see the --player-args parameter, - which does not log the customer player arguments. + which does not log any custom player arguments. """ ) player.add_argument( @@ -340,7 +343,8 @@ def boolean(value): help=""" This option allows you to customize the default arguments which are put together with the value of --player to create a command - to execute. + to execute. Unlike the --player parameter, custom player + arguments will not be logged. This value can contain formatting variables surrounded by curly braces, {{ and }}. If you need to include a brace character, it @@ -357,6 +361,11 @@ def boolean(value): need to add arguments after the filename. Default is "{0}". + + Example: + + streamlink -p vlc -a "--play-and-exit {{filename}}" <url> <quality> + """.format(DEFAULT_PLAYER_ARGUMENTS) ) player.add_argument( @@ -393,7 +402,6 @@ def boolean(value): This makes it possible to handle stream disconnects if your player is capable of reconnecting to a HTTP stream. This is usually done by setting your player to a "repeat mode". - """ ) player.add_argument( @@ -485,9 +493,11 @@ def boolean(value): help=""" A URL to attempt to extract streams from. - If it's a HTTP URL then "http://" can be omitted. + Usually, the protocol of http(s) URLs can be omitted (https://), + depending on the implementation of the plugin being used. - This is an alternative to setting the URL using a positional argument. + This is an alternative to setting the URL using a positional argument + and can be useful if set in a config file. """ ) stream.add_argument( @@ -495,7 +505,16 @@ def boolean(value): type=comma_list, metavar="STREAM", help=""" - Open this stream when no stream argument is specified, e.g. "best". + Stream to play. + + Use "best" or "worst" for selecting the highest or lowest available quality. + + Fallback streams can be specified by using a comma-separated list: + + "720p,480p,best" + + This is an alternative to setting the stream using a positional argument + and can be useful if set in a config file. """ ) stream.add_argument( @@ -528,7 +547,8 @@ def boolean(value): The order will be used to separate streams when there are multiple streams with the same name but different stream types. Any stream type not listed will be omitted from the available streams list. A ``*`` - can be used as a wildcard to match any other type of stream, eg. muxed-stream. + can be used as a wildcard to match any other type of stream, + eg. muxed-stream. Default is "rtmp,hls,hds,http,akamaihd,*". """ @@ -683,9 +703,11 @@ def boolean(value): type=str, metavar="CODE", help=""" - Selects a specific audio source, by language code, when multiple audio sources are available. + Selects a specific audio source by language code + when multiple audio sources are available. - Note: This is only useful in special circumstances where the regular locale option fails. + Note: This is only useful in special circumstances + where the regular locale option fails. """) transport.add_argument( "--http-stream-timeout", @@ -801,6 +823,7 @@ def boolean(value): This is generic option used by streams not covered by other options, such as stream protocols specific to plugins, e.g. UStream. + Default is 60.0. """) transport.add_argument( @@ -814,7 +837,7 @@ def boolean(value): "--subprocess-cmdline", "--cmdline", "-c", action="store_true", help=""" - Print command-line used internally to play stream. + Print the command-line used internally to play the stream. This is only available on RTMP streams. """ @@ -844,7 +867,7 @@ def boolean(value): "--ffmpeg-ffmpeg", metavar="FILENAME", help=""" - FFMPEG is used to access mux separate video and audio streams. + FFMPEG is used to access or mux separate video and audio streams. You can specify the location of the ffmpeg executable if it is not in your PATH. @@ -855,7 +878,7 @@ def boolean(value): "--ffmpeg-verbose", action="store_true", help=""" - Write the console output from ffmpeg to the console + Write the console output from ffmpeg to the console. """ ) transport.add_argument( @@ -863,14 +886,16 @@ def boolean(value): type=str, metavar="PATH", help=""" - Path to write the output from the ffmpeg console + Path to write the output from the ffmpeg console. """ ) transport.add_argument( "--ffmpeg-video-transcode", metavar="CODEC", help=""" - When muxing streams transcode the video to this CODEC, defaults to copy (no transcode) + When muxing streams transcode the video to this CODEC. + + Default is "copy". Example: "h264" """ @@ -879,7 +904,9 @@ def boolean(value): "--ffmpeg-audio-transcode", metavar="CODEC", help=""" - When muxing streams transcode the audio to this CODEC, defaults to copy (no transcode) + When muxing streams transcode the audio to this CODEC. + + Default is "copy". Example: "aac" """ @@ -892,7 +919,7 @@ def boolean(value): help=""" A HTTP proxy to use for all HTTP requests. - Example: http://hostname:port/ + Example: "http://hostname:port/" """ ) http.add_argument( @@ -901,7 +928,7 @@ def boolean(value): help=""" A HTTPS capable proxy to use for all HTTPS requests. - Example: http://hostname:port/ + Example: "https://hostname:port/" """ ) http.add_argument( @@ -1003,8 +1030,7 @@ def boolean(value): help=""" Attempts to load plugins from these directories. - Multiple directories can be used by separating them with a - semi-colon. + Multiple directories can be used by separating them with a semicolon. """ ) plugin.add_argument( @@ -1037,7 +1063,6 @@ def boolean(value): Note: This method is the old and clunky way of authenticating with Twitch, using --twitch-oauth-authenticate is the recommended and simpler way of doing it now. - """ ) plugin.add_argument( @@ -1086,7 +1111,7 @@ def boolean(value): metavar="SESSION_ID", help=""" Set a specific session ID for crunchyroll, can be used to bypass - region restrictions + region restrictions. """ ) plugin.add_argument( @@ -1107,7 +1132,8 @@ def boolean(value): "--schoolism-email", metavar="EMAIL", help=""" - The email associated with your Schoolism account, required to access any Schoolism stream. + The email associated with your Schoolism account, + required to access any Schoolism stream. """ ) plugin.add_argument( @@ -1123,23 +1149,23 @@ def boolean(value): default=1, metavar="PART", help=""" - Play part number PART of the lesson + Play part number PART of the lesson. - Defaults is 1 + Defaults is 1. """ ) plugin.add_argument( "--daisuki-mux-subtitles", action="store_true", help=""" - Automatically mux available subtitles in to the output stream + Automatically mux available subtitles in to the output stream. """ ) plugin.add_argument( "--rtve-mux-subtitles", action="store_true", help=""" - Automatically mux available subtitles in to the output stream + Automatically mux available subtitles in to the output stream. """ ) plugin.add_argument( @@ -1148,16 +1174,16 @@ def boolean(value): choices=["en", "ja", "english", "japanese"], default="english", help=""" - The audio language to use for Funimation streams; japanese or english + The audio language to use for Funimation streams; japanese or english. - Default is english + Default is "english". """ ) plugin.add_argument( "--funimation-mux-subtitles", action="store_true", help=""" - Enable automatically including available subtitles in to the output stream + Enable automatically including available subtitles in to the output stream. """ ) plugin.add_argument( @@ -1178,14 +1204,15 @@ def boolean(value): "--pluzz-mux-subtitles", action="store_true", help=""" - Automatically mux available subtitles in to the output stream + Automatically mux available subtitles in to the output stream. """ ) plugin.add_argument( "--wwenetwork-email", metavar="EMAIL", help=""" - The email associated with your WWE Network account, required to access any WWE Network stream. + The email associated with your WWE Network account, + required to access any WWE Network stream. """ ) plugin.add_argument( @@ -1213,7 +1240,7 @@ def boolean(value): "--npo-subtitles", action="store_true", help=""" - Include subtitles for the deaf or hard of hearing, if available + Include subtitles for the deaf or hard of hearing, if available. """ ) plugin.add_argument(
Default Stream quality to best? (documentation improvement) ### Checklist - [ ] This is a bug report. - [ ] This is a plugin request. - [x] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description I personally use streamlink for all my stream needs (mostly twitch), so I type a lot of streamlink commands into the terminal so any less typing would be appreciated. This would only require a minimal change (see [my fork](https://github.com/streamlink/streamlink/compare/master...Germandrummer92:master)) and would as far as I can see it not break anything, as even if someone just wanted to print the available qualities they are still printed and you can just exit the source stream immediately as you will most likely type into the same terminal window again. If someone actually wants the behavior of just printing the stream qualities I could implement a separate option for that although I'm not sure anyone actually uses that. ### Expected / Actual behavior `streamlink twitch.tv/pgl_dota` defaults to `streamlink twitch.tv/pgl_dota best` instead of just printing the stream qualities Let me know if this makes sense and I would open a pull request with my one-line change!
You can already specify a default quality. See [--default-stream](https://streamlink.github.io/cli.html#cmdoption-default-stream). Just add it to your config file and you wont have to enter a quality every time. As @skulblakka this is something users can set via their config file. We don't want to default to `best` without a user specifying it as `best` typically requires a large amount of bandwidth which may negatively impact the end user if they have any sort of limitation or cap in place. I'm going to close this out for now since it's easy to work around via existing settings. Edit: Do you feel we could communicate this better via the documentation? If so can you detail what you looked at prior to creating this issue to see if we can improve the path users follow to find out about these options? I went through the docs related to --default-stream and I think we could definitely improve them. They're super bare bones right now and not very useful. It doesn't really explain how to set ti and use it. > so I type a lot of streamlink commands into the terminal so any less typing would be appreciated. I guess the --default-stream option is the solution already, but if you want to shorten the command even more, use aliases/functions (bash? you said terminal). ``` function sl() { streamlink "$1" best } ``` I use many functions like that for diferent purposes and many different sites. I'd go insane by typing them all the time or even just copy-pasting from a text file. Your function is not ideal and only takes one argument. This is a better one: ```bash function sl() { streamlink --default-stream best "$@" } ``` Actually, if you put the default-stream into the streamlinkrc you don't have to retype the argument for every function you define (if you're like me and have different ones for example and are even too lazy to type the argument in your zshrc/bashrc :smile: ). Also, for completeness sake here is the function I use. It also autocompletes my stream names to twitch if it doesnt include a "/" (e.g. any other url will just be passed through). ```bash wt() { url="$1" if [[ "$url" =~ ".*twitch.*" || "$url" =~ ".*/.*" ]]; then streamlink "$url" "${@:2}" else streamlink "twitch.tv/$url" "${@:2}" fi } ``` This means, that `wt twitch.tv/ppd` and `wt ppd` will work. Thanks for all the help though :+1:
2017-05-30T13:04:51
streamlink/streamlink
974
streamlink__streamlink-974
[ "959" ]
c7462bd01f7f447e0e17b8d4993c4d9019367913
diff --git a/src/streamlink/plugins/dailymotion.py b/src/streamlink/plugins/dailymotion.py --- a/src/streamlink/plugins/dailymotion.py +++ b/src/streamlink/plugins/dailymotion.py @@ -128,7 +128,12 @@ def _get_live_streams(self, params, swf_url): continue if quality == "hds": - streams = HDSStream.parse_manifest(self.session, res.url) + self.logger.debug('PLAYLIST URL: {0}'.format(res.url)) + try: + streams = HDSStream.parse_manifest(self.session, res.url) + except: + streams = HLSStream.parse_variant_playlist(self.session, res.url) + for name, stream in streams.items(): if key == "source": name += "+"
Unable to play Dailymotion live stream ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Streamlink cannot read the live stream http://www.dailymotion.com/video/x3b68jn ### Reproduction steps / Explicit stream URLs to test ``` $ streamlink -l debug http://www.dailymotion.com/video/x3b68jn [cli][info] Found matching plugin dailymotion for URL http://www.dailymotion.com/video/x3b68jn [plugin.dailymotion][debug] Found media ID: x3b68jn error: Unable to parse manifest XML: syntax error: line 1, column 0 ('#EXTM3U\n#EXT-X-STREAM-INF:BANDWID ...) ``` ### Environment details Operating system and version: Fedora 25 Streamlink version: https://github.com/streamlink/streamlink/commit/0c31ca9115bb62550fb3af7b626ef5496b6cf81b (latest snapshot today) Python version: 3.5.3 ### Comments, logs, screenshots, etc. This is the only live stream on DM I've found with this issue. All the others I tested are OK.
Same is here but I try other video: http://www.dailymotion.com/video/x2qg8t0 and working OK **streamlink-0.6.0.exe** streamlink.exe "http://www.dailymotion.com/video/x3b68jn" [cli][info] Found matching plugin dailymotion for URL http://www.dailymotion.com/video/x3b68jn error: Unable to parse manifest XML: syntax error: line 1, column 0 ('#EXTM3U\n#EXT-X-STREAM-INF:BANDWID ...) **youtube-dl 2017.05.29** youtube-dl.exe -v -F --no-check-certificate http://www.dailymotion.com/video/x3b68jn [debug] System config: [] [debug] User config: [] [debug] Custom config: [] [debug] Command-line args: ['-v', '-F', '--no-check-certificate', 'http://www.dailymotion.com/video/x3b68jn'] [debug] Encodings: locale cp1252, fs mbcs, out cp850, pref cp1252 [debug] youtube-dl version 2017.05.29 [debug] Python version 3.4.4 - Windows-7-6.1.7601-SP1 [debug] exe versions: ffmpeg n3.2.1, ffprobe 3.3.1, rtmpdump 2.4 [debug] Proxy map: {} [dailymotion] x3b68jn: Downloading webpage [dailymotion] x3b68jn: Downloading m3u8 information [info] Available formats for x3b68jn: format code extension resolution note hls-514-0 mp4 327x184 514k , avc1.66.30@ 420k, mp4a.40.5@ 64k hls-514-1 mp4 327x184 514k , avc1.66.30@ 420k, mp4a.40.5@ 64k hls-915-0 mp4 512x288 915k , avc1.66.30@ 735k, mp4a.40.2@128k hls-915-1 mp4 512x288 915k , avc1.66.30@ 735k, mp4a.40.2@128k hls-1472-0 mp4 853x480 1472k , avc1.66.30@1260k, mp4a.40.2@128k hls-1472-1 mp4 853x480 1472k , avc1.66.30@1260k, mp4a.40.2@128k hls-2362 mp4 1280x720 2362k , avc1.66.31@2100k, mp4a.40.2@128k hls-2919 mp4 1280x720 2919k , avc1.66.32@2625k, mp4a.40.2@128k hls-6814 mp4 1920x1080 6814k , avc1.66.40@6300k, mp4a.40.2@128k hls-8484 mp4 1920x1080 8484k , avc1.66.42@7875k, mp4a.40.2@128k (best)
2017-06-01T18:06:41
streamlink/streamlink
989
streamlink__streamlink-989
[ "988" ]
695cc35d684a7d42719fb0446fa462a36884e673
diff --git a/src/streamlink/plugins/tvplayer.py b/src/streamlink/plugins/tvplayer.py --- a/src/streamlink/plugins/tvplayer.py +++ b/src/streamlink/plugins/tvplayer.py @@ -62,7 +62,7 @@ def _get_stream_data(self, resource, token, service=1): # Get the context info (validation token and platform) self.logger.debug("Getting stream information for resource={0}".format(resource)) context_res = http.get(self.context_url, params={"resource": resource, - "nonce": token}) + "gen": token}) context_data = http.json(context_res, schema=self.context_schema) # get the stream urls
tvplayer.com 404 Client Error ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description tvplayer.com has started returning 404 client error: streamlink https://tvplayer.com/watch/chilled [cli][info] Found matching plugin tvplayer for URL https://tvplayer.com/watch/chilled error: Unable to open URL: http://tvplayer.com/watch/context (404 Client Error: Not Found) ### Expected / Actual behavior Available video qualities are detected and if one has been selected the video begins to play. ### Reproduction steps / Explicit stream URLs to test streamlink https://tvplayer.com/watch/chilled ### Environment details streamlink 0.6.0-47-g695cc35 Python 2.7.9
2017-06-05T10:38:59
streamlink/streamlink
992
streamlink__streamlink-992
[ "991" ]
89ceeba2398726ee0e073c8399146d55de11da75
diff --git a/src/streamlink/plugins/looch.py b/src/streamlink/plugins/looch.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/looch.py @@ -0,0 +1,75 @@ +import re + +import itertools + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream +from streamlink.stream import HTTPStream +from streamlink.utils import parse_json + + +class Looch(Plugin): + url_re = re.compile(r"https?://(?:www\.)?looch\.tv/channel/(?P<name>[^/]+)(/videos/(?P<video_id>\d+))?") + + api_base = "https://api.looch.tv" + channel_api = api_base + "/channels/{name}" + video_api = api_base + "/videos/{id}" + + playback_schema = validate.Schema({"weight": int, "uri": validate.url()}) + data_schema = validate.Schema({ + "type": validate.text, + "attributes": { + validate.optional("playback"): [playback_schema], + validate.optional("resolution"): {"width": int, "height": int} + }}) + channel_schema = validate.Schema( + validate.transform(parse_json), + {"included": validate.all( + [data_schema], + validate.filter(lambda x: x["type"] == "active_streams"), + validate.map(lambda x: x["attributes"].get("playback")), + validate.transform(lambda x: list(itertools.chain(*x))) + ), + }, validate.get("included")) + video_schema = validate.Schema( + validate.transform(parse_json), + {"data": data_schema}, + validate.get("data"), + validate.get("attributes")) + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _get_live_stream(self, channel): + url = self.channel_api.format(name=channel) + self.logger.debug("Channel API call: {0}", url) + data = http.get(url, schema=self.channel_schema) + self.logger.debug("Got {0} channel playback items", len(data)) + for playback in data: + for s in HLSStream.parse_variant_playlist(self.session, playback["uri"]).items(): + yield s + + def _get_video_stream(self, video_id): + url = self.video_api.format(id=video_id) + self.logger.debug("Video API call: {0}", url) + data = http.get(url, schema=self.video_schema) + self.logger.debug("Got video {0} playback items", len(data["playback"])) + res = data["resolution"]["height"] + for playback in data["playback"]: + yield "{0}p".format(res), HTTPStream(self.session, playback["uri"]) + + + def _get_streams(self): + match = self.url_re.match(self.url) + self.logger.debug("Matched URL: name={name}, video_id={video_id}", **match.groupdict()) + + if match.group("video_id"): + return self._get_video_stream(match.group("video_id")) + elif match.group("name"): + return self._get_live_stream(match.group("name")) + + +__plugin__ = Looch
Add support for looch.tv - [x] This is a feature request. - [x] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description Any chance of getting a plugin for this? https://looch.tv/channels
Do you have any additional details? An example channel, what requests look like, etc.? Anything would be appreciated. Example: https://looch.tv/channel/KofyeinTV
2017-06-08T07:56:52
streamlink/streamlink
1,027
streamlink__streamlink-1027
[ "1026" ]
d6ba7a7d68ae76b7144641f5f6fcbf7adaaf4091
diff --git a/src/streamlink/plugins/ine.py b/src/streamlink/plugins/ine.py --- a/src/streamlink/plugins/ine.py +++ b/src/streamlink/plugins/ine.py @@ -15,7 +15,7 @@ class INE(Plugin): (.*?)""", re.VERBOSE) play_url = "https://streaming.ine.com/play/{vid}/watch" js_re = re.compile(r'''script type="text/javascript" src="(https://content.jwplatform.com/players/.*?)"''') - jwplayer_re = re.compile(r'''jwplayer\(".*?"\).setup\((\{.*\})\);''', re.DOTALL) + jwplayer_re = re.compile(r'''jwConfig\s*=\s*(\{.*\});''', re.DOTALL) setup_schema = validate.Schema( validate.transform(jwplayer_re.search), validate.any(
ine.py for source in data["playlist"][0]["sources"]: TypeError: 'NoneType' object is not subscriptable Hi, INE plugin is failing since recently: ``` $ streamlink -o ./streamlink.mp4 https://streaming.ine.com/play/1cfbc029-dd6d-4646-80b9-7316e3ac121a/introduction 720p --http-cookie laravel_session=removed [cli][info] Found matching plugin ine for URL https://streaming.ine.com/play/1cfbc029-dd6d-4646-80b9-7316e3ac121a/introduction Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/Current/bin/streamlink", line 11, in <module> load_entry_point('streamlink==0.6.0', 'console_scripts', 'streamlink')() File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink_cli/main.py", line 1027, in main handle_url() File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink_cli/main.py", line 482, in handle_url streams = fetch_streams(plugin) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink_cli/main.py", line 394, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink/plugin/plugin.py", line 328, in get_streams return self.streams(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink/plugin/plugin.py", line 236, in streams ostreams = self._get_streams() File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink/plugins/ine.py", line 50, in _get_streams for source in data["playlist"][0]["sources"]: TypeError: 'NoneType' object is not subscriptable $ $ python --version Python 3.5.3 $ streamlink --version streamlink 0.6.0 $ streamlink --version-check [cli][info] Your Streamlink version (0.6) is up to date! $ ``` Same error on mac OS and Windows. This particular URL was 'downloadable' with no problem about a month ago or so.
Same URL with '--loglevel debug' just in case: ``` $ streamlink -o ./streamlink.mp4 https://streaming.ine.com/play/1cfbc029-dd6d-4646-80b9-7316e3ac121a/introduction 720p --loglevel debug --http-cookie laravel_session=removed [cli][info] Found matching plugin ine for URL https://streaming.ine.com/play/1cfbc029-dd6d-4646-80b9-7316e3ac121a/introduction [plugin.ine][debug] Found video ID: 1cfbc029-dd6d-4646-80b9-7316e3ac121a [plugin.ine][debug] Loading player JS: https://content.jwplatform.com/players/aLBZ9PbQ-p4NBeNN0.js?exp=1499343063&amp;sig=9fba6b330907964e9898a2e4759e5c05 Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/Current/bin/streamlink", line 11, in <module> load_entry_point('streamlink==0.6.0', 'console_scripts', 'streamlink')() File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink_cli/main.py", line 1027, in main handle_url() File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink_cli/main.py", line 482, in handle_url streams = fetch_streams(plugin) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink_cli/main.py", line 394, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink/plugin/plugin.py", line 328, in get_streams return self.streams(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink/plugin/plugin.py", line 236, in streams ostreams = self._get_streams() File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/streamlink/plugins/ine.py", line 50, in _get_streams for source in data["playlist"][0]["sources"]: TypeError: 'NoneType' object is not subscriptable $ ``` Thanks the detailed report with the debug log. Looks like jwplayer changed their embedded player js source a bit. I'm preparing a PR to fix it now :)
2017-06-22T13:50:02
streamlink/streamlink
1,030
streamlink__streamlink-1030
[ "1029" ]
3df657d3cedc943adaf3d7b823e62335fc7344a7
diff --git a/src/streamlink/plugins/ufctv.py b/src/streamlink/plugins/ufctv.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/ufctv.py @@ -0,0 +1,91 @@ +from __future__ import print_function + +import re +import string +from functools import partial + +from streamlink.plugin import Plugin, PluginOptions +from streamlink.plugin.api import http +from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream +from streamlink.utils import parse_json + + +def js_to_json(data): + js_re = re.compile(r'(?!<")(\w+):(?!/)') + trimmed = [y.replace("\r", "").strip() for y in data.split(",")] + jsons = ','.join([js_re.sub(r'"\1":', x, count=1) for x in trimmed]) + return parse_json(jsons) + + +class UFCTV(Plugin): + url_re = re.compile(r"https?://(?:www\.)?ufc\.tv/(channel|video)/.+") + video_info_re = re.compile(r"""program\s*=\s*(\{.*?});""", re.DOTALL) + channel_info_re = re.compile(r"""g_channel\s*=\s(\{.*?});""", re.DOTALL) + + stream_api_url = "https://www.ufc.tv/service/publishpoint" + auth_url = "https://www.ufc.tv/secure/authenticate" + auth_schema = validate.Schema(validate.xml_findtext("code")) + + options = PluginOptions({ + "username": None, + "password": None + }) + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _get_stream_url(self, video_id, vtype="video"): + res = http.post(self.stream_api_url, data={ + "id": video_id, + "type": vtype, + "format": "json" + }, headers={ + "User-Agent": useragents.IPHONE_6 + }) + data = http.json(res) + return data.get("path") + + def _get_info(self, url): + res = http.get(url) + # try to find video info first + m = self.video_info_re.search(res.text) + if not m: + # and channel info if that fails + m = self.channel_info_re.search(res.text) + return m and js_to_json(m.group(1)) + + def _login(self, username, password): + res = http.post(self.auth_url, data={ + "username": username, + "password": password, + "cookielink": False + }) + login_status = http.xml(res, schema=self.auth_schema) + self.logger.debug("Login status for {0}: {1}", username, login_status) + if login_status == "loginlocked": + self.logger.error("The account {0} has been locked, the password needs to be reset") + return login_status == "loginsuccess" + + def _get_streams(self): + if self.get_option("username") and self.get_option("password"): + self.logger.debug("Attempting login as {0}", self.get_option("username")) + if self._login(self.get_option("username"), self.get_option("password")): + self.logger.info("Successfully logged in as {0}", self.get_option("username")) + else: + self.logger.info("Failed to login as {0}", self.get_option("username")) + + video = self._get_info(self.url) + if video: + self.logger.debug("Found {type}: {name}", **video) + surl = self._get_stream_url(video['id'], video.get('type', "video")) + if surl: + return HLSStream.parse_variant_playlist(self.session, surl) + else: + self.logger.error("Could not get stream URL for video: {name} ({id})", **video) + else: + self.logger.error("Could not find any video info on the page") + +__plugin__ = UFCTV diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -1271,6 +1271,20 @@ def boolean(value): A bbc.co.uk account password to use with --bbciplayer-username. """ ) +plugin.add_argument( + "--ufctv-username", + metavar="USERNAME", + help=""" + The username used to register with ufc.tv. + """ +) +plugin.add_argument( + "--ufctv-password", + metavar="PASSWORD", + help=""" + A ufc.tv account password to use with --ufctv-username. + """ +) # Deprecated options stream.add_argument( diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -930,6 +930,17 @@ def setup_plugin_options(): if bbciplayer_password: streamlink.set_plugin_option("bbciplayer", "password", bbciplayer_password) + if args.ufctv_username: + streamlink.set_plugin_option("ufctv", "username", args.ufctv_username) + + if args.ufctv_username and not args.ufctv_password: + ufctv_password = console.askpass("Enter ufc.tv account password: ") + else: + ufctv_password = args.ufctv_password + + if ufctv_password: + streamlink.set_plugin_option("ufctv", "password", ufctv_password) + # Deprecated options if args.jtv_legacy_names: console.logger.warning("The option --jtv/twitch-legacy-names is "
Plugin Request for UFC Fightpass ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. Not sure if this is possible but would be cool to have a plugin for ufc fightpass. Happy to contribute to developing the plugin but python isn't my primary language so would need some help. ### Description I would like to be able to stream ufc fight pass. This is a "paid" service but they do have some free videos. Some that require a login and some that don't. It appears that there are existing "paid" services implemented already (crunchyroll) Here is an example video that requires no login. https://www.ufc.tv/video/fight-night-oklahoma-city-michael-chiesa-vs-kevin-lee-preview Here is an example of video that requires a paid account (30 day free trial available) https://www.ufc.tv/video/ufc-fortaleza-2017 ### Details There's a similar project that exists for Kodi. I was actually looking at this to attempt to build a similar project before I found this repo. https://github.com/portse/plugin.video.ufcfightpass/blob/master/default.py If you parse out the xbmc parts of the code you can very easily get stream urls. I was having issues pairing them with cookies in browser though. ufc.tv is using neulion and swfobject player to handle all the auth management. The code passed down from the server isn't minified but it's a nightmare to comprehend. ### Source URL From the above code I was able to parse out this source url. ``` http://nlds277.cdnak.neulion.com/nlds_vod/ufc/vod/2017/06/17/28527/2_28527_cam1_cam0_2017_cam0_whole_1_ced.mp4.m3u8?hdnea=expires%3D1497944837%7Eaccess%3D%2Fnlds_vod%2Fufc%2Fvod%2F2017%2F06%2F17%2F28527%2F*%7Emd5%3D80b467247583fc329c2ba2767f552276&nltid=ufc&nltdt=8&nltnt=1&uid=2906116|User-Agent=Mozilla/5.0%20(Linux;%20Android%206.0.1;%20D6603%20Build/23.5.A.0.570;%20wv)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Version/4.0%20Chrome/56.0.2924.87%20Mobile%20Safari/537.36%20android%20mobile%20ufc%207.0310 ``` The userAgent doesn't seem to be completely necessary as the `.m0_whole_1_ced.mp4.m3u8` downloads regardless. Contents to that file points to a bunch of smaller `mp4.m3u8` files. ### Stream file contents ``` Contents are this. #EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=800000 2_28527_cam1_cam0_2017_cam0_whole_1_800_ced.mp4.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=3000000 2_28527_cam1_cam0_2017_cam0_whole_1_3000_ced.mp4.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2400000 2_28527_cam1_cam0_2017_cam0_whole_1_2400_ced.mp4.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1600000 2_28527_cam1_cam0_2017_cam0_whole_1_1600_ced.mp4.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1200000 2_28527_cam1_cam0_2017_cam0_whole_1_1200_ced.mp4.m3u8 ``` Appending one of thse files names to the above url produces a larger m3u8 file filled with smaller `.ts` files. I'm assuming those .ts files are encrypted as they don't play in any player. ``` http://nlds277.cdnak.neulion.com/nlds_vod/ufc/vod/2017/06/17/28527/2_28527_cam1_cam0_2017_cam0_whole_1_1200_ced.mp4.m3u8?hdnea=expires%3D1497944837%7Eaccess%3D%2Fnlds_vod%2Fufc%2Fvod%2F2017%2F06%2F17%2F28527%2F*%7Emd5%3D80b467247583fc329c2ba2767f552276&nltid=ufc&nltdt=8&nltnt=1&uid=2906116 ``` Notice the bitrate before ced in the above uri. Alternatively, you can replace ced with android but doesn't seem to change much. Without cookies and pairing with the aes key it doesn't do any good. Using Charles while playing on ufc.tv I was able to detect the stream.xml file which had these contents. ### More Stream Details ``` <?xml version="1.0" encoding="utf-8" ?> <channel version="3.5" currentTime="1488136644000" currentTimeDescription="2017-02-26 19:17:24" defaultStreamIndex="1"> <streamDatas> <streamData url="/nlds/skysportsfanpass/skysports1/as/live/skysports1_hd_400" isLive="true" blockDuration="2000" bitrate="409600" liveStartupTime="1458138474000" liveDVRDuration="86400000" livePlayerDelay="25000" liveBlockDelay="16000"> <encryption method="aes-128" keyUrl="/nlds/skysportsfanpass/skysports1/as/live/skysports1_hd_400" keyDuration="3600000" keySecure="false" keyTransfer="secure" token="NLAuth=40a77e36af54091f6442ea8b6e8530b3-0-32;serverKey_internal_ASV3=1b6f3532e8ee36cbcd1e1ba2d3536e32-d47043cd5ef615c8105f12567731d186-1488149269-32" /> <video width="400" height="224" fps="25.000000" ccChannels="CC1,CC2,CC3,CC4" codec="avc1" /> <audio channelCount="2" samplesRate="44100" sampleBitSize="16" bitrate="65536" /> <httpservers> <httpserver name="nlds635.cdnaknl.oc.neulion.com" port="80" /> </httpservers> <ranges> <range begin="2017-02-25 19:17:22" /> </ranges> </streamData> .... </streamDatas> <ccStreamDatas> <streamData url="CC1" language="CC1" displayName="CC1" /> <streamData url="CC2" language="CC2" displayName="CC2" /> <streamData url="CC3" language="CC3" displayName="CC3" /> <streamData url="CC4" language="CC4" displayName="CC4" /> </ccStreamDatas> </channel> ``` > `...` - Truncated, view full file [here](http://stream-recorder.com/forum/neul10n-livestreamer-capture-livestreamer-t22707.html?s=fec248f50809e33f379c3cb46b2ed2c7&amp;p=89946&mode=threaded) **Notice** > `<encryption method="aes-128" keyUrl="/nlds/skysportsfanpass/skysports1/as/live/skysports1_hd_4500" keyDuration="3600000" keySecure="false" keyTransfer="secure" token="NLAuth=40a77e36af54091f6442ea8b6e8530b3-0-32;serverKey_internal_ASV3=1b6f3532e8ee36cbcd1e1ba2d3536e32-d47043cd5ef615c8105f12567731d186-1488149269-32" />` Neulion is used for hockey and NBA streams so there's some knowledge sprinkled through various forums related to the service. Though it's hard to tell what is old/new and some of it seems to be under wraps as they are attempting to bypass auth (not my intention). ### Grab-bag of links that I have collected. - [Python code to fetch stream url and cookie](https://github.com/portse/plugin.video.ufcfightpass/blob/master/default.py) - [Kodi forum post detailing above python code](https://forum.kodi.tv/showthread.php?tid=213642&page=6) - [Example of stream.xml with keys](http://stream-recorder.com/forum/neul10n-livestreamer-capture-livestreamer-t22707.html?s=fec248f50809e33f379c3cb46b2ed2c7&amp;p=89946&mode=threaded) - [details on parsing neulion streams, possibly old, unrelated ]( https://www.reddit.com/r/NHLStreams/comments/2jz9kv/how_to_record_a_vlc_stream/)
Thanks for the detailed issue @SeanDunford! We'll see if someone is interested in picking this one up. We've had some issues with encryption in the past so I'm not sure how that will impact this one. @gravyboat - Cool! Yeah, the encryption seems to be the tricky part. Does that count as DRM? I actually spent a few hours today trying to capture the contents sent to chromecast but it doesn't do anything different than the swfobject. There's also an "isIos" flag that seems to make the video display differently but I haven't dug into it, yet.
2017-06-23T11:39:38
streamlink/streamlink
1,039
streamlink__streamlink-1039
[ "804" ]
13abffa6f327c43fd67b1741a6d6a6027bccdcc1
diff --git a/src/streamlink/plugins/zattoo.py b/src/streamlink/plugins/zattoo.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/zattoo.py @@ -0,0 +1,238 @@ +import re +import time +import uuid + +from streamlink.cache import Cache +from streamlink.plugin import Plugin +from streamlink.plugin import PluginOptions +from streamlink.plugin.api import http +from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream + + +class Zattoo(Plugin): + API_HELLO = '{0}/zapi/session/hello' + API_LOGIN = '{0}/zapi/v2/account/login' + API_CHANNELS = '{0}/zapi/v2/cached/channels/{1}?details=False' + API_WATCH = '{0}/zapi/watch' + API_WATCH_VOD = '{0}/zapi/avod/videos/{1}/watch' + + _url_re = re.compile(r''' + https?:// + (?P<base_url> + zattoo\.com + | + tvonline\.ewe\.de + | + nettv\.netcologne\.de + )/(?:watch/(?P<channel>[^/\s]+) + | + ondemand/watch/(?P<vod_id>[^-]+)-) + ''', re.VERBOSE) + + _app_token_re = re.compile(r"""window\.appToken\s+=\s+'([^']+)'""") + + _channels_schema = validate.Schema({ + 'success': int, + 'channel_groups': [{ + 'channels': [ + { + 'display_alias': validate.text, + 'cid': validate.text + }, + ] + }]}, + validate.get('channel_groups'), + ) + + options = PluginOptions({ + 'email': None, + 'password': None, + 'purge_credentials': None + }) + + def __init__(self, url): + super(Zattoo, self).__init__(url) + self._session_attributes = Cache(filename='plugin-cache.json', key_prefix='zattoo:attributes') + self._authed = self._session_attributes.get('beaker.session.id') and self._session_attributes.get('pzuid') and self._session_attributes.get('power_guide_hash') + self._uuid = self._session_attributes.get('uuid') + self._expires = self._session_attributes.get('expires') + + self.base_url = 'https://{0}'.format(Zattoo._url_re.match(url).group('base_url')) + self.headers = { + 'User-Agent': useragents.CHROME, + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + 'X-Requested-With': 'XMLHttpRequest', + 'Referer': self.base_url + } + + @classmethod + def can_handle_url(cls, url): + return Zattoo._url_re.match(url) + + def _hello(self): + self.logger.debug('_hello ...') + res = http.get(self.base_url) + match = self._app_token_re.search(res.text) + + app_token = match.group(1) + hello_url = self.API_HELLO.format(self.base_url) + + if self._uuid: + __uuid = self._uuid + else: + __uuid = str(uuid.uuid4()) + self._session_attributes.set('uuid', __uuid, expires=3600 * 24) + + params = { + 'client_app_token': app_token, + 'uuid': __uuid, + 'lang': 'en', + 'format': 'json' + } + res = http.post(hello_url, headers=self.headers, data=params) + return res + + def _login(self, email, password, _hello): + self.logger.debug('_login ... Attempting login as {0}'.format(email)) + + login_url = self.API_LOGIN.format(self.base_url) + + params = { + 'login': email, + 'password': password, + 'remember': 'true' + } + + res = http.post(login_url, headers=self.headers, data=params, cookies=_hello.cookies) + data = http.json(res) + + self._authed = data['success'] + if self._authed: + self.logger.debug('New Session Data') + self._session_attributes.set('beaker.session.id', res.cookies.get('beaker.session.id'), expires=3600 * 24) + self._session_attributes.set('pzuid', res.cookies.get('pzuid'), expires=3600 * 24) + self._session_attributes.set('power_guide_hash', data['session']['power_guide_hash'], expires=3600 * 24) + return self._authed + else: + return None + + def _watch(self): + self.logger.debug('_watch ...') + match = self._url_re.match(self.url) + if not match: + return + channel = match.group('channel') + vod_id = match.group('vod_id') + + cookies = { + 'beaker.session.id': self._session_attributes.get('beaker.session.id'), + 'pzuid': self._session_attributes.get('pzuid') + } + + watch_url = [] + if channel: + params, watch_url = self._watch_live(channel, cookies) + elif vod_id: + params, watch_url = self._watch_vod(vod_id) + + if not watch_url: + return + + res = [] + try: + res = http.post(watch_url, headers=self.headers, data=params, cookies=cookies) + except Exception as e: + if '404 Client Error' in str(e): + self.logger.error('Unfortunately streaming is not permitted in this country or this channel does not exist.') + elif '402 Client Error: Payment Required' in str(e): + self.logger.error('Paid subscription required for this channel.') + self.logger.info('If paid subscription exist, use --zattoo-purge-credentials to start a new session.') + else: + self.logger.error(str(e)) + return + + data = http.json(res) + + if data['success']: + for hls_url in data['stream']['watch_urls']: + for s in HLSStream.parse_variant_playlist(self.session, hls_url['url']).items(): + yield s + + def _watch_live(self, channel, cookies): + self.logger.debug('_watch_live ... Channel: {0}'.format(channel)) + watch_url = self.API_WATCH.format(self.base_url) + + channels_url = self.API_CHANNELS.format(self.base_url, self._session_attributes.get('power_guide_hash')) + res = http.get(channels_url, headers=self.headers, cookies=cookies) + data = http.json(res, schema=self._channels_schema) + + c_list = [] + for d in data: + for c in d['channels']: + c_list.append(c) + + cid = [] + zattoo_list = [] + for c in c_list: + zattoo_list.append(c['display_alias']) + if c['display_alias'] == channel: + cid = c['cid'] + + self.logger.debug('Available zattoo channels in this country: {0}'.format(', '.join(sorted(zattoo_list)))) + + if not cid: + cid = channel + + self.logger.debug('CHANNEL ID: {0}'.format(cid)) + + params = { + 'cid': cid, + 'https_watch_urls': True, + 'stream_type': 'hls' + } + return params, watch_url + + def _watch_vod(self, vod_id): + self.logger.debug('_watch_vod ...') + watch_url = self.API_WATCH_VOD.format(self.base_url, vod_id) + params = { + 'https_watch_urls': True, + 'stream_type': 'hls' + } + return params, watch_url + + def _get_streams(self): + email = self.get_option('email') + password = self.get_option('password') + + if self.options.get('purge_credentials'): + self._session_attributes.set('beaker.session.id', None, expires=0) + self._session_attributes.set('expires', None, expires=0) + self._session_attributes.set('power_guide_hash', None, expires=0) + self._session_attributes.set('pzuid', None, expires=0) + self._session_attributes.set('uuid', None, expires=0) + self._authed = False + self.logger.info('All credentials were successfully removed.') + + if not self._authed and (not email and not password): + self.logger.error('A login for Zattoo is required, use --zattoo-email EMAIL --zattoo-password PASSWORD to set them') + return + + if self._authed: + if self._expires < time.time(): + # login after 24h + expires = time.time() + 3600 * 24 + self._session_attributes.set('expires', expires, expires=3600 * 24) + self._authed = False + + if not self._authed: + __hello = self._hello() + if not self._login(email, password, __hello): + self.logger.error('Failed to login, check your username/password') + return + + return self._watch() + +__plugin__ = Zattoo diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -1285,6 +1285,28 @@ def boolean(value): A ufc.tv account password to use with --ufctv-username. """ ) +plugin.add_argument( + "--zattoo-email", + metavar="EMAIL", + help=""" + The email associated with your zattoo account, required to access any zattoo stream. + """ +) +plugin.add_argument( + "--zattoo-password", + metavar="PASSWORD", + help=""" + A zattoo account password to use with --zattoo-email. + """ +) +plugin.add_argument( + "--zattoo-purge-credentials", + action="store_true", + help=""" + Purge cached zattoo credentials to initiate a new session + and reauthenticate. + """ +) # Deprecated options stream.add_argument( diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -941,6 +941,19 @@ def setup_plugin_options(): if ufctv_password: streamlink.set_plugin_option("ufctv", "password", ufctv_password) + if args.zattoo_email: + streamlink.set_plugin_option("zattoo", "email", args.zattoo_email) + if args.zattoo_email and not args.zattoo_password: + zattoo_password = console.askpass("Enter zattoo password: ") + else: + zattoo_password = args.zattoo_password + if zattoo_password: + streamlink.set_plugin_option("zattoo", "password", zattoo_password) + + if args.zattoo_purge_credentials: + streamlink.set_plugin_option("zattoo", "purge_credentials", + args.zattoo_purge_credentials) + # Deprecated options if args.jtv_legacy_names: console.logger.warning("The option --jtv/twitch-legacy-names is "
diff --git a/tests/test_plugin_zattoo.py b/tests/test_plugin_zattoo.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_zattoo.py @@ -0,0 +1,24 @@ +import unittest + +from streamlink.plugins.zattoo import Zattoo + + +class TestPluginZattoo(unittest.TestCase): + def test_can_handle_url(self): + # ewe live + self.assertTrue(Zattoo.can_handle_url('http://tvonline.ewe.de/watch/daserste')) + self.assertTrue(Zattoo.can_handle_url('http://tvonline.ewe.de/watch/zdf')) + # netcologne live + self.assertTrue(Zattoo.can_handle_url('https://nettv.netcologne.de/watch/daserste')) + self.assertTrue(Zattoo.can_handle_url('https://nettv.netcologne.de/watch/zdf')) + # zattoo live + self.assertTrue(Zattoo.can_handle_url('https://zattoo.com/watch/daserste')) + self.assertTrue(Zattoo.can_handle_url('https://zattoo.com/watch/zdf')) + # zattoo vod + self.assertTrue(Zattoo.can_handle_url('https://zattoo.com/ondemand/watch/ibR2fpisWFZGvmPBRaKnFnuT-alarm-am-airport')) + self.assertTrue(Zattoo.can_handle_url('https://zattoo.com/ondemand/watch/G8S7JxcewY2jEwAgMzvFWK8c-berliner-schnauzen')) + + # shouldn't match + self.assertFalse(Zattoo.can_handle_url('https://ewe.de')) + self.assertFalse(Zattoo.can_handle_url('https://netcologne.de')) + self.assertFalse(Zattoo.can_handle_url('https://zattoo.com'))
Plugin for zattoo.com ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Could You please add a plugin for https://zattoo.com, a livestreaming platform on which many TV stations are streamed. There are about 70 channels on the free version and about 90 channels in the premium version. Sorry for grammatic mistakes if done and thanks a lot. ...
Here's the URL for getting a session-ID: https://sandbox.zattoo.com/zapi/session/token?app_tid=driess&format=json Last time I checked the streams were only available as dash streams, this might have changed though. Dash is not yet supported, but will be soon :-) Thank you for your quick answer. Can I also use the plugin in streamlink or can i otherwise stream the content from zattoo.com directly into a file? I would like to save some tv shows or films as video files, so i can watch them again later. Thank you for your help.
2017-06-26T20:04:09
streamlink/streamlink
1,082
streamlink__streamlink-1082
[ "1078" ]
3a6547c1763a58690dd790b26810147bb68a2023
diff --git a/src/streamlink/plugins/hitbox.py b/src/streamlink/plugins/hitbox.py --- a/src/streamlink/plugins/hitbox.py +++ b/src/streamlink/plugins/hitbox.py @@ -178,7 +178,7 @@ def _get_streams(self): if not media_id: res = http.get(LIVE_API.format(channel)) livestream = http.json(res, schema=_live_schema) - if livestream["media_hosted_media"]: + if livestream.get("media_hosted_media"): hosted = _live_schema.validate(livestream["media_hosted_media"]) self.logger.info("{0} is hosting {1}", livestream["media_user_name"], hosted["media_user_name"]) livestream = hosted
Unable to open Smashcast streams I get the following error whenever I try to open a Smashcast stream ``` streamlink smashcast.tv/greatvaluesmash best [cli][info] Found matching plugin hitbox for URL smashcast.tv/greatvaluesmash Traceback (most recent call last): File "C:\Program Files (x86)\Streamlink\bin\streamlink-script.py", line 15, in <module> main() File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 103 8, in main handle_url() File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 482 , in handle_url streams = fetch_streams(plugin) File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 394 , in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugin\plugin.py", lin e 345, in get_streams return self.streams(*args, **kwargs) File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugin\plugin.py", lin e 248, in streams ostreams = self._get_streams() File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugins\hitbox.py", li ne 181, in _get_streams if livestream["media_hosted_media"]: KeyError: 'media_hosted_media' ``` Tried with multiple different streams and using a hitbox url instead of smashcast and it still occurs. It still works perfectly fine on Livestreamer, so I'm not really sure what's up. Asked a friend to test it out to see if it's not just me and he had the same error. Using the latest version (0.7.0) on Windows 7, and my friend was using Windows 8.1.
2017-07-10T10:12:56
streamlink/streamlink
1,092
streamlink__streamlink-1092
[ "778" ]
3e2cb6dd5b0e8b5de7a44446745c74560960f5dc
diff --git a/docs/conf.py b/docs/conf.py --- a/docs/conf.py +++ b/docs/conf.py @@ -58,7 +58,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ['_build', '_applications.rst'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None
Where does one go to share a GUI/frontend? ### Checklist - [ ] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description I looked around but I couldn't find any place where they can be submitted. Can someone help me out?
There's currently no official list of third party tools like GUIs/frontends, etc. AFAIK, the Livestreamer repository had its wiki with a dedicated page for this that could be edited by everyone. I personally would welcome a menu on the website for this though, so that there can be a bit of quality assurance without fear of vandalism. Yes, I know, the wiki is just a git repo and changes can be undone, but this stuff gets usually noticed late. Do you want to submit your own project or is it from somebody else? Could you please provide some infos? Well it's just a lightweight bash script I've been adding to and expanding on for the last couple of years. I've added support for sites streamlink and livestreamer don't support, along with a history of saved links, the ability to open chats for a couple of sites, and a few other features I've added for use for my family and myself around the home. I honestly don't know how it compares to other frontends, and I usually don't share my projects with the public, but I guess I've been feeling brave enough (or dumb enough) to open myself up to criticism for some reason. @techmouse, we're always interested in adding extra plugins ... maybe we can port some over in to `streamlink` :) Haha well try not to get too excited. Like I said it's all done in bash so I doubt it would be useful to anything other than Linux systems and maybe Macs. I'm leaving my 2 cents in here (instead of just silently subscribing) since I'd be interested in this as well. Anything that could lead to more exposure for Streamlink is a good thing, the work you guys are doing __does matter__ to a lot of people. And seeing what others are doing and being a part of that would make me feel like giving something back. Also a good thing :wink:. Well I don't know where to put this so I guess I'll just leave it here. Below is the link to the script and the description. If this is a problem, let me know. https://www.dropbox.com/s/048p1u5wheo1r9d/livestreamlinkgui-public ![livestreamlinkgui screenshot](https://cloud.githubusercontent.com/assets/4404140/25201795/0687381a-2521-11e7-803b-cba27b6792fa.png) This is LiveStreamLinkGUI. It's a lightweight GUI for Livestreamer, Streamlink, and any future forks. I made it for the personal use of my family and myself, but when I looked around, I saw people making requests for things I've already implemented. So I decided to share it. Its only requirements are BASH, rtmpdump, and zenity. I wrote it in Linux, for Linux, but because it's a BASH script, it should (in theory) work for any platform that supports BASH and its requirements. I hear Win10 has some kind of BASH support but I have no idea how capable it is of running this or any other script. Features: Open Chats. Some websites have popout chats, such as twitch and vaughnlive. When you give LiveStreamLinkGUI a link for one of these sites, it can ask if you want to open the chat for that stream in your browser. It's important to know only the chat will be opened. So you don't have to worry about your browser eating up a lot of your system resources just to take part in the chat. I designed LiveStreamLinkGUI in a way where adding support for other sites shouldn't be difficult at all. All you need to know is the popout chat's URL and how to parse it. Save Links. LiveStreamLinkGUI can also save links. This makes it easy to keep track of your favorite streams and even open them without running your browser. Loop Forever. If the stream is lost or closed for whatever reason, you have the option to "loop forever". While doing so, LiveStreamLinkGUI will keep trying to reopen the stream until the script is manually killed. This is best used in a media setup, so you can keep watching your streams while you fall asleep, work, clean the house, or whatever. It works very well with the shutdown command. An example of the shutdown command (which can differ from distro to distro) is sudo shutdown -hP {minutes}, which will shutdown the system after the specified number of minutes. So it's similar to sleepmode for TVs. I've added support for sites like arconaitv.me, funhaus.roosterteeth.com, and a few other sites. LiveStreamLinkGUI is designed so that adding support for other sites shouldn't be much of a chore. Configurations: All of the user specific configurations are at the top of the script. I would recommend going through them before running the script, but there is also a first time setup GUI which will help take you through the more basic configurations. How to use: If you want to open a new stream, all you have to do is execute the script and select "Open A New Link". A text input box will appear and you can drag and drop the link to that text box and click "OK". You can also copy-paste the link or manually type it in, if you so choose. When the player closes, you're presented with a list of options. You can reopen it (if the stream is online), save the link for future use, loop it forever, open a new stream, open a saved stream, etc, etc. To save you a click, selecting "Close Program", is the same as clicking "Cancel", pressing ESC, or closing the window in any other way. So you don't have to scroll to the bottom every time you're done with the script. For ease of use, I have a launcher for LiveStreamLinkGUI in my DE's panel. For media machines, I also keep a launcher for timed shutdowns. It makes it very easy to watch streams while falling asleep using only a pointer device. I'm not telling you what to do, I'm just telling you what I do. As a side note, there's a VLC script that allows VLC to play Youtube playlists. Naturally, LiveStreamLinkGUI gets along very well with this. Feel free to make whatever changes you want with this. If you make a change, such as adding chat support for other sites, or site support for any sites livestreamer/streamlink don't support, please let me know so I can add the changes too. If you redistribute this script, I would like to ask that you please give me credit as "Mouse". Thank you and enjoy! @techmouse You've put a lot of effort in your comment above, may I ask why you didn't just setup a Git repository of your own, put everything there and link that back here? That would be the best way not only to preserve your work but to enable/encourage future additions as you already mentioned. @dehesselle Well at the risk of sounding foolish, I appear to be very github illiterate. While looking through different projects, I've had a heck of a time just trying to find the pages other people were talking about. I eventually went to google and did a search for "keywords site:github.com". I don't think I'm getting old, but just trying to view the content on here sure makes me feel that way. So needless to say, learning how to set up a github project seems like a chore unto itself. I wouldn't even know where to begin for this one situation alone. @techmouse Not foolish - everybody has to start somewhere. I created a repository and requested a transfer to you. Now the only thing you have to do is accept the transfer. @dehesselle Thank you very much! Clicking the link that was emailed to me took me to github's tutorial on how to use github. Ask and you shall receive. If only I had known about it sooner. i Like this, maybe could implement url's from this simple shell script giving user choices. https://github.com/streamlink/streamlink/issues/872 a database of all/popular streams added to the frontend would be nice for the non DOS/bash types ;) the filmon/vaughnlive url's are static, not too sure about others. @cirrusUK All filmon links I checked were region locked so I couldn't verify much. But it appears streamlink supports it so LiveStreamLinkGUI would have no problem with it either. And of course you can save the links for future use. I checked all over LondonLive and I couldn't find where you got that m3u8 link from. I don't know if it's because LondonLive is region locked too or if I'm on the wrong site all together but I would need more information to support it. Concerning the Twit link, is that the same Twit as Twit.tv? As in Leo Laporte's Twit? If so, they have a Twitch account: twitch.tv/twit, which means livestreamer/streamlink support it. I also added support for Twit.tv, including non-twitch.tv videos. As for the rest of the links, I added a new experimental way to automatically search pages for supported video types. So any page that has a m3u8/mp4/webm/etc link will automatically be parsed and piped into the video player. This should make it much easier to watch unsupported sites and even add support for them yourself. So if something doesn't work with Livestreamer, Streamlink, or other forks, give this a shot. https://github.com/techmouse/livestreamlinkgui If anyone is interested @karlo2105 and I have been working on this list of live TV channels: https://beardypig.github.io/tv-stream-db/ @techmouse Yeah sorry, some of the links might well be dead, i wrote that script a while back , yes it is twit.tv. @beardypig Thanks for the list.
2017-07-13T02:47:13
streamlink/streamlink
1,117
streamlink__streamlink-1117
[ "1034" ]
e6db4113c204d20239f619e0bc5769d2416c989e
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -44,6 +44,8 @@ deps.append("iso-639") deps.append("iso3166") +deps.append("websocket-client") + # When we build an egg for the Win32 bootstrap we don't want dependency # information built into it. if environ.get("NO_DEPS"): diff --git a/src/streamlink/plugins/vaughnlive.py b/src/streamlink/plugins/vaughnlive.py --- a/src/streamlink/plugins/vaughnlive.py +++ b/src/streamlink/plugins/vaughnlive.py @@ -1,122 +1,106 @@ import random import re +import itertools +import ssl +import websocket from streamlink.plugin import Plugin -from streamlink.plugin.api import http, validate +from streamlink.plugin.api import useragents, http from streamlink.stream import RTMPStream -from streamlink.utils import swfdecompress - -INFO_URL = "http://{site}{path}{domain}_{channel}?{version}_{ms}-{ms}-{random}" - -DOMAIN_MAP = { - "breakers": "btv", - "vapers": "vtv", - "vaughnlive": "live", -} _url_re = re.compile(r""" http(s)?://(\w+\.)? - (?P<domain>vaughnlive|breakers|instagib|vapers).tv + (?P<domain>vaughnlive|breakers|instagib|vapers|pearltime).tv (/embed/video)? /(?P<channel>[^/&?]+) """, re.VERBOSE) -_swf_player_re = re.compile(r'swfobject.embedSWF\("(/\d+/swf/[0-9A-Za-z]+\.swf)"') - -_schema = validate.Schema( - validate.any( - validate.all(u"<error></error>", validate.transform(lambda x: None)), - validate.all( - validate.transform(lambda s: s.split(";")), - validate.length(3), - validate.union({ - "server": validate.all( - validate.get(0), - validate.text - ), - "token": validate.all( - validate.get(1), - validate.text, - validate.startswith(":mvnkey-"), - validate.transform(lambda s: s[len(":mvnkey-"):]) - ), - "ingest": validate.all( - validate.get(2), - validate.text - ) - }) - ) - ) -) + +class VLWebSocket(websocket.WebSocket): + def __init__(self, **_): + self.session = _.pop("session") + self.logger = self.session.logger.new_module("plugins.vaughnlive.websocket") + sslopt = _.pop("sslopt", {}) + sslopt["cert_reqs"] = ssl.CERT_NONE + super(VLWebSocket, self).__init__(sslopt=sslopt, **_) + + def send(self, payload, opcode=websocket.ABNF.OPCODE_TEXT): + self.logger.debug("Sending message: {0}", payload) + return super(VLWebSocket, self).send(payload + "\n\x00", opcode) + + def recv(self): + d = super(VLWebSocket, self).recv().replace("\n", "").replace("\x00", "") + return d.split(" ", 1) class VaughnLive(Plugin): + api_re = re.compile(r'new sApi\("(#(vl|igb|btv|pt|vtv)-[^"]+)",') + servers = ["wss://sapi-ws-{0}x{1:02}.vaughnlive.tv".format(x, y) for x, y in itertools.product(range(1, 3), + range(1, 6))] + origin = "https://vaughnlive.tv" + rtmp_server_map = { + "594140c69edad": "198.255.17.18", + "585c4cab1bef1": "198.255.17.26", + "5940d648b3929": "198.255.17.34", + "5941854b39bc4": "198.255.17.66"} + name_remap = {"#vl": "live", "#btv": "btv", "#pt": "pt", "#igb": "instagib", "#vtv": "vtv"} + @classmethod def can_handle_url(cls, url): return _url_re.match(url) - def _get_streams(self): - res = http.get(self.url) - match = _swf_player_re.search(res.text) - if match is None: - return - swf_url = "http://vaughnlive.tv" + match.group(1) - self.logger.debug("Using swf url: {0}", swf_url) - - swfres = http.get(swf_url) - swfdata = swfdecompress(swfres.content).decode("latin1") - - player_version_m = re.search(r"0\.\d+\.\d+\.\d+", swfdata) - info_url_domain_m = re.search(r"\w+\.vaughnsoft\.net", swfdata) - info_url_path_m = re.search(r"/video/edge/[a-zA-Z0-9_]+-", swfdata) - - player_version = player_version_m and player_version_m.group(0) - info_url_domain = info_url_domain_m and info_url_domain_m.group(0) - info_url_path = info_url_path_m and info_url_path_m.group(0) - - if player_version and info_url_domain and info_url_path: - self.logger.debug("Found player_version={0}, info_url_domain={1}, info_url_path={2}", - player_version, info_url_domain, info_url_path) - match = _url_re.match(self.url) - params = {"channel": match.group("channel").lower(), - "domain": DOMAIN_MAP.get(match.group("domain"), match.group("domain")), - "version": player_version, - "ms": random.randint(0, 999), - "random": random.random(), - "site": info_url_domain, - "path": info_url_path} - info_url = INFO_URL.format(**params) - self.logger.debug("Loading info url: {0}", INFO_URL.format(**params)) - - info = http.get(info_url, schema=_schema) - if not info: - self.logger.info("This stream is currently unavailable") - return - - app = "live" - self.logger.debug("Streaming server is: {0}", info["server"]) - if info["server"].endswith(":1337"): - app = "live-{0}".format(info["ingest"].lower()) - - stream = RTMPStream(self.session, { - "rtmp": "rtmp://{0}/live".format(info["server"]), - "app": "{0}?{1}".format(app, info["token"]), - "swfVfy": swf_url, - "pageUrl": self.url, - "live": True, - "playpath": "{domain}_{channel}".format(**params), - }) - - return dict(live=stream) + def api_url(self): + return random.choice(self.servers) + + def parse_ack(self, action, message): + if action.endswith("3"): + channel, _, viewers, token, server, choked, is_live, chls, trns, ingest = message.split(";") + is_live = is_live == "1" + viewers = int(viewers) + self.logger.debug("Viewers: {0}, isLive={1}", viewers, is_live) + domain, channel = channel.split("-", 1) + return is_live, server, domain, channel, token, ingest else: - self.logger.info("Found player_version={0}, info_url_domain={1}, info_url_path={2}", - player_version, info_url_domain, info_url_path) - if not player_version: - self.logger.error("Could not detect player_version") - if not info_url_domain: - self.logger.error("Could not detect info_url_domain") - if not info_url_path: - self.logger.error("Could not detect info_url_path") + self.logger.error("Unhandled action format: {0}", action) + + def _get_info(self, stream_name): + server = self.api_url() + self.logger.debug("Connecting to API: {0}", server) + ws = websocket.create_connection(server, + header=["User-Agent: {0}".format(useragents.CHROME)], + origin=self.origin, + class_=VLWebSocket, + session=self.session) + ws.send("MVN LOAD3 {0}".format(stream_name)) + action, message = ws.recv() + return self.parse_ack(action, message) + + def _get_rtmp_streams(self, server, domain, channel, token): + rtmp_server = self.rtmp_server_map.get(server, server) + + url = "rtmp://{0}/live?{1}".format(rtmp_server, token) + + yield "live", RTMPStream(self.session, params={ + "rtmp": url, + "pageUrl": self.url, + "playpath": "{0}_{1}".format(self.name_remap.get(domain, "live"), channel), + "live": True + }) + + def _get_streams(self): + res = http.get(self.url, headers={"User-Agent": useragents.CHROME}) + + m = self.api_re.search(res.text) + stream_name = m and m.group(1) + + if stream_name: + is_live, server, domain, channel, token, ingest = self._get_info(stream_name) + + if not is_live: + self.logger.info("Stream is currently off air") + else: + for s in self._get_rtmp_streams(server, domain, channel, token): + yield s __plugin__ = VaughnLive
vaughnlive plugin is buggy ### Checklist - [x] This is a bug report. - [x] This is a feature request. - [ ] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description vaughnlive streams may not work all the time as it shows not found ### Expected / Actual behavior ... ### Reproduction steps / Explicit stream URLs to test 1. vaughnlive.tv/sherming66 ### Environment details Operating system and version: Windows 7 Streamlink and Python version: 0.6.0 ### Comments, logs, screenshots, etc.
Could you please include what is printed out on the console when it does not work? Would you also be able to run it with `-l debug` and comment back what it says, there should be quite a bit if debug information. it prints out connection failed message sometimes when I open a vaughnlive stream. When it happens again can you copy the full message here, and if possible use the `-l debug` option as that will give us a much better idea of what is going wrong. ok thanks. @beardypig Vaughnlive recently switched to a HTML player from Flash, so that could be part of the issue. It says "no playable streams" I got no extra meaningful output by applying the debug flag, but I could have done it incorrectly. Edit: The correct syntax is: streamlink -l debug http://vaughnlive.tv/newzviewz/old best Might as well add it to all my .bat bookmarks. ![screenshot001](https://user-images.githubusercontent.com/12178152/27619691-4f6391d0-5b92-11e7-8cda-5b1a282c9f96.jpg) Will monitor this with interest. Thanks for looking! Ah OK, I didn't know that - I haven't actually been able to check the website. Sounds like we might need a rewrite of the plugin if they have finally stopped using flash! Seems they are still broadcasting a flash stream. If one appends /old to any Vaughnlive URL it'll access a flash version of the stream that'll work with Streamlink. Don't know how long it'll work. Edit: Worked for about 4 days? I can attest to techNeffect's comment. If you attach /old to the URL, it works immediately but fails with the mentioned above error if you don't. For me, it stopped working yesterday. This is the message I'm receiving. Curiously, even when I'm not using the '/old' appendix, the website still uses a Flash Player (on Firefox, at least): ``` C:\>streamlink vaughnlive.tv/erobtv/old live [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/erobtv/old [plugin.vaughnlive][info] Found player_version=0.1.1.796, info_url_domain=mvn.va ughnsoft.net, info_url_path=None [plugin.vaughnlive][error] Could not detect info_url_path error: No playable streams found on this URL: vaughnlive.tv/erobtv/old ``` Looks like the player has changed more than expected. I'll take a look at the html player soon :-) @beardypig Thanks a lot for you effort! If it's any help, a buddy of mine is reporting that the /old with livestreamer 1.12.2 is working still with /old but streamlink is not. Getting the same error as @EFEVE though it still seems to be pulling up the flash player whenever I go to the site (on chrome) even without having the "/old" prefix. Hope this can be fixed soonish as I despise the vaughnlive site. @JourneyOver I despise vaughnlive and their constantly changing crappy design choices! (though this change is to HTML5 so that's nice) :) Looks like the HTML5 player use WebSocket protocol (WSS) to get the m3u8 url. Example: Connect to > wss://sapi-ws-1x02.vaughnlive.tv Send > MVN LOAD2 #vl-jandjtrip Response > ACK2 #vl-jandjtrip;70;**CjAMPHqs2EVfoZ9FyKUI1vQehFWS5sNS**;**5940d648b3929**;0;1;1;0;ord And the m3u8 url will be: 5940d648b3929.streamlock.net/live/live_jandjtrip/playlist.m3u8?CjAMPHqs2EVfoZ9FyKUI1vQehFWS5sNS Vaughnlive is back to using /old on the http website to access flash, but it no longer works in streamlink as others have said. Defaults to HTML 5 when using browser as normal. When they reverted back to flash player a few days ago you could use /hls to access the HTML 5 player. It may do so again, so that may help in your testing if so. Current output, targeting /old site: ![screenshot001](https://user-images.githubusercontent.com/12178152/27846078-adafd012-6102-11e7-95df-9ff94d14c282.jpg) Thanks for looking, as always. Looks like they had an updated noting everyone should swap over for html5 by June 26th: https://blog.vaughnsoft.com/2017/06/17/video-encoder-settings/ so the plugin will need to be reworked. This is actually a pretty big improvement considering the headache vaughnlive has been in the past. For whatever it's worth, I tried with @techNeffect method of using /hls and got a different error. ``` C:\>streamlink vaughnlive.tv/erobtv/hls live [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/erobtv/hls error: No playable streams found on this URL: vaughnlive.tv/erobtv/hls ``` Hey @beardypig and @techNeffect when the vaughnlive plugin is gonna be fixed because i hate using flash player on vaughnlive site because it really slows down the pc and uses up a lot of cpu usage. Plz help me guys thanks. @bobvargas Someone will fix it when they have time to do so. Please remember that we are unpaid volunteers and this is an open source project that people work on in their spare time. If you would like to place a bounty on this issue feel free to do so here: https://www.bountysource.com/issues/46548041-vaughnlive-plugin-is-buggy. Otherwise it's all down to when someone has the time and interest to fix it. @bobvargas, @gravyboat has already explained this in one of your other threads: https://github.com/streamlink/streamlink/issues/315#issuecomment-269572638 As [someone who's opened a couple of issues here](https://github.com/streamlink/streamlink/issues?utf8=%E2%9C%93&q=is%3Aissue%20author%3Abobvargas%20), you could consider [supporting the people](https://www.bountysource.com/teams/streamlink) who are spending their time on solving these issues. Apart from that, Streamlink is still an open source software project with a [permissive license](https://github.com/streamlink/streamlink/blob/master/LICENSE), which means that you can always fix plugins or any kind of bug by yourself and contribute back to the project if you want to. ok thanks guys. Hi there, I have found a temporary solution until masters @beardypig and @gravyboat can fix the problem with streamlink plugin. In order to play vaughnlive streams, just use the /old url and livestreamer with this [script](https://raw.githubusercontent.com/intact/livestreamer/fix-vaughn/src/livestreamer/plugins/vaughnlive.py). Example of command: `livestreamer --plugin-dirs "Directory where vaughnlive.py file is found" http://vaughnlive.tv/newzviewz/old worst | vlc - ` ![screenshot from 2017-07-11 15-07-01](https://user-images.githubusercontent.com/28090483/28069731-cee07f5a-664a-11e7-8d7c-f14b08953265.png) Hope this helps :D so @skilleek method works for the time being, you don't need to download livestreamer at all though. what you can do is download the script from his link and put it in the plugins folder for streamlink (Default for me was "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugins"), rename the old plugin to vaughnlive.py.bak (or just replace the old script with the one from the script above) and then go into the new script and replace ``` from livestreamer.plugin import Plugin from livestreamer.plugin.api import http, validate from livestreamer.stream import RTMPStream ``` to ``` from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate from streamlink.stream import RTMPStream ``` @skilleek method works perfectly, even more so with @JourneyOver 's correction, you don't even need to put '/old' at the end of the link. It's broken again after today's update. The script returns with the error "No data returned from stream" now. I decompiled VaughnSoftPlayer.swf and it seems changes have been made in the way the player obtains the streaming server URL and the stream token. I believe it no longer uses INFO_URL to get this information. Instead, it uses an external call to MvnApi.getFlashData(). The output of this function can be seen on the console when loading a channel page, it looks like this: VTrace: flashData: 5940d648b3929;1tn5MjdACmQRLjmaJtWdPdMV7LeIDupG The part before the semicolon is the encoded streaming server IP and the part after it is the token. The correspondence between encoded and plain server IP is readily available from the decompiled source but I don't know if there is a way to call MvnApi.getFlashData() from a Python script, especially if this is prevented by the settings in crossdomain.xml. Of course, this only applies to the flash player which may soon be deprecated altogether. @fadster Yeah if we're going to fix it then it might as well be changed to no longer support the flash player, moving to an html5 player is the first thing that vaughnlive has done in a while that hasn't been annoying in terms of Streamlink functionality. Thanks for putting the time in to take a look and see what's up with it! @gravyboat Well, flash or html5, all we really want is a stream URL to pass to an external player. :smile: You're welcome! I'll report back if I find anything useful. bet once they do finally move everything over to the html5 player they are still going to try and fuck with livestreamer/streamlink a ton just because they want their stupid ad money :/ @JourneyOver I can't really blame them for wanting to stay fed with the hard work they're doing. It's one of the reasons we encourage people to donate to streaming services they like when possible. Without those ads/donations/subscriptions the services won't exist for us to help people stream! And it's completely broken now @kargaroc Yeah they probably phased out the flash player completely in favor of their html5 player. Actually it still begs for me to install Flash at the moment. Being on Linux, I have no way of watching their streams anymore until this plugin gets fixed or replaced, or they actually enable their HTML5 player. @kargaroc Yeah if you aren't willing to make Flash happen and their HTML5 player doesn't work properly for you there's not much we can do. If someone wants to update the plugin they'll say so. You can also place a bounty on this issue if you would like: https://www.bountysource.com/issues/46548041-vaughnlive-plugin-is-buggy @kargaroc I know what you mean there. Technically Chrome on Linux is supposedly supposed to have Flash but it doesn't always seem to be properly detected by various websites which act like you don't have Flash and need an upgrade. To remedy this and it has worked for me for Vaughlive in the past is, use Opera Mini for Linux if you do want to watch Vaughlive streams on your Linux PC in the mean time. They have indeed reverted to the flash player on the main site but the embeds use the html5 player. The old INFO_URL used by the streamlink plugin to get the stream URL now returns a 404 so that mechanism seems to have been phased out altogether. Even though the new implementation might make things a bit more difficult, I'm fairly certain we can still get this information but I haven't looked much into it. The comment made by @RosadinTV regarding the way the html5 player gets the m3u8 URL could be our most promising avenue. Guys, With the modifications they have been making, now it's possible to catch it again, just add the referer: `streamlink --http-header "Referer=http://vaughnlive.tv/newzviewz" "hls://https://hls-ord-2a.vaughnsoft.net/nyc/live/live_newzviewz/chunklist.m3u8" best` ![screenshot from 2017-07-17 15-07-05](https://user-images.githubusercontent.com/28090483/28269319-e4251e6e-6b01-11e7-8b71-1b011b5bf80b.png) Hopefully this will be a more permanent solution. I am glad to help you all and encourage people to keep collaborating to improve streamlink :D I'm working on an updated version of the plugin using the new websocket API. `newzviewz` is actually a special case and handled slog differently to some of the other channels. Some channels are only available via rtmp and not hls, but some support both. Hopefully I'll PR an updated plugin in the next couple of days. @skilleek How do you find the server for a given channel? I got a 404 when I tried your method on other channels that have been switched to hls (eg. kingthehilltv1). Most streams are on all servers, but you need to know the `ingest` part. In the case of `newzviewz` it's `nyc`, and for `kingthehilltv1` it's `ord`, so ``` streamlink --http-header "Referer=http://vaughnlive.tv/kingthehilltv1" "hls://https://hls-ord-2a.vaughnsoft.net/ord/live/live_kingthehilltv1/chunklist.m3u8" best ``` should work. To find out the `ingest` part, you need to consult the API :) @beardypig Thanks! I don't know if there's a better way to find out but I got the info from looking at the console output on a channel page. Yep, you can get it from the console - for the plugin it will use the API :) how about sherming66 url? i tried to stream it. @bobvargas Look at the console output in your browser, you'll find all the info you need. streamlink --http-header "Referer=http://vaughnlive.tv/sherming66" "hls://https://hls-ord-2a.vaughnsoft.net/ord/live/live_sherming66/chunklist.m3u8" best ok i'll try thanks yep it works thank you @fadster. @fadster It is working ^^. Same here, ありがとう :) Looks like they also fixed the exploit url as well :( Hey @fadster sometimes the url you gave (streamlink --http-header "Referer=http://vaughnlive.tv/newzviewz" "hls://https://hls-ord-2a.vaughnsoft.net/nyc/live/live_newzviewz/chunklist.m3u8" best) can sometimes bring up a 404 error other times it may work. Hopefully a full plugin fix would resolve it soon. Oh btw vaughnlive on streamlink is fully broken because of no flash player version appearing at all :( C:\Users\Bob>streamlink vaughnlive.tv/sherming66 live [cli][info] Found matching plugin vaughnlive for URL vaughnlive.tv/sherming66 error: No playable streams found on this URL: vaughnlive.tv/sherming66 and the url you gave return an error... C:\Users\Bob>streamlink --http-header "Referer=http://vaughnlive.tv/sherming66" "hls://https://hls-ord-2a.vaughnsoft.net/ord/live/live_sherming66/chunklist.m3u8 " best [cli][info] Found matching plugin stream for URL hls://https://hls-ord-2a.vaughn soft.net/ord/live/live_sherming66/chunklist.m3u8 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (hls) [cli][error] Try 1/1: Could not open stream <HLSStream('https://hls-ord-2a.vaugh nsoft.net/ord/live/live_sherming66/chunklist.m3u8')> (Could not open stream: Una ble to open URL: https://hls-ord-2a.vaughnsoft.net/ord/live/live_sherming66/chun klist.m3u8 (404 Client Error: Not Found for url: https://hls-ord-2a.vaughnsoft.n et/ord/live/live_sherming66/chunklist.m3u8)) error: Could not open stream <HLSStream('https://hls-ord-2a.vaughnsoft.net/ord/l ive/live_sherming66/chunklist.m3u8')>, tried 1 times, exiting I don't know if vaughnlive has officially gone all html5 or what. let me know if there's a fix soon @bobvargas The error you're getting just means the stream is currently offline. @fadster just kidding i found the problem it was (streamlink --http-header "Referer=http://vaughnlive.tv/sherming66" "hls://https://hls-ord-2a.vaughnsoft.net/den/live/live_sherming66/chunklist.m3u8" best) not (streamlink --http-header "Referer=http://vaughnlive.tv/sherming66" "hls://https://hls-ord-2a.vaughnsoft.net/ord/live/live_sherming66/chunklist.m3u8" best) now it finally works sorry @fadster for the other post I made eariler. The stream is on a different ingest server now so the URL changed. As was mentioned in previous comments, you can get this information by looking at the console output in your browser's developer tools. The command for that stream is now: streamlink --http-header "Referer=http://vaughnlive.tv/sherming66" "hls://https://hls-ord-2a.vaughnsoft.net/den/live/live_sherming66/chunklist.m3u8" best Note the change from `ord` to `den`, as indicated by the following line printed on the console when you load the channel's page: >>> hlsServer: hls-ord-2a.vaughnsoft.net/den streamlink now seems to need hlsvariant:// instead of hls://: `[cli][error] Try 1/1: Could not open stream <HLSStream('https://hls-ord-4a.vaughnsoft.net/den/live/live_sherming9/playlist.m3u8')> (Could not open stream: Attempted to play a variant playlist, use 'hlsvariant://https://hls-ord-4a.vaughnsoft.net/den/live/live_sherming9/playlist.m3u8' instead)` @rtega for `playlist.m3u8`, yes you will need to use `hlsvariant`, but if you use the `chunklist.m3u8` url you will need to use `hls`. Just to quickly explain hls:// vs hlsvariant:// for anybody, because I was confused for a second when I first seen it, but hls:// is for a single bitrate/resolutions playlist while hlsvariant:// is for a playlist with multiple bitrates/resolutions. You can tell if you open the m3u8 in a text editor if it is single or variant. just to let you know @fadster's vaughnlive url treak also works with livestreamer. However some questions to ask do Vaughnlive flash url version works though? And if using the new url exploit does it doss the broadcaster? @bobvargas you mean the rtmp URLs? They still exist, at least for the channels I have tried, but getting the rtmp URL is not as simple. Using the rtmp or hls stream will not doss the broadcaster, the broadcasts stream to vl and then vl re-stream it to you. The broadcaster only sends the stream once, so 0 or a 1,000 viewers makes no difference to the broadcaster. Any progress made to fix vaughnlive stream yet? Oh Btw sometimes some vaughnlive broadcasters can have multiple servers working besides the main one. Example >>> hlsServer: hls-ord-2a.vaughnsoft.net/ord ![image](https://user-images.githubusercontent.com/24505327/28490429-17b02342-6ea8-11e7-8122-ec38ac27d858.png) ![image](https://user-images.githubusercontent.com/24505327/28490439-374c393e-6ea8-11e7-8a6b-b504827b1e00.png) ![image](https://user-images.githubusercontent.com/24505327/28490446-5a378250-6ea8-11e7-94de-e4e4c54fd254.png) I tried it multiple vaughnlive servers and sometimes these 3 servers work even if it not ord. Well here's something to think about @fadster @beardypig let's use to following url C:\Users\SUS>streamlink --http-header "Referer=http://vaughnlive.tv/sherming66" "hls://https://sherming66;7;100;itojBxGRAWsyyUozOddeW75NufwmPLdO;594140c69edad;0 ;1;1;0;ord if this work it may use to stream the flash player version as well... plz post. Well here's something to think about @fadster @beardypig let's use to following url C:\Users\SUS>streamlink --http-header "Referer=http://vaughnlive.tv/sherming66" "hls://https://sherming66;7;100;itojBxGRAWsyyUozOddeW75NufwmPLdO;594140c69edad;0 ;1;1;0;ord if this work it may use to stream the flash player version as well... Hey @beardypig How do you find the rtmp url on vaughnlive plz help me. @bobvargas Please don't tag people in two comments like that (edit instead), and don't close this as it isn't fixed. Please remember this is an unpaid 'job' we do on the side, and we all have lives to live. @bobvargas please wait a few days while I complete the plugin. @gravyboat sorry about that. And one last thing the url that @fadster given was a html 5 version of the stream. Hopefully the fixed plugin would still use rtmp (flash streams) because the html 5 version still have buffering issues for a channel. @bobvargas The new version won't support flash as far as I know (@beardypig can probably confirm). Vaughn is basically EOL'ing their flash stuff. The site is now defaulting to a new flash player. The html5 player is still accessible by adding /hls to a channel's URL (https://www.facebook.com/thevaughn/posts/10159028932310640). Note that for some channels I've had to use `hlsvariant` with `playlist.m3u8` as `hls` with `chunklist.m3u8` was timing out. This could just be a transient glitch though. Hi @Fadster i was wondering do you have a url fix for rtmp flash streams on vaughnlive because the html5 streams keeps buffering every 15 minutes. Even your hls method still has buffering issue because of html 5 servers/ player of vaughnlive plz give us a flash rtmp streams url thanks. @fadster which channels did you have to use the `playlist.m3u8` url for?
2017-07-26T15:09:28
streamlink/streamlink
1,119
streamlink__streamlink-1119
[ "966", "963" ]
e6db4113c204d20239f619e0bc5769d2416c989e
diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py --- a/src/streamlink/plugins/twitch.py +++ b/src/streamlink/plugins/twitch.py @@ -203,8 +203,7 @@ def call(self, path, format="json", schema=None, **extra_params): headers = {'Accept': 'application/vnd.twitchtv.v{0}+json'.format(self.version), 'Client-ID': TWITCH_CLIENT_ID} - # The certificate used by Twitch cannot be verified on some OpenSSL versions. - res = http.get(url, params=params, verify=False, headers=headers) + res = http.get(url, params=params, headers=headers) if format == "json": return http.json(res, schema=schema)
Enable certificate verification for Twitch ### Description Certificate verification is disable when making API calls in the Twitch plugin. According to comments in the code, "The certificate used by Twitch cannot be verified on some OpenSSL versions." The commit to disable verification was done 3 years ago during Livestreamer development, but the specifics are unclear. It might be risky to re-enable it and wait for people to complain that it doesn't work. The issue could be limited to Python 2.6 or perhaps Windows? I have no problems enabling certificate verification on Python 2.7/3.5/3.6 under Linux or macOS. The question is how should we go about re-enabling the verification? ### Expected / Actual behaviour Streamlink should _always_ verify SSL certificates, but it does not. ### Environment details Streamlink and Python version: `streamlink<=0.6.0` Related to #963 InsecureRequestWarning error on connecting to Twitch channels ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description error on connecting to Twitch channels (formatted to increase readability): <user-pip-folder>/lib/python3.5/site-packages/urllib3/connectionpool.py:852 InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings ### Environment details Xubuntu 16.04 LTS Streamlink 0.6.0 Python 3.5.2 ### Other notes My streamlink invocation (which I've been using since livestreamer days): streamlink \ --http-header (Twitch ID) \ --retry-open 8000 \ --retry-streams 10 \ --player-continuous-http \ --player-passthrough hls \ --hls-segment-threads 3 \ --player "mpv" \ URL
I did some digging: - The commit that added it: https://github.com/chrippa/livestreamer/commit/5f6a3d3fe24f50b161be66e711db2989eea1e378 - The issue describing the problem: https://github.com/chrippa/livestreamer/issues/255 Seemed to be two problems: 1. A specific version of `ca-certificates` for Arch Linux 2. MITM-proxies I don't think the first issue is still relevant. However, the second part should be investigated. I don't think there are any reasons for keeping this disabled. That's weird, certificate verification should be enabled on any https request. Can you try curling the URL and see if it also gives a warning about certificates? Sure, here is the output curl https://twitch.tv/<channel-name> <html> <head><title>302 Found</title></head> <body bgcolor="white"> <center><h1>302 Found</h1></center> <hr><center>nginx</center> </body> </html> @beardypig the twitch plugin explicitly disables certificate verification: https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugins/twitch.py#L207 ``` # The certificate used by Twitch cannot be verified on some OpenSSL versions. res = http.get(url, params=params, verify=False, headers=headers) ``` changing to `verify=True` removes the warnings. what's interesting is streamlink should be silencing these InsecureRequestWarnings: https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugin/api/http_session.py#L20 ``` # We tell urllib3 to disable warnings about unverified HTTPS requests, # because in some plugins we have to do unverified requests intentionally. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) ``` so the crux of this issue is that call to disable_warnings is no longer working. if i remove the `try`/`except` block it works, so it isn't throwing an exception. i can still suppress the warning by setting the `PYTHONWARNINGS` environmental variable, so it's possible: ``` PYTHONWARNINGS="ignore:Unverified HTTPS request" streamlink https://www.twitch.tv/sovietwomble ``` Ah true... I'll try to recreate it, I haven't seen those warnings recently... @globau do you get the warnings? Which python version/OS are you running? @beardypig yes - Python 2.7.13 (homebrew) on OSX 10.12.5. @globau @v1kn could you let me know which version of `requests` and `urllib3` you are using. You should be able to find the versions by using `pip freeze`. @beardypig Up till yesterday I had `requests 2.16.5`. My systemd service for updating pip packages ran yesterday, now the package is `2.17.3`, and the issue is gone. No more errors. So this was a `requests` thing? @beardypig `requests 2.16.5` and `urllib3 1.21.1`. With `2.16.x` I do get the warnings, with `2.17.1+` I do not get the warnings, `2.15.x` also does not give the warnings. It appears to be an issue with `requests`. @globau are you able to update to `requests>=2.17.1`. @beardypig good to know. For me the issue is resolved, at least for now. @beardypig yes, upgrading requests resolves this issue for me too. From testing, versions `2.16.0`, `2.16.1`, `2.16.2`, `2.16.3`, `2.16.4`, `2.16.5`, `2.17.1` are all affected. Other then editing the twitch.py file and change # The certificate used by Twitch cannot be verified on some OpenSSL versions. res = http.get(url, params=params, verify=False, headers=headers) to True, is there something I can add to the configuration file to make it bypass the InsecureRequestWarning? You can try the latest nightly, I think it should have the fix now... Just tested the latest nightly and still ``` [cli][info] Found matching plugin twitch for URL twitch.tv/crream [plugin.twitch][info] Attempting to authenticate using OAuth token d:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) [plugin.twitch][info] Successfully logged in as Thinkpad4 d:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) d:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) [plugin.twitch][info] crream is hosting admiralbahroo [plugin.twitch][info] hosting was disabled by command line optiond:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) error: No playable streams found on this URL: twitch.tv/crream ``` Edit, copying the Requests folder from here https://pypi.python.org/packages/6d/ed/3adebdc29ca33f11bca00c38c72125cd4a51091e13685375ba4426fb59dc/requests-2.15.1.tar.gz over the one in the Streamlink folder fixed this issue for me, but I still would like to not have to do this every time I install the latest nightly That's strange, I cannot reproduce that warning. Could you re-download the latest nightly, uninstall and reinstall it. I used [streamlink-0.6.0-20170603.exe](https://bintray.com/streamlink/streamlink-nightly/download_file?file_path=streamlink-0.6.0-20170603.exe) (generated 6 hours ago), and I did not get the warning when playing a twitch stream. Yep, uninstalling the old version and install that nightly works with no issue I just deleted the files in the install directory, then installed the nightly to that directory. On a side note, does uninstalling delete the config file in Appdata/Roaming? I ask because I have written instructions for people on a twitch channel I mod to follow to install this. I wanna know if I need to add a line about remaking the config file if it is deleted when uninstalling. I haven't encountered this issue since @beardypig suggested I uninstall and reinstall the nightly. Since then I have installed newer nightlies, without uninstalling, without any issues @thinkpad4 Thanks for the update, are we good to close this out then? Edit: Hit close and comment instead of just comment like an idiot. And using the latest Nightly [cli][info] Found matching plugin twitch for URL twitch.tv/crream [plugin.twitch][info] Attempting to authenticate using OAuth token d:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRe questWarning: Unverified HTTPS request is being made. Adding certificate verific ation is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advance d-usage.html#ssl-warnings InsecureRequestWarning) [plugin.twitch][info] Successfully logged in as Thinkpad4 d:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRe questWarning: Unverified HTTPS request is being made. Adding certificate verific ation is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advance d-usage.html#ssl-warnings InsecureRequestWarning) d:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRe questWarning: Unverified HTTPS request is being made. Adding certificate verific ation is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advance d-usage.html#ssl-warnings InsecureRequestWarning) d:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:852: InsecureRe questWarning: Unverified HTTPS request is being made. Adding certificate verific ation is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advance d-usage.html#ssl-warnings InsecureRequestWarning) error: No playable streams found on this URL: twitch.tv/crream Getting this again, it WAS working with the nightlies until today. Uninstalling did NOT work to resolve it this time. It DID work the last time The certificate used by Twitch cannot be verified on some OpenSSL versions. res = http.get(url, params=params, verify=False, headers=headers) Might have to be made default to True to make sure this doesn't keep happening
2017-07-27T14:50:34
streamlink/streamlink
1,121
streamlink__streamlink-1121
[ "573" ]
e6db4113c204d20239f619e0bc5769d2416c989e
diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -673,18 +673,12 @@ def setup_http_session(): streamlink.set_option("http-timeout", args.http_timeout) if args.http_cookies: - console.logger.warning("The option --http-cookies is deprecated since " - "version 1.11.0, use --http-cookie instead.") streamlink.set_option("http-cookies", args.http_cookies) if args.http_headers: - console.logger.warning("The option --http-headers is deprecated since " - "version 1.11.0, use --http-header instead.") streamlink.set_option("http-headers", args.http_headers) if args.http_query_params: - console.logger.warning("The option --http-query-params is deprecated since " - "version 1.11.0, use --http-query-param instead.") streamlink.set_option("http-query-params", args.http_query_params)
cli: please remove deprecated warning messages ### Checklist - [ ] This is a bug report. - [ ] This is a plugin request. - [x] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description Since livestreamer 1.11.0 was released, deprecated warning have been added to following switches : ``` Deprecated the --http-cookies option. Deprecated the --http-headers option. Deprecated the --http-query-params option. ``` Fortunatelly those switches haven't been removed. But sometimes they don't allow to use full features that's why switches which allow repeating functions have also been added. ### Expected / Actual behavior Switches above are very useful because they allow to add several informations on one line using only one switch and features are separated by ";" For instance : ``` streamlink --http-headers "User-Agent=android;X-Forwarded-For=0.0.0.0;Cookies=4545s4fsfsf4s;X-Requested-With=;Referer=;X-Do-Not-Track=" streamlink --http-query-params "video_id=100;authority_instance_id=spectar-prd-cgt;token=74n8mnSREdQ4X-anI1rCXw" "hlsvariant://http:// [cli][warning] The option --http-query-params is deprecated since version 1.11.0 , use --http-query-param instead. ``` ### Environment details (operating system, python version, etc.) Python 2.7.13 ### Comments, logs, screenshots, etc. So it will be useful to keep both features as each one provide advantages. They are complementary. That's why I would like to ask if you could please remove deprecated warning messages because I hope they are not intended to be removed.
Having two command line arguments that do the same thing is generally not a good idea. I would say that `http-header` is superior to `http-headers`. With `http-header` you can specify multiple Headers in different places, for example in `streamlinkrc` and in the command line, with those on the command line taking precedence over those in the config. `http-headers` will overwrite all of the headers and cannot be combined from the config file. You can load configuration options for a file too. For example, for the stream you give in your example you could create `stream.cfg`: ```cfg http-header=User-Agent=android http-header=X-Forwarded-For=0.0.0.0 http-header=X-Requested-With= http-header=Referer= http-header=X-Do-Not-Track= http-cookie=authToken=4545s4fsfsf4s http-query-param=video_id=100 http-query-param=authority_instance_id=spectar-prd-cgt http-query-param=token=74n8mnSREdQ4X-anI1rCXw ``` And then load it on the command line using the `@` syntax (which might not be documented): ```shell $ streamlink @stream.cfg "hlsvariant://http://test.se/example" ``` And then, if you wish to override the cookie or one of the query params you can just add those on the command line too: ```shell $ streamlink @stream.cfg --http-cookie "authToken=aNewToken" --http-query-param "token=otherNewToken" "hlsvariant://http://test.se/example" ``` Much cleaner, and more manageable I think... Hi Beardypig I use batch file with channels and for instance I put general query on one line as it's used on all channels : `set "query_channelname=video_id=95;authority_instance_id=spectar-prd-hrt;token=utS3Py8Fg8B0ZmzTdi6oZg"` I call it simply by `streamlink --http-query-params "%query_channelname%" "hlsvariant://server:port/HLS/channelname"` With --http-query-param switch I would be obliged to repeat it for each part of query above as that : `streamlink --http-query-param "video_id=95" --http-query-param "authority_instance_id=spectar-prd-hrt" --http-query-param "token=utS3Py8Fg8B0ZmzTdi6oZg" "hlsvariant://server:port/HLS/channelname"` As you can see it's much longer with repeatable switch and I can't make one general line by setting full query replaced by %query_channelname%. Second example : set "headers_test=User-Agent=android;X-Forwarded-For=0.0.0.0;Cookies=4545s4fsfsf4s;X-Requested-With=XMLHttpRequest;Referer=;X-Do-Not-Track=" It's much simplier : `streamlink --http-headers "%headers_test%" "hlsvariant://server:port/sub/channelname" ` than to repeat it for each part. I didn't ask to remove repeatable switches on the contrary. At least please don't remove them those three general commands in future development, because it will be pain in the arse for me. In documentation, you can add examples for general switches I think people will not mixed up it with each others when they see examples. Thanks. I don't seem those options being removed any time soon, but I don't see them been un-deprecated either. Surely if it's in a batch script then it doesn't matter if it's longer? Or do you run the batch script, then run the streamlink command? If it's the latter, I'd look at using the `@`syntax to import config files instead. I have plenty examples used in my batch file and they take just one line by example, that's why for me general switch is much more interesting otherwise I will be obliged to make small files with headers for every example. I edit this batch for every new channel I find so for me it's important that all informations are centralised in one batch file. In brief my batch file is a playlist with channels which use plugins mainly. I made shortcut on desktop to my batch file from where I run streamlink with all headers and queries required so making for 6 different networks will not be as transparent as it's now. What do you think to add to following switches same syntax as to general ones without removing repeatable ability? ``` --http-cookie --http-header --http-query-param ``` Could do that... best of both worlds.
2017-07-27T15:29:19
streamlink/streamlink
1,129
streamlink__streamlink-1129
[ "1127" ]
8d2a607eab240e36b230bcb52d113d023378a146
diff --git a/src/streamlink/plugins/adultswim.py b/src/streamlink/plugins/adultswim.py --- a/src/streamlink/plugins/adultswim.py +++ b/src/streamlink/plugins/adultswim.py @@ -24,7 +24,7 @@ class AdultSwim(Plugin): live_schema = validate.Schema({ u"streams": { validate.text: {u"stream": validate.text, - u"isLive": bool, + validate.optional(u"isLive"): bool, u"archiveEpisodes": [{ u"id": validate.text, u"slug": validate.text, @@ -88,7 +88,7 @@ def _get_live_stream(self, stream_data, show, episode=None): for epi in show_info[u"archiveEpisodes"]: if epi[u"slug"] == episode: stream_id = epi[u"id"] - elif show_info["isLive"] or not len(show_info[u"archiveEpisodes"]): + elif show_info.get("isLive") or not len(show_info[u"archiveEpisodes"]): self.logger.debug("Loading LIVE streams for: {0}", show) stream_id = show_info[u"stream"] else: # off-air
AdultSwim stream broken ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description running `streamlink.exe http://www.adultswim.com/videos/streams best` does not open the AdultSwim stream. ### Expected / Actual behavior Expected: open the AdultSwim stream Actual behavior: `error: Unable to validate JSON: Unable to validate key 'streams': Key 'isLive' not found in {'description': 'Walk with Him all-day long.', 'email': '', 'archiveCollection': [], 'stream': 'At-rci-fT1SgqmQ2ZA5XtQ', 'id': 'black-jesus', 'pipVideoID': '', 'chat': '', 'doc_id': 'video_stream_shows_black_jesus_marathon', 'showLinks': [{'external': False, 'value': 'More Black Jesus', 'url': 'http://www.adultswim.com/videos/black-jesus/'}, {'external': False, 'value': 'Facebook', 'url': 'http://www.facebook.com/BlackJesus'}, {'external': True, 'value': 'Twitter', 'url': 'https://twitter.com/blackjesusshow'}], 'url': 'http://www.adultswim.com/videos/streams/black-jesus/', 'telephone': '', 'schedule': [], 'images': {'video': 'http://i.cdn.turner.com/adultswim/big/video/black-jesus-marathon/marathonStream_blackjesus.jpg'}, 'chatService': 'http://www.adultswim.com/utilities/api/v1/live/chat/black-jesus', 'type': 'marathon', 'archiveEpisodes': [], 'sponsor':{'link': '', 'title': '', 'imageUrl': ''}, 'title': 'Black Jesus', 'rating': 'TV-MA'}` ### Reproduction steps / Explicit stream URLs to test look above ### Environment details Operating system and version: Windows 7 64bit Streamlink and Python version: Python 3.5.2/Streamlink 0.7.0 [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
2017-07-31T08:42:44
streamlink/streamlink
1,143
streamlink__streamlink-1143
[ "1138" ]
39d8093787508a78630445b2aefaf6e1feef7dfc
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -46,6 +46,9 @@ deps.append("websocket-client") +# Support for SOCKS proxies +deps.append("requests[socks]") + # When we build an egg for the Win32 bootstrap we don't want dependency # information built into it. if environ.get("NO_DEPS"): diff --git a/src/streamlink/session.py b/src/streamlink/session.py --- a/src/streamlink/session.py +++ b/src/streamlink/session.py @@ -1,11 +1,12 @@ import imp -import locale import pkgutil import re import sys import traceback import requests + +from streamlink.utils import update_scheme from streamlink.utils.l10n import Localization from . import plugins, __version__ @@ -230,13 +231,9 @@ def set_option(self, key, value): key = "subprocess-errorlog-path" if key == "http-proxy": - if not re.match("^http(s)?://", value): - value = "http://" + value - self.http.proxies["http"] = value + self.http.proxies["http"] = update_scheme("http://", value) elif key == "https-proxy": - if not re.match("^http(s)?://", value): - value = "https://" + value - self.http.proxies["https"] = value + self.http.proxies["https"] = update_scheme("https://", value) elif key == "http-cookies": if isinstance(value, dict): self.http.cookies.update(value)
SOCKS Support? can we get socks support? way simpler than http, also requests supports it https://github.com/requests/requests/issues/3172
_Please follow the guidelines for creating issues in the future._ This is a good feature to have, I didn't realise they had add support in `requests` :) It should be pretty straight forward to add socks support.
2017-08-04T16:57:57
streamlink/streamlink
1,168
streamlink__streamlink-1168
[ "1164", "921" ]
0521ae3ca127f7cc600f1adcbc18b302760889ab
diff --git a/src/streamlink/plugins/cdnbg.py b/src/streamlink/plugins/cdnbg.py --- a/src/streamlink/plugins/cdnbg.py +++ b/src/streamlink/plugins/cdnbg.py @@ -1,13 +1,14 @@ from __future__ import print_function + import re -from streamlink import PluginError +from streamlink.compat import urlparse from streamlink.plugin import Plugin from streamlink.plugin.api import http from streamlink.plugin.api import useragents from streamlink.plugin.api import validate from streamlink.stream import HLSStream -from streamlink.compat import urlparse +from streamlink.utils import update_scheme class CDNBG(Plugin): @@ -17,12 +18,14 @@ class CDNBG(Plugin): bitelevision\.com/live| nova\.bg/live| kanal3\.bg/live| - bgonair\.bg/tvonline + bgonair\.bg/tvonline| + tvevropa\.com/na-zhivo| + bloombergtv.bg/video )/? """, re.VERBOSE) iframe_re = re.compile(r"iframe .*?src=\"((?:https?:)?//(?:\w+\.)?cdn.bg/live[^\"]+)\"", re.DOTALL) sdata_re = re.compile(r"sdata\.src.*?=.*?(?P<q>[\"'])(?P<url>http.*?)(?P=q)") - hls_file_re = re.compile(r"file: (?P<q>[\"'])(?P<url>http.+?m3u8.*?)(?P=q)") + hls_file_re = re.compile(r"(src|file): (?P<q>[\"'])(?P<url>(https?:)?//.+?m3u8.*?)(?P=q)") hls_src_re = re.compile(r"video src=(?P<url>http[^ ]+m3u8[^ ]*)") stream_schema = validate.Schema( @@ -54,11 +57,9 @@ def _get_streams(self): if iframe_url: self.logger.debug("Found iframe: {0}", iframe_url) res = http.get(iframe_url, headers={"Referer": self.url}) - try: - return HLSStream.parse_variant_playlist(self.session, - self.stream_schema.validate(res.text), - headers={"User-Agent": useragents.CHROME}) - except PluginError: - return + stream_url = update_scheme(self.url, self.stream_schema.validate(res.text)) + return HLSStream.parse_variant_playlist(self.session, + stream_url, + headers={"User-Agent": useragents.CHROME}) __plugin__ = CDNBG
Bug report: Changes in cdnbg plugin - streams not opening and 2 new channels ### Checklist - [x] This is a bug report. - [x] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description No playable streams found on these URLs. These channels seem to be using a new video player, while content is still coming in from cdn.bg. Other cdn links seem to be working with the old code for the time being, I'm not sure if/when they will migrate to this new videoplayer. http://www.bgonair.bg/tvonline http://kanal3.bg/live http://tv.bnt.bg/bnt2/16x9/ http://tv.bnt.bg/bnt1/16x9/ Also, **Bloomberg Bulgaria and TV Evropa have migrated to CDN.bg**, so they can be added to this plugin. The original request for Bloomberg (#921) can be closed if this is done. The live channel can be found at this link: http://www.bloombergtv.bg/video TV Evropa can be found at this link: http://www.tvevropa.com/na-zhivo/ ### Additional problems encountered http://tv.bnt.bg/bnt1/4x3 - there seems to be nothing on this URL any longer, even though there's a link in the website. Either they haven't updated the website, or they've deprecated the non-HD 4x3 stream. http://tv.bnt.bg/bnt1/hd/ - slight delay between the video and the audio (audio seems to be lagging by a fraction of a second, as you can see that the newscasters' lips aren't in sync). Not sure if this is a plugin problem, decided to share anyway. ### Comments These streams may be and probably are geo-restricted to Bulgaria. Here are some proxy options: 1. http://bgproxy.org/ 2. https://nqma.net/ 3. http://www.bgproxy.net/bg/index.php 4. http://www.php-proxy.net/ Plugin Request: Bloomberg Bulgaria ---- ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description A simple plugin for Bloomberg Bulgaria, hosted at http://www.bloombergtv.bg/video which uses https://flowplayer.org/ to livestream and post videos.
2017-08-14T14:19:05
streamlink/streamlink
1,247
streamlink__streamlink-1247
[ "1234" ]
e7b3e6fc91afbe730acf614d742b0395870372d9
diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -1010,6 +1010,8 @@ def check_version(force=False): def main(): + error_code = 0 + setup_args() setup_streamlink() setup_plugins() @@ -1028,16 +1030,12 @@ def main(): try: streamlink.resolve_url(args.can_handle_url) except NoPluginError: - sys.exit(1) - else: - sys.exit(0) + error_code = 1 elif args.can_handle_url_no_redirect: try: streamlink.resolve_url_no_redirect(args.can_handle_url_no_redirect) except NoPluginError: - sys.exit(1) - else: - sys.exit(0) + error_code = 1 elif args.url: try: setup_options() @@ -1048,13 +1046,14 @@ def main(): if output: output.close() console.msg("Interrupted! Exiting...") + error_code = 130 finally: if stream_fd: try: console.logger.info("Closing currently open stream...") stream_fd.close() except KeyboardInterrupt: - sys.exit() + error_code = 130 elif args.twitch_oauth_authenticate: authenticate_twitch_oauth() elif args.help: @@ -1066,3 +1065,5 @@ def main(): "read the manual at https://streamlink.github.io" ).format(usage=usage) console.msg(msg) + + sys.exit(error_code)
keyboard interrupt should not exit with code 0 currently streamlink exit with 0 when hit by keyboard interrupt, it's hard to handle within automation script, https://unix.stackexchange.com/questions/223189/what-does-exit-code-130-mean-for-postgres-command - if the process exited with exit(n) or return n from main(): the lower 8 bits of n (n & 0xFF). - if the process was killed by signal n: n + 128. that do have some convention so people can handle them graceful with script
Could you please send a PR with a fix here: https://github.com/streamlink/streamlink/blob/0.8.1/src/streamlink_cli/main.py#L1041-L1057 Related issue: #781 (which btw looks like it has been closed by accident) https://github.com/streamlink/streamlink/blob/0.8.1/src/streamlink_cli/main.py#L247-L257 @bastimeyer thanks for the head up, I will just left this here by now, will do PR if I have free time,
2017-09-29T03:53:28
streamlink/streamlink
1,268
streamlink__streamlink-1268
[ "1267" ]
1b74cdaba7c274dbf7de85540216f5b057921937
diff --git a/src/streamlink/plugins/kanal7.py b/src/streamlink/plugins/kanal7.py --- a/src/streamlink/plugins/kanal7.py +++ b/src/streamlink/plugins/kanal7.py @@ -3,6 +3,7 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http +from streamlink.plugin.api import useragents from streamlink.plugin.api import validate from streamlink.stream import HLSStream @@ -10,7 +11,7 @@ class Kanal7(Plugin): url_re = re.compile(r"https?://(?:www.)?kanal7.com/canli-izle") iframe_re = re.compile(r'iframe .*?src="(http://[^"]*?)"') - stream_re = re.compile(r'src: "(http[^"]*?)"') + stream_re = re.compile(r'src="(http[^"]*?)"') @classmethod def can_handle_url(cls, url): @@ -34,7 +35,7 @@ def _get_streams(self): stream_m = self.stream_re.search(ires.text) stream_url = stream_m and stream_m.group(1) if stream_url: - yield "live", HLSStream(self.session, stream_url) + yield "live", HLSStream(self.session, stream_url, headers={"Referer": iframe2}) else: self.logger.error("Could not find second iframe, has the page layout changed?") else:
Kanal7 Plugin defective! Hi there, can you have a look on the kanal7.py please? "error: No playable streams found on this URL" Greetings
2017-10-12T10:48:04
streamlink/streamlink
1,302
streamlink__streamlink-1302
[ "1282" ]
160e34a4f35d201984dbf519254c8b8d15e95340
diff --git a/src/streamlink/plugins/tvcatchup.py b/src/streamlink/plugins/tvcatchup.py --- a/src/streamlink/plugins/tvcatchup.py +++ b/src/streamlink/plugins/tvcatchup.py @@ -6,7 +6,7 @@ USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" _url_re = re.compile(r"http://(?:www\.)?tvcatchup.com/watch/\w+") -_stream_re = re.compile(r'''(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''') +_stream_re = re.compile(r'''source.*?(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''') class TVCatchup(Plugin):
TVCatchup plugin is not working - "This service is ending soon" ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description TVCatchup plugin is not working for some time. The problem is that plugin is able to connect to a stream without any errors but the stream is different comparing to the TVCatchup website's stream. It looks like streamlink gets a different type of stream deliberately prepared by the service provider to send the message: "This service is ending soon. Please download TVCatchup from the app store". Assuming that there is a real stream available on the website and mobile app, is it still possible to open it by streamlink? Current stream for all of the channels: ![image](https://user-images.githubusercontent.com/12859955/31864398-f6226d86-b75c-11e7-84fe-b633eaef66e8.png) Thanks ### Reproduction steps / Explicit stream URLs to test streamlink http://tvcatchup.com/watch/bbctwo best ### Environment details Operating system and version: Windows/Linux Streamlink and Python version: Streamlink 0.8.1 [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
2017-11-01T12:08:26
streamlink/streamlink
1,311
streamlink__streamlink-1311
[ "1290" ]
e71336f3729148c64b26511b2b41b22fa6d249c9
diff --git a/src/streamlink/plugins/showroom.py b/src/streamlink/plugins/showroom.py --- a/src/streamlink/plugins/showroom.py +++ b/src/streamlink/plugins/showroom.py @@ -3,16 +3,16 @@ from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate, useragents -from streamlink.stream import RTMPStream +from streamlink.stream import HLSStream, RTMPStream _url_re = re.compile(r'''^https?:// - (?:\w*.)? - showroom-live.com/ - (?: - (?P<room_title>[\w-]+$) - | - room/profile\?room_id=(?P<room_id>\d+)$ - ) + (?:\w*.)? + showroom-live.com/ + (?: + (?P<room_title>[\w-]+$) + | + room/profile\?room_id=(?P<room_id>\d+)$ + ) ''', re.VERBOSE) _room_id_re = re.compile(r'"roomId":(?P<room_id>\d+),') @@ -20,30 +20,35 @@ _room_id_lookup_failure_log = 'Failed to find room_id for {0} using {1} regex' _api_status_url = 'https://www.showroom-live.com/room/is_live?room_id={room_id}' -_api_data_url = 'https://www.showroom-live.com/room/get_live_data?room_id={room_id}' +_api_stream_url = 'https://www.showroom-live.com/api/live/streaming_url?room_id={room_id}' -_api_data_schema = validate.Schema( - { - "streaming_url_list_rtmp": validate.all([ +_api_stream_schema = validate.Schema( + validate.any({ + "streaming_url_list": validate.all([ { "url": validate.text, - "stream_name": validate.text, + validate.optional("stream_name"): validate.text, "id": int, "label": validate.text, - "is_default": int + "is_default": int, + "type": validate.text, + "quality": int, } - ]), - "is_live": int, - "room": { - "room_url_key": validate.text - }, - "telop": validate.any(None, validate.text) - } + ]) + }, + {} + ) ) + +# the "low latency" streams are rtmp, the others are hls _rtmp_quality_lookup = { "オリジナル画質": "high", + "オリジナル画質(低遅延)": "high", + "original spec(low latency)": "high", "original spec": "high", "低画質": "low", + "低画質(低遅延)": "low", + "low spec(low latency)": "low", "low spec": "low" } # changes here must also be updated in test_plugin_showroom @@ -95,15 +100,7 @@ def __init__(self, url): 'User-Agent': useragents.FIREFOX } self._room_id = None - self._info = None - self._title = None - - @property - def telop(self): - if self._info: - return self._info['telop'] - else: - return "" + self._stream_urls = None @property def room_id(self): @@ -111,10 +108,6 @@ def room_id(self): self._room_id = self._get_room_id() return self._room_id - def _get_stream_info(self, room_id): - res = http.get(_api_data_url.format(room_id=room_id), headers=self._headers) - return http.json(res, schema=_api_data_schema) - def _get_room_id(self): """ Locates unique identifier ("room_id") for the room. @@ -137,16 +130,9 @@ def _get_room_id(self): return # Raise exception? return match.group('room_id') - def _get_title(self): - if self._title is None: - if 'profile?room_id=' not in self.url: - self._title = self.url.rsplit('/', 1)[-1] - else: - if self._info is None: - # TODO: avoid this - self._info = self._get_stream_info(self.room_id) - self._title = self._info.get('room').get('room_url_key') - return self._title + def _get_stream_info(self, room_id): + res = http.get(_api_stream_url.format(room_id=room_id), headers=self._headers) + return http.json(res, schema=_api_stream_schema) def _get_rtmp_stream(self, stream_info): rtmp_url = '/'.join((stream_info['url'], stream_info['stream_name'])) @@ -156,14 +142,15 @@ def _get_rtmp_stream(self, stream_info): return quality, RTMPStream(self.session, params=params) def _get_streams(self): - self._info = self._get_stream_info(self.room_id) - if not self._info or not self._info['is_live']: + info = self._get_stream_info(self.room_id) + if not info: return - self.logger.debug("Getting streams for {0}".format(self._get_title())) - - for stream_info in self._info.get("streaming_url_list_rtmp", []): - yield self._get_rtmp_stream(stream_info) - + for stream_info in info.get("streaming_url_list", []): + if stream_info["type"] == "rtmp": + yield self._get_rtmp_stream(stream_info) + elif stream_info["type"] == "hls": + for s in HLSStream.parse_variant_playlist(self.session, stream_info["url"]).items(): + yield s __plugin__ = Showroom
showroom-live Unable to open URL ---- ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description Trying to use streamlink to open a showroom-live stream seems to fail due to 404, possibly due to site structure changes. ### Expected / Actual behavior Running `streamlink <room url>`, in the case that the given room is live, should probably open a stream or ask for a quality setting, but reports 404 instead. ### Reproduction steps / Explicit stream URLs to test 1. Find a live room from here: https://www.showroom-live.com/onlive 2. Enter `streamlink <room url>` ### Environment details Operating system and version: Win7x64 Streamlink and Python version: Streamlink 0.8.1, Prepackaged Python ### Comments, logs, screenshots, etc. `streamlink https://www.showroom-live.com/misaki0719` `[cli][info] Found matching plugin showroom for URL https://www.showroom-live.com/misaki0719` `error: Unable to open URL: https://www.showroom-live.com/room/get_live_data?room_id=144710` `(404 Client Error: Not Found for url: https://www.showroom-live.com/room/get_live_data?room_id=144710)`
This is due to an API change. The API location for room information is https://www.showroom-live.com/api/live/live_info?room_id={room_id} now. I don't know Python and rtmp well enough to fix this problem since the variable names have also changed. Example of new API output: {"age_verification_status":0,"video_type":0,"enquete_gift_num":0,"is_enquete":false,"bcsvr_port":8080,"live_type":0,"is_free_gift_only":false,"bcsvr_host":"online.showroom-live.com","live_id":0,"is_enquete_result":false,"live_status":1,"room_id":115516,"bcsvr_key":"","background_image_url":null} @wlerin Sorry to bother you. It seems you are the original author of this plugin so I wanted to let you know. Ah, I forgot to update this. The `live_info` endpoint does not contain the necessary information, and I haven't found any other API endpoint that does. However, the html of the room page (e.g. https://www.showroom-live.com/w1017 ) does, at least when the stream is live. I can submit a patch to get it from there instead, but really we need to find the new endpoint, if one exists. (The bcsvr information there is for a websocket connection, it's possible the stream info is pushed through that.) @Antares31415 I don't believe the variable names have changed, the ones we need just aren't there anymore. I have updated the showroom plugin on my fork here: https://github.com/wlerin/streamlink/blob/showroom/src/streamlink/plugins/showroom.py Basically all functionality besides getting a single streamable url is gone. I'll remove most of the comments before submitting a PR, but I need to see if I can figure out how to restore some of the other features first. there is an api for hls and rtmp urls @wlerin `https://www.showroom-live.com/api/live/streaming_url?room_id={room_id}` https://gist.github.com/back-to/a051c3e7bb450d323e4d1f07c1b1a6d6 here is a diff file, just the `is_live` is not fixed there ``` error: Unable to validate JSON: Key 'streaming_url_list' not found in {} ``` for offline streams and some other cleanups could be done. feel free to use it, if you want.
2017-11-07T02:55:42
streamlink/streamlink
1,317
streamlink__streamlink-1317
[ "1316" ]
e71336f3729148c64b26511b2b41b22fa6d249c9
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -1,10 +1,10 @@ #!/usr/bin/env python +import os from os import environ from os.path import abspath, dirname, join from setuptools import setup, find_packages from sys import version_info, path as sys_path -import warnings deps = [] @@ -47,7 +47,12 @@ deps.append("websocket-client") # Support for SOCKS proxies -deps.append("requests[socks]") +deps.append("PySocks!=1.5.7,>=1.5.6") # requests[socks] uses this version + +# win-inet-pton is missing a dependency in PySocks, this has been fixed but not released yet +if os.name == "nt" and version_info < (3, 0): + # Required due to missing socket.inet_ntop & socket.inet_pton method in Windows Python 2.x + deps.append("win-inet-pton") # When we build an egg for the Win32 bootstrap we don't want dependency # information built into it.
Streamlink 0.8.1 does not work with standalone python. I had been using Streamlink 0.7.0 for so long and thought it was time to update but if I do, Streamlink no longer works. When trying to launch streamlink gives out these errors. ``` Traceback (most recent call last): File "C:\Users\Jesus\AppData\Local\Programs\Python\Python36\Scripts\streamlink-script.py", line 6, in <module> from pkg_resources import load_entry_point File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 3017, in <module> @_call_aside File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 3003, in _call_aside f(*args, **kwargs) File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 3030, in _initialize_master_working_set working_set = WorkingSet._build_master() File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 659, in _build_master ws.require(__requires__) File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 967, in require needed = self.resolve(parse_requirements(requirements)) File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 853, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'PySocks!=1.5.7,>=1.5.6; extra == "socks"' distribution was not found and is required by requests ``` ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description Streamlink does not work after 0.8.1 update. ### Reproduction steps 1. Install python 3.6.3 x64 2. Install Streamlink via pip 3. Streamlink fails to launch ### Environment details Operating system and version: Windows 10 x64 v1709 build 16299.19 Streamlink and Python version: Streamlink v0.8.1 together with python x64 v3.6.3 or v3.6.2 (Have not tried any other versions) ### Log ``` PS C:\WINDOWS\system32> streamlink --version streamlink 0.7.0 PS C:\WINDOWS\system32> streamlink usage: streamlink [OPTIONS] <URL> [STREAM] Use -h/--help to see the available options or read the manual at https://streamlink.github.io PS C:\WINDOWS\system32> pip install --upgrade streamlink Collecting streamlink Using cached streamlink-0.8.1.tar.gz Requirement already up-to-date: requests!=2.12.0,!=2.12.1,!=2.16.0,!=2.16.1,!=2.16.2,!=2.16.3,!=2.16.4,!=2.16.5,!=2.17.1,<3.0,>=2.2 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from streamlink) Requirement already up-to-date: pycryptodome<4,>=3.4.3 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from streamlink) Requirement already up-to-date: iso-639 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from streamlink) Requirement already up-to-date: iso3166 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from streamlink) Requirement already up-to-date: websocket-client in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from streamlink) Requirement already up-to-date: urllib3<1.23,>=1.21.1 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from requests!=2.12.0,!=2.12.1,!=2.16.0,!=2.16.1,!=2.16.2,!=2.16.3,!=2.16.4,!=2.16.5,!=2.17.1,<3.0,>=2.2->streamlink) Requirement already up-to-date: chardet<3.1.0,>=3.0.2 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from requests!=2.12.0,!=2.12.1,!=2.16.0,!=2.16.1,!=2.16.2,!=2.16.3,!=2.16.4,!=2.16.5,!=2.17.1,<3.0,>=2.2->streamlink) Requirement already up-to-date: idna<2.7,>=2.5 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from requests!=2.12.0,!=2.12.1,!=2.16.0,!=2.16.1,!=2.16.2,!=2.16.3,!=2.16.4,!=2.16.5,!=2.17.1,<3.0,>=2.2->streamlink) Requirement already up-to-date: certifi>=2017.4.17 in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from requests!=2.12.0,!=2.12.1,!=2.16.0,!=2.16.1,!=2.16.2,!=2.16.3,!=2.16.4,!=2.16.5,!=2.17.1,<3.0,>=2.2->streamlink) Requirement already up-to-date: six in c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages (from websocket-client->streamlink) Installing collected packages: streamlink Found existing installation: streamlink 0.7.0 Uninstalling streamlink-0.7.0: Successfully uninstalled streamlink-0.7.0 Running setup.py install for streamlink ... done Successfully installed streamlink-0.8.1 PS C:\WINDOWS\system32> streamlink Traceback (most recent call last): File "C:\Users\Jesus\AppData\Local\Programs\Python\Python36\Scripts\streamlink-script.py", line 6, in <module> from pkg_resources import load_entry_point File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 3017, in <module> @_call_aside File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 3003, in _call_aside f(*args, **kwargs) File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 3030, in _initialize_master_working_set working_set = WorkingSet._build_master() File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 659, in _build_master ws.require(__requires__) File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 967, in require needed = self.resolve(parse_requirements(requirements)) File "c:\users\jesus\appdata\local\programs\python\python36\lib\site-packages\pkg_resources\__init__.py", line 853, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'PySocks!=1.5.7,>=1.5.6; extra == "socks"' distribution was not found and is required by requests ``` [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
This is a known issue, the easiest solution is to `pip install "PySocks!=1.5.7,>=1.5.6"`.
2017-11-07T16:57:44
streamlink/streamlink
1,351
streamlink__streamlink-1351
[ "1350" ]
6d1f9ded3bb293c8f9ad21a2d76301f64513b8d1
diff --git a/src/streamlink/plugins/kanal7.py b/src/streamlink/plugins/kanal7.py --- a/src/streamlink/plugins/kanal7.py +++ b/src/streamlink/plugins/kanal7.py @@ -11,7 +11,7 @@ class Kanal7(Plugin): url_re = re.compile(r"https?://(?:www.)?kanal7.com/canli-izle") iframe_re = re.compile(r'iframe .*?src="(http://[^"]*?)"') - stream_re = re.compile(r'src="(http[^"]*?)"') + stream_re = re.compile(r'''tp_file\s+=\s+['"](http[^"]*?)['"]''') @classmethod def can_handle_url(cls, url):
Kanal7 Defective again Only 2 months later they have changed the design. Not opening with latest 0.9.0 Release: [cli][info] Found matching plugin kanal7 for URL http://www.kanal7.com/canli-izle error: No playable streams found on this URL: http://www.kanal7.com/canli-izle
2017-12-01T10:41:35
streamlink/streamlink
1,359
streamlink__streamlink-1359
[ "1354" ]
8d51a3e341a37e0130e621db5b516627777ce4ef
diff --git a/src/streamlink/plugins/picarto.py b/src/streamlink/plugins/picarto.py --- a/src/streamlink/plugins/picarto.py +++ b/src/streamlink/plugins/picarto.py @@ -1,6 +1,7 @@ from __future__ import print_function import re +import json from streamlink.plugin import Plugin from streamlink.plugin.api import http @@ -9,50 +10,30 @@ class Picarto(Plugin): - API_CHANNEL_INFO = "https://picarto.tv/process/channel" + CHANNEL_API_URL = "https://api.picarto.tv/v1/channel/name/{channel}" + VIDEO_API_URL = "https://picarto.tv/process/channel" RTMP_URL = "rtmp://{server}:1935/play/" RTMP_PLAYPATH = "golive+{channel}?token={token}" HLS_URL = "https://{server}/hls/{channel}/index.m3u8?token={token}" + # Regex for all usable URLs _url_re = re.compile(r""" https?://(?:\w+\.)?picarto\.tv/(?:videopopout/)?([^&?/]+) """, re.VERBOSE) - # divs with tech_switch class - _tech_switch_re = re.compile(r""" - <div\s+class=".*?tech_switch.*?"(.*?)> - """, re.VERBOSE) - # placeStream(channel, playerID, product, offlineImage, online, token, tech) - _place_stream_re = re.compile(r""" - <script>\s*placeStream\s*\((.*?)\);?\s*</script> - """, re.VERBOSE) - # <source ...> - _source_re = re.compile(r'''source src="(http[^"]+)"''') + # Regex for VOD extraction + _vod_re = re.compile(r'''vod: "(https?://[\S]+?/index.m3u8)",''') @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None - @classmethod - def _stream_online(cls, page): - match = cls._place_stream_re.search(page.text) - if match: - return match.group(1).split(",")[4].strip() == "1" - return False - - @classmethod - def _get_steam_list(cls, page): - for match in cls._tech_switch_re.findall(page.text): - args = {} - for attr in match.strip().split(" "): - key, value = attr.split("=") - _, key = key.split("-") - args[key] = value.strip('"') - yield args - - def _create_hls_stream(self, server, args): + def _create_hls_stream(self, server, channel, token): streams = HLSStream.parse_variant_playlist(self.session, - self.HLS_URL.format(server=server, **args), + self.HLS_URL.format( + server=server, + channel=channel, + token=token), verify=False) if len(streams) > 1: self.logger.debug("Multiple HLS streams found") @@ -64,67 +45,68 @@ def _create_hls_stream(self, server, args): # one HLS streams, rename it to live return {"live": list(streams.values())[0]} - def _create_flash_stream(self, server, args): + def _create_flash_stream(self, server, channel, token): params = { "rtmp": self.RTMP_URL.format(server=server), - "playpath": self.RTMP_PLAYPATH.format(**args) + "playpath": self.RTMP_PLAYPATH.format(token=token, channel=channel) } return RTMPStream(self.session, params=params) def _get_vod_stream(self, page): - m = self._source_re.search(page.text) + m = self._vod_re.search(page.text) if m: return HLSStream.parse_variant_playlist(self.session, m.group(1)) def _get_streams(self): - page = http.get(self.url) + url_channel_name = self._url_re.match(self.url).group(1) - page_channel = self._url_re.match(self.url).group(1) - if page_channel.endswith(".flv"): + # Handle VODs first, since their "channel name" is different + if url_channel_name.endswith(".flv"): self.logger.debug("Possible VOD stream...") + page = http.get(self.url) vod_streams = self._get_vod_stream(page) if vod_streams: for s in vod_streams.items(): yield s return + else: + self.logger.warning("Probably a VOD stream but no VOD found?") + + ci = http.get(self.CHANNEL_API_URL.format(channel=url_channel_name), raise_for_status=False) - if "This channel does not exist" in page.text: - self.logger.error("The channel {0} does not exist".format(page_channel)) + if ci.status_code == 404: + self.logger.error("The channel {0} does not exist".format(url_channel_name)) return - if not self._stream_online(page): - self.logger.error("The channel {0} is currently offline".format(page_channel)) + channel_api_json = json.loads(ci.text) + + if channel_api_json["online"] != True: + self.logger.error("The channel {0} is currently offline".format(url_channel_name)) return server = None - streams = list(self._get_steam_list(page)) - multi = False - - for args in streams: - channel, tech, token = args["channel"], args["tech"], args["token"] - if channel.lower() != page_channel.lower(): - if not multi: - self.logger.info("Skipping multi-channel stream for: {0}".format(channel)) - multi = True - continue - - self.logger.debug("Found stream for {channel}; tech=\"{tech}\", token=\"{token}\"", **args) - - # cache the load balancing info - if not server: - channel_server_res = http.post(self.API_CHANNEL_INFO, data={"loadbalancinginfo": channel}) - server = channel_server_res.text - self.logger.debug("Using load balancing server {0} for channel {1}", - server, - channel) - - # generate all the streams, for multi-channel streams also append the channel name - if tech == "hls": - for s in self._create_hls_stream(server, args).items(): + token = "public" + channel = channel_api_json["name"] + + # Extract preferred edge server and available techs from the undocumented channel API + channel_server_res = http.post(self.VIDEO_API_URL, data={"loadbalancinginfo": channel}) + info_json = json.loads(channel_server_res.text) + pref = info_json["preferedEdge"] + for i in info_json["edges"]: + if i["id"] == pref: + server = i["ep"] + break + self.logger.debug("Using load balancing server {0} : {1} for channel {2}", + pref, + server, + channel) + + for i in info_json["techs"]: + if i["label"] == "HLS": + for s in self._create_hls_stream(server, channel, token).items(): yield s - - elif tech == "flash": - stream = self._create_flash_stream(server, args) + elif i["label"] == "RTMP Flash": + stream = self._create_flash_stream(server, channel, token) yield "live", stream
picarto.tv plugin broken *Thanks for reporting an issue!* *Please read the contribution guidelines first! (see the link above)* *Also check the list of known issues before reporting an issue!* *Feel free to use the following template. Be as detailed as possible.* *Please see the text preview to avoid unnecessary formatting errors.* *Don't forget to remove this text before submitting.* ---- ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description Picarto.tv plugin erroneously reports channel offline ### Expected / Actual behavior Command: streamlink https://picarto.tv/RedAxis best causes player to open, stream to start in it. Actually reports [plugin.picarto][error] The channel RedAxis is currently offline When channel physically online and can be viewed in browser. ### Reproduction steps / Explicit stream URLs to test 1. Try open any picarto.tv stream 2. Fail 3. Check that stream works in browser ### Environment details Operating system and version: Windows 7, OpenSUSE Tumbleweed Streamlink and Python version: streamlink-script.py 0.8.1 for windows, streamlink 0.9.0 for Linux, Python 3.6 ### Comments, logs, screenshots, etc. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
OK, I've been digging into this a bit. It seems like the changes are mostly to the html of the Picarto stream page, and the plugin uses some semi-fragile regexes to scrape that page. Should be fairly simple to fix. The only backend change I've noticed is the load balancer API page. It seems to now return json instead of just a url: `$ curl https://picarto.tv/process/channel -d loadbalancinginfo=twokinds` `{"edges":[{"label":"US East","id":"us-east1","ep":"edge5-us-east.picarto.tv"},{"label":"US West","id":"us-west1","ep":"edge5-us-east.picarto.tv"}],"preferedEdge":"us-east1","techs":[{"type":"application\/x-mpegurl","label":"HLS"},{"type":"video\/mp4","label":"MP4"},{"type":"rtmp\/mp4","label":"RTMP Flash"}]}` In watching the behavior of the web client, it seems like the token field is just "public", so the token extraction code can probably be removed. Did this token serve any purpose previously?
2017-12-05T23:53:22
streamlink/streamlink
1,365
streamlink__streamlink-1365
[ "1364" ]
f4ad8ebd37f9673a938050c4aecd5ace9286dd67
diff --git a/src/streamlink/plugins/huya.py b/src/streamlink/plugins/huya.py --- a/src/streamlink/plugins/huya.py +++ b/src/streamlink/plugins/huya.py @@ -1,11 +1,10 @@ import re -from requests.adapters import HTTPAdapter - from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate from streamlink.stream import HLSStream from streamlink.plugin.api import useragents +from streamlink.utils import update_scheme HUYA_URL = "http://m.huya.com/%s" @@ -13,17 +12,18 @@ _hls_re = re.compile(r'^\s*<video\s+id="html5player-video"\s+src="(?P<url>[^"]+)"', re.MULTILINE) _hls_schema = validate.Schema( - validate.all( - validate.transform(_hls_re.search), - validate.any( - None, - validate.all( - validate.get('url'), - validate.transform(str) - ) - ) + validate.all( + validate.transform(_hls_re.search), + validate.any( + None, + validate.all( + validate.get('url'), + validate.transform(str) ) ) + ) +) + class Huya(Plugin): @classmethod @@ -35,9 +35,10 @@ def _get_streams(self): channel = match.group("channel") http.headers.update({"User-Agent": useragents.IPAD}) - #Some problem with SSL on huya.com now, do not use https + # Some problem with SSL on huya.com now, do not use https hls_url = http.get(HUYA_URL % channel, schema=_hls_schema) - yield "live", HLSStream(self.session, hls_url) + yield "live", HLSStream(self.session, update_scheme("http://", hls_url)) + __plugin__ = Huya
catch a simple bug of handling url ### Checklist - [x] This is a bug report. ### Description catch a simple bug of returning url. ### Version streamlink 0.9.0 ### Unexpected behavior for example ```sh streamlink http://www.huya.com/1547946968 "best" ``` it reports: requests.exceptions.MissingSchema: Invalid URL '//ws.streamhls.huya.com/huyalive/30765679-2523417567-10837995924416888832-2789253832-10057-A-1512526581-1_1200/playlist.m3u8': No schema supplied. Perhaps you meant http:////ws.streamhls.huya.com/huyalive/30765679-2523417567-10837995924416888832-2789253832-10057-A-1512526581-1_1200/playlist.m3u8? ### Expected behavior but if you replace with the m3u8 url above, by **removing // header**, it will work. The equivalent successful example are as follows: ```sh streamlink ws.streamhls.huya.com/huyalive/30765679-2523417567-10837995924416888832-2789253832-10057-A-1512526581-1_1200/playlist.m3u8 "best" ```
2017-12-08T13:29:20
streamlink/streamlink
1,394
streamlink__streamlink-1394
[ "1102" ]
a139b858b4c9f4b70825c9da26b67b26c8c81b4a
diff --git a/src/streamlink/plugins/douyutv.py b/src/streamlink/plugins/douyutv.py --- a/src/streamlink/plugins/douyutv.py +++ b/src/streamlink/plugins/douyutv.py @@ -10,7 +10,7 @@ API_URL = "https://capi.douyucdn.cn/api/v1/{0}&auth={1}" VAPI_URL = "https://vmobile.douyu.com/video/getInfo?vid={0}" -API_SECRET = "Y237pxTx2In5ayGz" +API_SECRET = "zNzMV1y4EMxOHS6I5WKm" SHOW_STATUS_ONLINE = 1 SHOW_STATUS_OFFLINE = 2 STREAM_WEIGHTS = { @@ -129,10 +129,10 @@ def _get_streams(self): if channel is None: channel = http.get(self.url, schema=_room_id_alt_schema) - http.headers.update({'User-Agent': useragents.ANDROID}) + http.headers.update({'User-Agent': useragents.WINDOWS_PHONE_8}) cdns = ["ws", "tct", "ws2", "dl"] ts = int(time.time()) - suffix = "room/{0}?aid=androidhd1&cdn={1}&client_sys=android&time={2}".format(channel, cdns[0], ts) + suffix = "room/{0}?aid=wp&cdn={1}&client_sys=wp&time={2}".format(channel, cdns[0], ts) sign = hashlib.md5((suffix + API_SECRET).encode()).hexdigest() res = http.get(API_URL.format(suffix, sign))
July 17 Douyu.com error 0.7.0 streamlink https://www.douyu.com/17732 source -o "PATH & FILENAME" [cli][info] Found matching plugin douyutv for URL https://www.douyu.com/17732 error: Unable to open URL: https://www.douyu.com/lapi/live/getPlay/17732 (500 Server Error: Internal Server Error for url: https://www.douyu.com/lapi/live/getPlay/17732) @fozzysec @steven7851
There is no solution for the LAPI 500 error AFAIK. Douyu changed their flash player and their api again, waiting for a solution to it. @fozzysec I have several software on my computer, At present, only this one can be normal video I tried to catch the bag You see Do you look at these for your help? ------------------------- GET /api/v1/room/156277?aid=dytool2&time=1500284308&auth=8b972619bb9ae83d63dd175cf1e44c8e HTTP/1.1 Cache-Control: no-cache Connection: Keep-Alive Content-Type: application/x-www-form-urlencoded Accept: text/html, application/xhtml+xml, / Accept-Language: zh-cn User-Agent: Mozilla/5.0 (compatible; MSIE 11.0; Windows NT 6.1) Host: api.douyutv.com GET /live/156277raU8XQkRHx.flv?wsAuth=e04b9d008c40e5a68fdd02e0427a5d13&token=app-dytool2-0-156277-dafa16da92004488622f7dc918e03ed2&logo=0&expire=0 HTTP/1.1 Cache-Control: no-cache Connection: Keep-Alive Content-Type: application/x-www-form-urlencoded Accept: text/html, application/xhtml+xml, / Accept-Language: zh-cn User-Agent: Mozilla/5.0 (compatible; MSIE 11.0; Windows NT 6.1) Host: hdla.douyucdn.cn GET /hdla.douyucdn.cn/live/156277raU8XQkRHx.flv?wsAuth=e04b9d008c40e5a68fdd02e0427a5d13&token=app-dytool2-0-156277-dafa16da92004488622f7dc918e03ed2&logo=0&expire=0&wshc_tag=0&wsts_tag=596c85ce&wsid_tag=3a1240ec&wsiphost=ipdbm HTTP/1.1 Cache-Control: no-cache Connection: Keep-Alive Content-Type: application/x-www-form-urlencoded Accept: text/html, application/xhtml+xml, / Accept-Language: zh-cn User-Agent: Mozilla/5.0 (compatible; MSIE 11.0; Windows NT 6.1) Host: 221.194.180.100 @lki2019 I tried the API but it seems it doesn't work for me. ``` curl 'http://api.douyutv.com/api/v1/room/156277?aid=dytool2&time=1500284308&auth=8b972619bb9ae83d63dd175cf1e44c8e' -H 'User-Agent: Mozilla/5.0 (compatible; MSIE 11.0; Windows NT 6.1)' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: text/html, application/xhtml+xml, /' {"error":1003,"msg":"","data":[]} ``` I modified the time it doesn't work too. Would you please provide me with the app/software name so I can have a try on it. @fozzysec It is a need for a machine a code of software, you will crack it? If i can pass you, you get it verified Leave a mailbox, I sent you @lki2019 No, I don't know much about cracking, thanks for the help. https://github.com/spacemeowx2/DouyuHTML5Player/issues/28 @bupmc I only have Mac computers so I can't get dump decoded SWF ASCRIPT from memory while running the official flash player. I will keep on watch that issue and try to fix the plugin ASAP. Thanks. 感谢 According to https://github.com/spacemeowx2/DouyuHTML5Player/issues/28 , I wrote an simple script to redirect the HLS playlist, it can work temporarily but have lag. I don't know if I should add a simple http server to this project and generate HLS playlist dynamically to enable it can work with streamlink. ps. If someone want to stream douyu.com, just use http://open.douyucdn.cn/api/RoomApi/room/ROOMID to get the real roomid then use mpv to play playlist.m3u8?room=REALROOMID The code is here https://gist.github.com/fozzysec/b98e681c352b6e5b0c7503d99c942670 And can also be directly accessed via http://fozzy.co/douyu/playlist.m3u8 https://www.douyu.com/274874 Being broadcast live How do you enter the specific order? mpv http://fozzy.co/douyu/playlist.m3u8 274874 What about that? @lki2019 For those numerical room, just try ``` mpv "http://fozzy.co/douyu/playlist.m3u8?room=274874" ``` For those non-numerical room, for example https://www.douyu.com/nado, first visit http://open.douyucdn.cn/api/RoomApi/room/nado to get the room id, then ``` mpv "http://fozzy.co/douyu/playlist.m3u8?room=2020877" ``` For those special room whose format is `/t/roomid`, in html source find `onlineid` and get the room id. OK,谢谢! ![qq 20170720141000](https://user-images.githubusercontent.com/30022431/28403004-53245956-6d55-11e7-9e20-860e0f81f19d.png) Can play, but will be from time to time about the card, I watched for 2 minutes, the player did not automatically, and broke @lki2019 If there are broken frames, just try add `--autosync=30` to mpv, it will smooth the audio/video matching. It is very strange that douyu's WAF may block frequent request. Maybe a local http server is needed. ``` [root@freebsd ~/www/douyu]# ./playlist2.m3u8 1047629 Content-Type: application/x-mpegURL; charset=ISO-8859-1 [root@freebsd ~/www/douyu]# curl "https://m.douyu.com/html5/live?roomId=1047629" {"error":0,"data":{"hls_url":"http:\/\/hls3.douyucdn.cn\/live\/1047629rbtEPD0T0\/playlist.m3u8?wsSecret=09368623d3b82dcc83e01cf6d101dc05&wsTime=1500529944&did=&ver="}}[root@freebsd ~/www/douyu]# [root@freebsd ~/www/douyu]# curl "http://hls3.douyucdn.cn/live/1047629rbtEPD0T0/playlist.m3u8?wsSecret=09368623d3b82dcc83e01cf6d101dc05&wsTime=1500529944&did=&ver=" [root@freebsd ~/www/douyu]# ``` ![zuiixinde](https://user-images.githubusercontent.com/30022431/28404234-13568dd4-6d5b-11e7-87d7-7048eab05192.png) mpv --autosync=30 "http://fozzy.co/douyu/playlist.m3u8?room=274874" I watched more than 7 minutes without disconnected! Audio/Video desynchronisation detected! Possible reasons include too slow hardware, temporary CPU spikes, broken drivers, and broken files. Audio position will not match to the video (see A-V status field). Card a bit [ffmpeg/demuxer] hls,applehttp: Failed to reload playlist 0 Card a bit @lki2019 Yes, a local http server may reduce lag, my server is located in Tokyo so it may be a bit slow when mpv fetching the playlist. Thank you Read more than 15 minutes, did not break! feel good Is it possible to record? @lki2019 ``` ffmpeg -i "http://fozzy.co/douyu/playlist.m3u8?room=xxx" -acodec copy -vcodec copy -bsf:a aac_adtstoasc douyu.flv ``` Also has async problems. If you really want to download, just download all the sequenced TS files and combine all those files together. mpv can also record streams by ``` mpv --autosync=30 "http://fozzy.co/douyu/playlist.m3u8?room=xxx" -o file1.flv ``` frame=13935 fps= 40 q=-1.0 size= 76390kB time=00:05:50.92 bitrate=1783.3kbits/ [http @ 047beae0] No trailing CRLF found in HTTP header. frame=14056 fps= 41 q=-1.0 size= 77085kB time=00:05:54.03 bitrate=1783.7kbits/ [hls,applehttp @ 00397a00] Failed to reload playlist 0 [http @ 047beae0] No trailing CRLF found in HTTP header. http://fozzy.co/douyu/playlist.m3u8?room=274874: Unknown error frame=14175 fps= 40 q=-1.0 size= 77723kB time=00:05:57.00 bitrate=1783.5kbits/ frame=14175 fps= 40 q=-1.0 Lsize= 77732kB time=00:05:57.00 bitrate=1783.7kbits /s video:71487kB audio:5712kB subtitle:0kB other streams:0kB global headers:0kB mux ing overhead: 0.689756% G:\tools\tools> Recorded more than five minutes to disconnect @lki2019 This is network error, a local http server will be better. The remote server is not stable. Or someone can place this redirect script on cloud within Mainland China such as Aliyun or something else. https://gist.github.com/fozzysec/af4b6c2a4d95e3bb84cbb8462f2ec709 I edited the code to make a local simple http server, this is much more smooth than the previous script. just use ``` mpv --autosync=30 "http://localhost:8181/playlist.m3u8?room=xxx" ``` You can also change the port in the code. I am the network, you can use it? ![qq 20170720163533](https://user-images.githubusercontent.com/30022431/28408312-a09f564a-6d69-11e7-9b01-15bb87588887.png) I was WIN7 32-bit system How can i do it? I've copied your code What should I do next? ![1a00](https://user-images.githubusercontent.com/30022431/28408503-4d0668e2-6d6a-11e7-92b5-aba05a37e535.jpg) @lki2019 First you need to install the perl environment, for windows system, ActivePerl is easy to use. After installing perl, you need to install those CPAN packages: ``` JSON LWP::UserAgent CGI HTTP::Server::Simple ``` After get everything installed, you can just start the server by `perl douyu_server.pl`, then access http://localhost:8181/ , you will see a simple page to input the douyu room id, input the room id and it will give you an link, copy that link and just use mpv to play it ;D The douyu support cannot be implemented by plugin so you can temporarily use this for streaming. **Chinese translation** 首先需要安装perl执行环境,windows系统可以安装ActivePerl,装好了之后需要安装以下Perl包: ``` JSON LWP::UserAgent CGI HTTP::Server::Simple ``` 都装好了之后直接在命令行运行`perl douyu_server.pl`,然后访问http://localhost:8181/,会看到一个输入房间号的输入框,输入后回车会返回mpv可以直接播放的地址,直接用mpv播放即可。 目前斗鱼的支持做不进插件里面 OK,谢谢! D:\下载\Http_File_Server_2.3i_297\Http File Server 2.3i Build 297>perl douyu_ser ver.pl Unrecognized character \xA3; marked by <-- HERE after <-- HERE near column 1 at douyu_server.pl line 1. @lki2019 Don't paste use Notepad, directly download the code from https://raw.githubusercontent.com/fozzysec/DouyuHLS/master/douyu_server.pl P.S. Editing with Notepad on Windows is always a bad idea for nearly every script language, when you need to edit scripts, you can choose [Atom](https://github.com/atom/atom), GVim, notepad++ or some else you like, but not Notepad that come with Microsoft Windows, it will add BOM header to non-ascii file. D:\下载\Http_File_Server_2.3i_297\Http File Server 2.3i Build 297>perl douyu_ser ver.pl Can't locate HTTP/Server/Simple/CGI.pm in @INC (you may need to install the HTTP ::Server::Simple::CGI module) (@INC contains: C:/Perl/site/lib C:/Perl/lib .) at douyu_server.pl line 13. BEGIN failed--compilation aborted at douyu_server.pl line 13. D:\下载\Http_File_Server_2.3i_297\Http File Server 2.3i Build 297> ![qq 20170720200605](https://user-images.githubusercontent.com/30022431/28416549-0b9d4f02-6d87-11e7-9b95-5ae1a6e995f6.png) @lki2019 According to https://code.activestate.com/ppm/HTTP-Server-Simple/ , just open your cmd and run ``` ppm install HTTP-Server-Simple ppm install JSON ppm install LWP-UserAgent ppm install CGI ``` It should work according to the activeperl's website. ![11](https://user-images.githubusercontent.com/30022431/28417448-bd72242a-6d8a-11e7-965b-babbb7108e52.png) very good 谢谢!!!!! ![qq 20170720203330](https://user-images.githubusercontent.com/30022431/28417498-edf7b646-6d8a-11e7-8f1f-86c3e3bf247b.png) Can I add a feature? Click on the link automatically call, mpv player out! Harder? @lki2019 Not hard, but need to install url scheme to register in Windows, also enabling url scheme need to allow chrome to install developer extensions, it is annoying(Everytime you start Chrome, there is a alert that saying you are enabling developer mode). So just copy the link and paste it to mpv is the simplest way to play it. If you do need extension, you can reference https://github.com/fozzysec/streamlink-chrome-extension-for-windows this, only few modification are needed to make it work with mpv. Okay thank you! are you just replacing the **_550** from the **.ts** file with your server? if so, you could do this with streamlink based on https://github.com/beardypig/streamlink/blob/yoursportsinhd/src/streamlink/plugins/yoursportsinhd.py --- Here is a test plugin where the **_550** gets removed from the **.ts** file ``` streamlink http://exampledouyu.com/ID best ``` https://gist.github.com/back-to/9cec89ecc9c1fb7556523a8658391375 I don't know if this works, **douyu.com** is to laggy for my location. @back-to It works fine, very thanks. The only problem is that it will reconnect every 5 mins because of ```hls_url``` key expired. @back-to The problem now is that the original m3u8 playlist has an one-time token. When playing by player, the further request on the playlist will result in 403 error. We need a background script to provide the playlist that works with player. ok so you need to reload the m3u8 aswell, here is a new version of the test plugin it - reloads every **60 sec** the **playlist.m3u8** and replace it - replace **_550** from **.ts** link the **_550** link did not timeout for me, the link without **_550** did not timeout, but it's very laggy for me. --- ``` streamlink http://exampledouyu.com/ID best ``` https://gist.github.com/back-to/9cec89ecc9c1fb7556523a8658391375 Found a new API from https://github.com/spacemeowx2/DouyuHTML5Player/issues/28, I will open a PR later. @back-to Thanks for your code this can be an alternative way when Douyu block the new API. A fix(#1109) was done by using new API, you can just download the file and replace your douyutv.py, now only HD is supported.
2017-12-28T19:23:10
streamlink/streamlink
1,418
streamlink__streamlink-1418
[ "1187" ]
aa45712ee9919cd21dac758450ca06a0742bb2e4
diff --git a/src/streamlink/plugins/vaughnlive.py b/src/streamlink/plugins/vaughnlive.py --- a/src/streamlink/plugins/vaughnlive.py +++ b/src/streamlink/plugins/vaughnlive.py @@ -34,16 +34,17 @@ def recv(self): class VaughnLive(Plugin): - api_re = re.compile(r'new sApi\("(#(vl|igb|btv|pt|vtv)-[^"]+)",') servers = ["wss://sapi-ws-{0}x{1:02}.vaughnlive.tv".format(x, y) for x, y in itertools.product(range(1, 3), range(1, 6))] origin = "https://vaughnlive.tv" rtmp_server_map = { - "594140c69edad": "198.255.17.18", - "585c4cab1bef1": "198.255.17.26", - "5940d648b3929": "198.255.17.34", - "5941854b39bc4": "198.255.17.66"} + "594140c69edad": "66.90.93.42", + "585c4cab1bef1": "66.90.93.34", + "5940d648b3929": "66.90.93.42", + "5941854b39bc4": "198.255.0.10" + } name_remap = {"#vl": "live", "#btv": "btv", "#pt": "pt", "#igb": "instagib", "#vtv": "vtv"} + domain_map = {"vaughnlive": "#vl", "breakers": "#btv", "instagib": "#igb", "vapers": "#vtv", "pearltime": "#pt"} @classmethod def can_handle_url(cls, url): @@ -88,12 +89,11 @@ def _get_rtmp_streams(self, server, domain, channel, token): }) def _get_streams(self): - res = http.get(self.url, headers={"User-Agent": useragents.CHROME}) + m = _url_re.match(self.url) + if m: + stream_name = "{0}-{1}".format(self.domain_map[(m.group("domain").lower())], + m.group("channel")) - m = self.api_re.search(res.text) - stream_name = m and m.group(1) - - if stream_name: is_live, server, domain, channel, token, ingest = self._get_info(stream_name) if not is_live:
vaughnlive plugin not working.. ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Vaughnlive streams are not working ### Expected / Actual behavior ... ### Reproduction steps / Explicit stream URLs to test seems to be a replica of the closed issue https://github.com/streamlink/streamlink/issues/1034 Every stream just comes back with "error: No playable streams found" ### Environment details Operating system and version: Windows 10 x64 Streamlink and Python version: 0.7.0 ( and the latest dev buld from https://dl.bintray.com/streamlink/streamlink-nightly/ ) ### Comments, logs, screenshots, etc. This is happening even on the latest night/dev build Doing "-l debug" doesn't seem to produce anything at all either, just throws the same error: no playable streams found even though the streams are working just fine in browser.. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
@JourneyOver which channel? I tested a few and they still work for me ... I tested about 5-10 of them, all in the misc section, but as you say they are working now..so idk what was going on with vaughnlive when I was trying to watch something earlier.. @beardypig I'm waiting for the 500th change where you get tired of updating it (especially considering a lot of it is stolen content).. Closing since we can't duplicate. Seems changes have been made to the site today. The plugin was working this morning but all of a sudden I'm getting "No playable streams found" on all channels. Should I open a new issue? @fadster No let's just open this one back up, there are already 25 vaughnlive issues... I get the "No playable streams found" after successfully opening and playing two or three times. Could be that Vaughnlive is doing some kind of rate limiting now to potentially try to keep people from downloading multiple streams at once which has the side effect of prohibiting Streamlink users? I tracked down the problem to the `http.get()` call used to get the stream name in `_get_streams()`. By hardcoding the stream name instead of parsing the result of that call, I got it to work. It appears the recent changes to the site simply broke that part of the code so the fix should be trivial. I suspect some requests may have been hitting the old version of the site's code cached on Cloudflare's servers, which would explain why the plugin was still working on a couple occasions today. Either that or the site is currently in a state of flux. this the the problem now... streamlink -p "mpv --title=FUJI --mute --screen=1 --geometry=400x225-0+770" http://www.vaughnlive.tv/sherming5 best [cli][info] Found matching plugin vaughnlive for URL http://www.vaughnlive.tv/sherming5 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (rtmp) [cli][error] Try 1/1: Could not open stream <RTMPStream({'playpath': 'live_sherming5', 'pageUrl': 'http://www.vaughnlive.tv/sherming5', 'live': True, 'rtmp': 'rtmp://198.255.17.18/live?xKI2Dbx2rCpwXztBIhEENEmys4WgqqFZ', 'flv': '-'}, redirect=False> (No data returned from stream) error: Could not open stream <RTMPStream({'playpath': 'live_sherming5', 'pageUrl': 'http://www.vaughnlive.tv/sherming5', 'live': True, 'rtmp': 'rtmp://198.255.17.18/live?xKI2Dbx2rCpwXztBIhEENEmys4WgqqFZ', 'flv': '-'}, redirect=False>, tried 1 times, exiting [cli][info] Closing currently open stream... @c769214 I assume you hardcoded the channel's name to get this message, otherwise you would've gotten the "No playable streams found" error. If so, all you need to do is retry the command until it plays. It's just timing out a lot at the moment. I took a closer look at the result of that broken `http.get()` call. The site now detects the request as coming from a bot and returns a captcha challenge instead of the channel's page. It uses Distil scrape protection and spoofing the user agent isn't enough to circumvent it. Perhaps we could use something like this: https://github.com/Anorov/cloudflare-scrape However, according to that module's description, it won't work with captcha challenges. Alternatively, since we only need this request to determine the channel's internal name (ie. with the `#vl-` prefix), we could eliminate it altogether and just derive the name from the channel's URL: ```python stream_name = "#vl-" + re.search('//.*/(.+?)$', self.url).group(1) ``` Supporting all the subdomains (`#btv`, `#igb`, etc.) would involve some trial and error until the correct name is determined as this obviously only works for `#vl`. Thanks to this link and youtube tutorial: https://www.youtube.com/watch?v=oNR5xKstlgY posted in this thread 11 days ago: https://github.com/streamlink/streamlink/issues/1034 I managed to get streamlink working again, this is example command which I'm using atm: streamlink --http-header "Referer=https://vaughnlive.tv/unccharlie2" "hls://https://hls-ord-1a.vaughnsoft.net/nyc/live/live_unccharlie2/chunklist.m3u8" worst I hope this will give you extra information needed to solve this problem :\ It might be reasonable, as @fadster suggests, to use the channel name from the URL and have a mapping from domain to channel id prefix. That coudflare scraper is interesting, but it does execute JavaScript to get the tokens which makes me a be wary...
2018-01-08T13:44:41
streamlink/streamlink
1,486
streamlink__streamlink-1486
[ "643", "643" ]
db9f6640df5bf2cdb8d2acdf2960fe1fc96acfec
diff --git a/src/streamlink/plugins/ruv.py b/src/streamlink/plugins/ruv.py --- a/src/streamlink/plugins/ruv.py +++ b/src/streamlink/plugins/ruv.py @@ -3,40 +3,34 @@ import re from streamlink.plugin import Plugin -from streamlink.stream import RTMPStream, HLSStream +from streamlink.stream import HLSStream from streamlink.plugin.api import http +from streamlink.plugin.api import validate -RTMP_LIVE_URL = "rtmp://ruv{0}livefs.fplive.net/ruv{0}live-live/stream{1}" -RTMP_SARPURINN_URL = "rtmp://sipvodfs.fplive.net/sipvod/{0}/{1}{2}.{3}" - -HLS_RUV_LIVE_URL = "http://ruvruv-live.hls.adaptive.level3.net/ruv/ruv/index/stream{0}.m3u8" -HLS_RADIO_LIVE_URL = "http://sip-live.hds.adaptive.level3.net/hls-live/ruv-{0}/_definst_/live/stream1.m3u8" -HLS_SARPURINN_URL = "http://sip-ruv-vod.dcp.adaptive.level3.net/{0}/{1}{2}.{3}.m3u8" +# URL to the RUV LIVE API +RUV_LIVE_API = """http://www.ruv.is/sites/all/themes/at_ruv/scripts/\ +ruv-stream.php?channel={0}&format=json""" _live_url_re = re.compile(r"""^(?:https?://)?(?:www\.)?ruv\.is/ - (?P<channel_path> - ruv| - ras1| - ras-1| - ras2| - ras-2| - rondo + (?P<stream_id> + ruv/?$| + ruv2/?$| + ruv-2/?$| + ras1/?$| + ras2/?$| + rondo/?$ ) /? """, re.VERBOSE) -_sarpurinn_url_re = re.compile(r"""^(?:https?://)?(?:www\.)?ruv\.is/sarpurinn/ - (?: +_sarpurinn_url_re = re.compile(r"""^(?:https?://)?(?:www\.)?ruv\.is/spila/ + (?P<stream_id> ruv| ruv2| ruv-2| ruv-aukaras| - ras1| - ras-1| - ras2| - ras-2 ) / [a-zA-Z0-9_-]+ @@ -45,37 +39,26 @@ /? """, re.VERBOSE) -_rtmp_url_re = re.compile(r"""rtmp://sipvodfs\.fplive.net/sipvod/ - (?P<status> - lokad| - opid - ) - / - (?P<date>[0-9]+/[0-9][0-9]/[0-9][0-9]/)? - (?P<id>[A-Z0-9\$_]+) - \. - (?P<ext> - mp4| - mp3 - )""", re.VERBOSE) - -_id_map = { - "ruv": "ruv", - "ras1": "ras1", - "ras-1": "ras1", - "ras2": "ras2", - "ras-2": "ras2", - "rondo": "ras3" -} +_single_re = re.compile(r"""(?P<url>http://[0-9a-zA-Z\-\.]*/ + (lokad|opid) + / + ([0-9]+/[0-9][0-9]/[0-9][0-9]/)? + ([A-Z0-9\$_]+\.mp4\.m3u8) + ) + """, re.VERBOSE) + +_multi_re = re.compile(r"""(?P<base_url>http://[0-9a-zA-Z\-\.]*/ + (lokad|opid) + /) + manifest.m3u8\?tlm=hls&streams= + (?P<streams>[0-9a-zA-Z\/\.\,:]+) + """, re.VERBOSE) class Ruv(Plugin): @classmethod def can_handle_url(cls, url): - if _live_url_re.match(url): - return _live_url_re.match(url) - else: - return _sarpurinn_url_re.match(url) + return _live_url_re.match(url) or _sarpurinn_url_re.match(url) def __init__(self, url): Plugin.__init__(self, url) @@ -83,75 +66,77 @@ def __init__(self, url): if live_match: self.live = True - self.channel_path = live_match.group("channel_path") + self.stream_id = live_match.group("stream_id") + + # Remove slashes + self.stream_id.replace("/", "") + + # Remove dashes + self.stream_id.replace("-", "") + + # Rondo is identified as ras3 + if self.stream_id == "rondo": + self.stream_id = "ras3" else: self.live = False def _get_live_streams(self): - stream_id = _id_map[self.channel_path] + # Get JSON API + res = http.get(RUV_LIVE_API.format(self.stream_id)) - if stream_id == "ruv": - qualities_rtmp = ["720p", "480p", "360p", "240p"] - - for i, quality in enumerate(qualities_rtmp): - yield quality, RTMPStream( - self.session, - { - "rtmp": RTMP_LIVE_URL.format(stream_id, i + 1), - "pageUrl": self.url, - "live": True - } - ) + # Parse the JSON API + json_res = http.json(res) - qualities_hls = ["240p", "360p", "480p", "720p"] - for i, quality_hls in enumerate(qualities_hls): - yield quality_hls, HLSStream( - self.session, - HLS_RUV_LIVE_URL.format(i + 1) - ) + for url in json_res["result"]: + if url.startswith("rtmp:"): + continue - else: - yield "audio", RTMPStream(self.session, { - "rtmp": RTMP_LIVE_URL.format(stream_id, 1), - "pageUrl": self.url, - "live": True - }) + # Get available streams + streams = HLSStream.parse_variant_playlist(self.session, url) - yield "audio", HLSStream( - self.session, - HLS_RADIO_LIVE_URL.format(stream_id) - ) + for quality, hls in streams.items(): + yield quality, hls def _get_sarpurinn_streams(self): - res = http.get(self.url) - match = _rtmp_url_re.search(res.text) - - if not match: - yield - - token = match.group("id") - status = match.group("status") - extension = match.group("ext") - date = match.group("date") - if not date: - date = "" + # Get HTML page + res = http.get(self.url).text + lines = "\n".join([l for l in res.split("\n") if "video.src" in l]) + multi_stream_match = _multi_re.search(lines) + + if multi_stream_match and multi_stream_match.group("streams"): + base_url = multi_stream_match.group("base_url") + streams = multi_stream_match.group("streams").split(",") + + for stream in streams: + if stream.count(":") != 1: + continue + + [token, quality] = stream.split(":") + quality = int(quality) + key = "" + + if quality <= 500: + key = "240p" + elif quality <= 800: + key = "360p" + elif quality <= 1200: + key = "480p" + elif quality <= 2400: + key = "720p" + else: + key = "1080p" + + yield key, HLSStream( + self.session, + base_url + token + ) - if extension == "mp3": - key = "audio" else: - key = "576p" - - # HLS on Sarpurinn is currently only available on videos - yield key, HLSStream( - self.session, - HLS_SARPURINN_URL.format(status, date, token, extension) - ) - - yield key, RTMPStream(self.session, { - "rtmp": RTMP_SARPURINN_URL.format(status, date, token, extension), - "pageUrl": self.url, - "live": True - }) + single_stream_match = _single_re.search(lines) + + if single_stream_match: + url = single_stream_match.group("url") + yield "576p", HLSStream(self.session, url) def _get_streams(self): if self.live:
diff --git a/tests/test_plugin_ruv.py b/tests/test_plugin_ruv.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_ruv.py @@ -0,0 +1,28 @@ +import unittest + +from streamlink.plugins.ruv import Ruv + + +class TestPluginRuv(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Ruv.can_handle_url("ruv.is/ruv")) + self.assertTrue(Ruv.can_handle_url("http://ruv.is/ruv")) + self.assertTrue(Ruv.can_handle_url("http://ruv.is/ruv/")) + self.assertTrue(Ruv.can_handle_url("https://ruv.is/ruv/")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/ruv")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/ruv/")) + self.assertTrue(Ruv.can_handle_url("ruv.is/ruv2")) + self.assertTrue(Ruv.can_handle_url("ruv.is/ras1")) + self.assertTrue(Ruv.can_handle_url("ruv.is/ras2")) + self.assertTrue(Ruv.can_handle_url("ruv.is/rondo")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/spila/ruv/ol-2018-ishokki-karla/20180217")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/spila/ruv/frettir/20180217")) + + # shouldn't match + self.assertFalse(Ruv.can_handle_url("rruv.is/ruv")) + self.assertFalse(Ruv.can_handle_url("ruv.is/ruvnew")) + self.assertFalse(Ruv.can_handle_url("https://www.bloomberg.com/live/")) + self.assertFalse(Ruv.can_handle_url("https://www.bloomberg.com/politics/articles/2017-04-17/french-race-up-for-grabs-days-before-voters-cast-first-ballots")) + self.assertFalse(Ruv.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(Ruv.can_handle_url("http://www.youtube.com/"))
RUV Iceland : plugin partially outdated ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description RUV is Icelandic broadcasting corporation consisting of 3 radio and TV channels : 1. Radio channels ------------------ - RAS 1 : `http://ruv.is/nolayout/popup/ras1` - RAS 2 : `http://ruv.is/nolayout/popup/ras2` - Rondo : `http://ruv.is/nolayout/popup/rondo` 2. TV ----- - RUV : `http://ruv.is/ruv` - RUV 2 : `http://ruv.is/ruv-2` - Krakkaruv : `http://krakkaruv.is/hlusta/spila` ### Expected / Actual behavior Channels use HLS for broacasting. In the past they used rtmp too, not sure if it's still the case. ### Reproduction steps / Stream URLs to test Radio ------ `streamlink -l debug "http://ruv.is/nolayout/popup/ras1" error: No plugin can handle URL: http://ruv.is/nolayout/popup/ras1` TV --- ``` streamlink -l debug --http-proxy "82.221.48.137:8080" "http://ruv.is/ruv" best [cli][info] Found matching plugin ruv for URL http://ruv.is/ruv [cli][info] Available streams: 720p_hls, 480p_hls, 240p_hls, 360p_hls, 240p (wor st), 360p, 480p, 720p (best) [cli][info] Opening stream: 720p (rtmp) [stream.rtmp][debug] Spawning command: C:\Users\Ddr\Downloads\streamlink\\rtmpdu mp\rtmpdump.exe --flv - --live --pageUrl http://ruv.is/ruv --rtmp rtmp://ruvruvl ivefs.fplive.net/ruvruvlive-live/stream1 [cli][error] Could not open stream: Error while executing subprocess ``` ### Environment details (operating system, python version, etc.) W7 PRO/streamlink portable ### Comments, logs, screenshots, etc. TV channels are geolocked unlike radio. RUV Iceland : plugin partially outdated ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description RUV is Icelandic broadcasting corporation consisting of 3 radio and TV channels : 1. Radio channels ------------------ - RAS 1 : `http://ruv.is/nolayout/popup/ras1` - RAS 2 : `http://ruv.is/nolayout/popup/ras2` - Rondo : `http://ruv.is/nolayout/popup/rondo` 2. TV ----- - RUV : `http://ruv.is/ruv` - RUV 2 : `http://ruv.is/ruv-2` - Krakkaruv : `http://krakkaruv.is/hlusta/spila` ### Expected / Actual behavior Channels use HLS for broacasting. In the past they used rtmp too, not sure if it's still the case. ### Reproduction steps / Stream URLs to test Radio ------ `streamlink -l debug "http://ruv.is/nolayout/popup/ras1" error: No plugin can handle URL: http://ruv.is/nolayout/popup/ras1` TV --- ``` streamlink -l debug --http-proxy "82.221.48.137:8080" "http://ruv.is/ruv" best [cli][info] Found matching plugin ruv for URL http://ruv.is/ruv [cli][info] Available streams: 720p_hls, 480p_hls, 240p_hls, 360p_hls, 240p (wor st), 360p, 480p, 720p (best) [cli][info] Opening stream: 720p (rtmp) [stream.rtmp][debug] Spawning command: C:\Users\Ddr\Downloads\streamlink\\rtmpdu mp\rtmpdump.exe --flv - --live --pageUrl http://ruv.is/ruv --rtmp rtmp://ruvruvl ivefs.fplive.net/ruvruvlive-live/stream1 [cli][error] Could not open stream: Error while executing subprocess ``` ### Environment details (operating system, python version, etc.) W7 PRO/streamlink portable ### Comments, logs, screenshots, etc. TV channels are geolocked unlike radio.
2018-02-17T02:09:27
streamlink/streamlink
1,511
streamlink__streamlink-1511
[ "1481" ]
3b7dae75d924caa94d5d2e023b85959f0ac8ef39
diff --git a/src/streamlink/plugins/kanal7.py b/src/streamlink/plugins/kanal7.py --- a/src/streamlink/plugins/kanal7.py +++ b/src/streamlink/plugins/kanal7.py @@ -6,12 +6,13 @@ from streamlink.plugin.api import useragents from streamlink.plugin.api import validate from streamlink.stream import HLSStream +from streamlink.utils import update_scheme class Kanal7(Plugin): url_re = re.compile(r"https?://(?:www.)?kanal7.com/canli-izle") - iframe_re = re.compile(r'iframe .*?src="(http://[^"]*?)"') - stream_re = re.compile(r'''tp_file\s+=\s+['"](http[^"]*?)['"]''') + iframe_re = re.compile(r'iframe .*?src="((?:http:)?//[^"]*?)"') + stream_re = re.compile(r'''video-source\s*=\s*['"](http[^"']*?)['"]''') @classmethod def can_handle_url(cls, url): @@ -23,6 +24,7 @@ def find_iframe(self, url): iframe = self.iframe_re.search(res.text) iframe_url = iframe and iframe.group(1) if iframe_url: + iframe_url = update_scheme(self.url, iframe_url) self.logger.debug("Found iframe: {}", iframe_url) return iframe_url
Kanal 7 does not show ## **Checklist** - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ## **Description** i cant see anything at kanal 7.com . i have test it with this links but i became black screen ## **Reproduction steps / Explicit stream URLs to test** #SERVICE 5002:0:1:1DE6:C544:7E:460000:0:0:0:http%3a//127.0.0.1%3a8088/https%3a//new.10gbps.tv%3a443/live/kanal7LiveDesktop/index.m3u8 #DESCRIPTION KANAL 7 #SERVICE 5002:0:1:1DE6:C544:7E:460000:0:0:0:http%3a//127.0.0.1%3a8088/http%3a//www.kanal7.com/canli-izle #DESCRIPTION KANAL 7 #SERVICE 5002:0:1:1DE6:C544:7E:460000:0:0:0:http%3a//127.0.0.1%3a8088/http%3a//www.izle7.com/canli-yayin-frame?air=1 #DESCRIPTION KANAL 7
its not fixed! I have tested it with #SERVICE 5002:0:1:1DE6:C544:7E:460000:0:0:0:http%3a//127.0.0.1%3a8088/http%3a//www.kanal7.com/canli-izle #DESCRIPTION KANAL 7 @dreamboxco What would make you think that it is fixed? No one has worked on it in any way, shape, or form. If someone wants to work on it they will, there is no reason to spam the issue. in the synopsis it stands as a functioning plugins then out so if it does not work @dreamboxco I understand that and that's why the issue was created, but adding additional comments to the issue when no one has even looked at or worked on the issue does nothing. If someone decides to work on it they will, if not they won't. This is an open source project and people are spending their free time (unpaid) to contribute so you'll need to be patient and have some empathy for the team and what they choose to work on. its a streamlink plugin which not work look here https://streamlink.github.io/plugin_matrix.html kanal7 | kanal7.com | Yes | No |   -- | -- | -- | -- | -- here kanal 7 link http://www.izle7.com/canli-yayin-frame?air=1
2018-02-27T09:44:49
streamlink/streamlink
1,513
streamlink__streamlink-1513
[ "1495" ]
3b7dae75d924caa94d5d2e023b85959f0ac8ef39
diff --git a/src/streamlink/plugins/foxtr.py b/src/streamlink/plugins/foxtr.py --- a/src/streamlink/plugins/foxtr.py +++ b/src/streamlink/plugins/foxtr.py @@ -12,7 +12,7 @@ class FoxTR(Plugin): Support for Turkish Fox live stream: http://www.fox.com.tr/canli-yayin """ url_re = re.compile(r"https?://www.fox.com.tr/canli-yayin") - playervars_re = re.compile(r"desktop\s*:\s*\[\s*\{\s*src\s*:\s*'(.*?)'", re.DOTALL) + playervars_re = re.compile(r"source\s*:\s*\[\s*\{\s*videoSrc\s*:\s*'(.*?)'", re.DOTALL) @classmethod def can_handle_url(cls, url):
Fox.com.tr not work with Streamlink ## **Checklist** - [x] This is a bug report. - [ ] This is a feature request. - [ ] ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ## **Description** i cant see anything at fox.com.tr i have test it with this links but i became black screen ## **Reproduction steps / Explicit stream URLs to test** https://www.fox.com.tr/canli-yayin
This is not the livestreamer repo. thats right but its a plugin from streamlink look here Plugins This is a list of the currently built in plugins and what URLs and features they support. Streamlink's primary focus is live streams, so VOD support is limited. Name | URL(s) | Live | VOD | Notes foxtr | fox.com.tr | Yes | No https://streamlink.github.io/plugin_matrix.html
2018-02-27T11:53:39
streamlink/streamlink
1,517
streamlink__streamlink-1517
[ "1463" ]
b340b1e3dbb5b8dca59fcd01c224fc31f80f7402
diff --git a/src/streamlink/plugins/dogan.py b/src/streamlink/plugins/dogan.py --- a/src/streamlink/plugins/dogan.py +++ b/src/streamlink/plugins/dogan.py @@ -25,6 +25,7 @@ class Dogan(Plugin): playerctrl_re = re.compile(r'''<div[^>]*?ng-controller=(?P<quote>["'])(?:Live)?PlayerCtrl(?P=quote).*?>''', re.DOTALL) data_id_re = re.compile(r'''data-id=(?P<quote>["'])(?P<id>\w+)(?P=quote)''') content_id_re = re.compile(r'"content(?:I|i)d", "(\w+)"') + item_id_re = re.compile(r"_itemId\s+=\s+'(\w+)';") content_api = "/actions/content/media/{id}" new_content_api = "/action/media/{id}" content_api_schema = validate.Schema({ @@ -47,6 +48,7 @@ def _get_content_id(self): # find the contentId content_id_m = self.content_id_re.search(res.text) if content_id_m: + self.logger.debug("Found contentId by contentId regex") return content_id_m.group(1) # find the PlayerCtrl div @@ -56,8 +58,15 @@ def _get_content_id(self): player_ctrl_div = player_ctrl_m.group(0) content_id_m = self.data_id_re.search(player_ctrl_div) if content_id_m: + self.logger.debug("Found contentId by player data-id regex") return content_id_m.group("id") + # find the itemId var + item_id_m = self.item_id_re.search(res.text) + if item_id_m: + self.logger.debug("Found contentId by itemId regex") + return item_id_m.group(1) + def _get_hls_url(self, content_id): # make the api url relative to the current domain if "cnnturk" in self.url or "teve2.com.tr" in self.url:
Kanal7, dogan (teve2) plugins defective! Hi beardypig, kanal7 and teve2 (dogan.py) are not working since 1 month ago. ecanlitvizle from the canlitv.py needs a little fix too (changing ecanlitvizle.net to ecanlitvizle.tv) Hope you will read here :) Greetings rotarum
i wait too but ecanli dont work hi, ecanlitvizle has changed the domain again and is now known as https://www.ecanlitvizle.live/ in this case canlitv.py needs to be altered again.
2018-02-28T16:01:57
streamlink/streamlink
1,550
streamlink__streamlink-1550
[ "1515" ]
f25bf2157758b9cb5cb3df23c1c3c086ef459f78
diff --git a/src/streamlink/plugins/pixiv.py b/src/streamlink/plugins/pixiv.py new file mode 100644 --- /dev/null +++ b/src/streamlink/plugins/pixiv.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +import re + +from streamlink import PluginError +from streamlink.compat import urljoin +from streamlink.exceptions import NoStreamsError +from streamlink.plugin import Plugin +from streamlink.plugin import PluginOptions +from streamlink.plugin.api import http +from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream +from streamlink.utils import parse_json + + +class Pixiv(Plugin): + """Plugin for https://sketch.pixiv.net/lives""" + + _url_re = re.compile(r"https?://sketch\.pixiv\.net/[^/]+(?P<videopage>/lives/\d+)?") + + _videopage_re = re.compile(r"""["']live-button["']><a\shref=["'](?P<path>[^"']+)["']""") + _data_re = re.compile(r"""<script\sid=["']state["']>[^><{]+(?P<data>{[^><]+})</script>""") + _post_key_re = re.compile(r"""name=["']post_key["']\svalue=["'](?P<data>[^"']+)["']""") + + _data_schema = validate.Schema( + validate.all( + validate.transform(_data_re.search), + validate.any( + None, + validate.all( + validate.get("data"), + validate.transform(parse_json), + validate.get("context"), + validate.get("dispatcher"), + validate.get("stores"), + ) + ) + ) + ) + + login_url_get = "https://accounts.pixiv.net/login" + login_url_post = "https://accounts.pixiv.net/api/login" + + options = PluginOptions({ + "username": None, + "password": None + }) + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + def find_videopage(self): + self.logger.debug("Not a videopage") + res = http.get(self.url) + + m = self._videopage_re.search(res.text) + if not m: + self.logger.debug("No stream path, stream might be offline or invalid url.") + raise NoStreamsError(self.url) + + path = m.group("path") + self.logger.debug("Found new path: {0}".format(path)) + return urljoin(self.url, path) + + def _login(self, username, password): + res = http.get(self.login_url_get) + m = self._post_key_re.search(res.text) + if not m: + raise PluginError("Missing post_key, no login posible.") + + post_key = m.group("data") + data = { + "lang": "en", + "source": "sketch", + "post_key": post_key, + "pixiv_id": username, + "password": password, + } + + res = http.post(self.login_url_post, data=data) + res = http.json(res) + + if res["body"].get("success"): + return True + else: + return False + + def _get_streams(self): + http.headers = {"User-Agent": useragents.FIREFOX} + + login_username = self.get_option("username") + login_password = self.get_option("password") + if login_username and login_password: + self.logger.debug("Attempting login as {0}".format(login_username)) + if self._login(login_username, login_password): + self.logger.info("Successfully logged in as {0}".format(login_username)) + else: + self.logger.info("Failed to login as {0}".format(login_username)) + + videopage = self._url_re.match(self.url).group("videopage") + if not videopage: + self.url = self.find_videopage() + + data = http.get(self.url, schema=self._data_schema) + + if not data.get("LiveStore"): + self.logger.debug("No video url found, stream might be offline.") + return + + data = data["LiveStore"]["lives"] + + # get the unknown user-id + for _key in data.keys(): + video_data = data.get(_key) + + owner = video_data["owner"] + self.logger.info("Owner ID: {0}".format(owner["user_id"])) + self.logger.debug("HLS URL: {0}".format(owner["hls_movie"])) + for n, s in HLSStream.parse_variant_playlist(self.session, owner["hls_movie"]).items(): + yield n, s + + performers = video_data.get("performers") + if performers: + for p in performers: + self.logger.info("CO-HOST ID: {0}".format(p["user_id"])) + hls_url = p["hls_movie"] + self.logger.debug("HLS URL: {0}".format(hls_url)) + for n, s in HLSStream.parse_variant_playlist(self.session, hls_url).items(): + _n = "{0}_{1}".format(n, p["user_id"]) + yield _n, s + + +__plugin__ = Pixiv diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -1363,6 +1363,20 @@ def hours_minutes_seconds(value): A afreecatv.com account password to use with --afreeca-username. """ ) +plugin.add_argument( + "--pixiv-username", + metavar="USERNAME", + help=""" + The email/username used to register with pixiv.net + """ +) +plugin.add_argument( + "--pixiv-password", + metavar="PASSWORD", + help=""" + A pixiv.net account password to use with --pixiv-username + """ +) # Deprecated options stream.add_argument( diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -964,6 +964,17 @@ def setup_plugin_options(): if afreeca_password: streamlink.set_plugin_option("afreeca", "password", afreeca_password) + if args.pixiv_username: + streamlink.set_plugin_option("pixiv", "username", args.pixiv_username) + + if args.pixiv_username and not args.pixiv_password: + pixiv_password = console.askpass("Enter pixiv account password: ") + else: + pixiv_password = args.pixiv_password + + if pixiv_password: + streamlink.set_plugin_option("pixiv", "password", pixiv_password) + def check_root(): if hasattr(os, "getuid"):
diff --git a/tests/test_plugin_pixiv.py b/tests/test_plugin_pixiv.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_pixiv.py @@ -0,0 +1,19 @@ +import unittest + +from streamlink.plugins.pixiv import Pixiv + + +class TestPluginPixiv(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + 'https://sketch.pixiv.net/@exampleuser', + 'https://sketch.pixiv.net/@exampleuser/lives/000000000000000000', + ] + for url in should_match: + self.assertTrue(Pixiv.can_handle_url(url)) + + should_not_match = [ + 'https://sketch.pixiv.net', + ] + for url in should_not_match: + self.assertFalse(Pixiv.can_handle_url(url))
[Plugin Request] pixiv Sketch - [ ] This is a bug report. - [x] This is a feature request. - [ ] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. I'm requesting a plugin for pixiv sketch its streamed via HLS it serves a generated .m3u8(for 30ish seconds) along with its 3ish second chunk every second or so | xhr | https://hls4.pixivsketch.net/2018022718/15197228728388594847a96103176027c0811ead7c5788b1297/4000000_1920x1080/506579247.ts | xhr | https://hls4.pixivsketch.net/2018022718/15197228728388594847a96103176027c0811ead7c5788b1297/4000000_1920x1080/index.m3u8 hls4.pixivsketch.net: fixed gen'd server* 2018022718: stream start time (YYYYMMDDHH) 1519...1297: fixed UID* 4000000_1920x1080: video quality (low = 365000_480x270) *Until the api regens (The streamers internet drops) a look at the .m3u8 ``` #EXTM3U #EXT-X-VERSION:6 #EXT-X-MEDIA-SEQUENCE:506579247 #EXT-X-TARGETDURATION:6 #EXT-X-START:TIME-OFFSET=-3.00,PRECISE=NO #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:21.000741924+09:00 #EXTINF:3.000000, 506579247.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:24.000744924+09:00 #EXTINF:3.000000, 506579248.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:27.000747924+09:00 #EXTINF:3.000000, 506579249.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:30.000750924+09:00 #EXTINF:3.000000, 506579250.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:33.000753924+09:00 #EXTINF:3.000000, 506579251.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:36.000756924+09:00 #EXTINF:3.000000, 506579252.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:39.000759924+09:00 #EXTINF:3.000000, 506579253.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:42.000762924+09:00 #EXTINF:3.000000, 506579254.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:45.000765924+09:00 #EXTINF:3.000000, 506579255.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:48.000768924+09:00 #EXTINF:3.000000, 506579256.ts ``` **Update** found hlsvariant://... and it works but a proper plugin is appreciated
2018-03-12T20:17:11
streamlink/streamlink
1,556
streamlink__streamlink-1556
[ "1520" ]
f25bf2157758b9cb5cb3df23c1c3c086ef459f78
diff --git a/src/streamlink/plugins/youtube.py b/src/streamlink/plugins/youtube.py --- a/src/streamlink/plugins/youtube.py +++ b/src/streamlink/plugins/youtube.py @@ -78,6 +78,8 @@ def parse_fmt_list(formatsmap): validate.optional("hlsvp"): validate.text, validate.optional("live_playback"): validate.transform(bool), validate.optional("reason"): validate.text, + validate.optional("livestream"): validate.text, + validate.optional("live_playback"): validate.text, "status": validate.text } ) @@ -137,7 +139,7 @@ class YouTube(Plugin): } @classmethod - def can_handle_url(self, url): + def can_handle_url(cls, url): return _url_re.match(url) @classmethod @@ -157,13 +159,58 @@ def stream_weight(cls, stream): return weight, group + def _create_adaptive_streams(self, info, streams, protected): + adaptive_streams = {} + best_audio_itag = None + + # Extract audio streams from the DASH format list + for stream_info in info.get("adaptive_fmts", []): + if stream_info.get("s"): + protected = True + continue + + stream_params = dict(parse_qsl(stream_info["url"])) + if "itag" not in stream_params: + continue + itag = int(stream_params["itag"]) + # extract any high quality streams only available in adaptive formats + adaptive_streams[itag] = stream_info["url"] + + stream_type, stream_format = stream_info["type"] + if stream_type == "audio": + stream = HTTPStream(self.session, stream_info["url"]) + name = "audio_{0}".format(stream_format) + streams[name] = stream + + # find the best quality audio stream m4a, opus or vorbis + if best_audio_itag is None or self.adp_audio[itag] > self.adp_audio[best_audio_itag]: + best_audio_itag = itag + + if best_audio_itag and adaptive_streams and MuxedStream.is_usable(self.session): + aurl = adaptive_streams[best_audio_itag] + for itag, name in self.adp_video.items(): + if itag in adaptive_streams: + vurl = adaptive_streams[itag] + self.logger.debug("MuxedStream: v {video} a {audio} = {name}".format( + audio=best_audio_itag, + name=name, + video=itag, + )) + streams[name] = MuxedStream(self.session, + HTTPStream(self.session, vurl), + HTTPStream(self.session, aurl)) + + return streams, protected + def _find_channel_video(self): res = http.get(self.url) match = _channelid_re.search(res.text) if not match: return - return self._get_channel_video(match.group(1)) + channel_id = match.group(1) + self.logger.debug("Found channel_id: {0}".format(channel_id)) + return self._get_channel_video(channel_id) def _get_channel_video(self, channel_id): query = { @@ -178,6 +225,7 @@ def _get_channel_video(self, channel_id): for video in videos: video_id = video["id"]["videoId"] + self.logger.debug("Found video_id: {0}".format(video_id)) return video_id def _find_canonical_stream_info(self): @@ -233,10 +281,16 @@ def _get_stream_info(self, url): return info_parsed def _get_streams(self): + is_live = False + info = self._get_stream_info(self.url) if not info: return + if info.get("livestream") == '1' or info.get("live_playback") == '1': + self.logger.debug("This video is live.") + is_live = True + formats = info.get("fmt_list") streams = {} protected = False @@ -253,40 +307,8 @@ def _get_streams(self): streams[name] = stream - adaptive_streams = {} - best_audio_itag = None - - # Extract audio streams from the DASH format list - for stream_info in info.get("adaptive_fmts", []): - if stream_info.get("s"): - protected = True - continue - - stream_params = dict(parse_qsl(stream_info["url"])) - if "itag" not in stream_params: - continue - itag = int(stream_params["itag"]) - # extract any high quality streams only available in adaptive formats - adaptive_streams[itag] = stream_info["url"] - - stream_type, stream_format = stream_info["type"] - if stream_type == "audio": - stream = HTTPStream(self.session, stream_info["url"]) - name = "audio_{0}".format(stream_format) - streams[name] = stream - - # find the best quality audio stream m4a, opus or vorbis - if best_audio_itag is None or self.adp_audio[itag] > self.adp_audio[best_audio_itag]: - best_audio_itag = itag - - if best_audio_itag and adaptive_streams and MuxedStream.is_usable(self.session): - aurl = adaptive_streams[best_audio_itag] - for itag, name in self.adp_video.items(): - if itag in adaptive_streams: - vurl = adaptive_streams[itag] - streams[name] = MuxedStream(self.session, - HTTPStream(self.session, vurl), - HTTPStream(self.session, aurl)) + if is_live is False: + streams, protected = self._create_adaptive_streams(info, streams, protected) hls_playlist = info.get("hlsvp") if hls_playlist:
diff --git a/tests/test_plugin_youtube.py b/tests/test_plugin_youtube.py new file mode 100644 --- /dev/null +++ b/tests/test_plugin_youtube.py @@ -0,0 +1,23 @@ +import unittest + +from streamlink.plugins.youtube import YouTube + + +class TestPluginYouTube(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + "https://www.youtube.com/c/EXAMPLE/live", + "https://www.youtube.com/channel/EXAMPLE", + "https://www.youtube.com/v/aqz-KE-bpKQ", + "https://www.youtube.com/embed/aqz-KE-bpKQ", + "https://www.youtube.com/user/EXAMPLE/", + "https://www.youtube.com/watch?v=aqz-KE-bpKQ", + ] + for url in should_match: + self.assertTrue(YouTube.can_handle_url(url)) + + should_not_match = [ + "https://www.youtube.com", + ] + for url in should_not_match: + self.assertFalse(YouTube.can_handle_url(url))
Youtube Livestream download starts then instantly closes *Thanks for reporting an issue!* *Please read the contribution guidelines first! (see the link above)* *Also check the list of known issues before reporting an issue!* *Feel free to use the following template. Be as detailed as possible.* *Please see the text preview to avoid unnecessary formatting errors.* *Don't forget to remove this text before submitting.* ---- ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Youtube livestream download starts then instantly closes. Playing the file shows that it only downloaded about 1 second. The video and audio for that 1 second are fine though. ``` streamlink --hls-live-edge 99999 --hls-segment-threads 5 -o "video.ts" https://www.youtube.com/watch?v=mwhZ5C-Z1I8 best ``` This command has worked before dozens of time on the same channel. Thought it has been a few months since I last used it. ### Expected / Actual behavior Supposed to download the entire livestream from the start but only downloads 1 second at the current moment before quitting. ### Reproduction steps / Explicit stream URLs to test 1. https://www.youtube.com/watch?v=mwhZ5C-Z1I8 ### Logs _Logs are always required for a bug report, use `-l debug` [(help)](https://streamlink.github.io/cli.html#cmdoption-l) Make sure to **remove username and password** You can upload your logs to https://gist.github.com/ or_ ``` [Streamlink for Windows v0.10.0 - Git b839cfd] [cli][info] Found matching plugin youtube for URL https://www.youtube.com/watch?v=mwhZ5C-Z1I8 [plugin.youtube][debug] get_video_info - 1: Found data [cli][info] Available streams: audio_mp4, 144p (worst), 240p, 360p, 480p, 720p, 1080p, 1080p60 (best) [cli][info] Opening stream: 1080p60 (muxed-stream) [stream.][debug] Opening http substream [stream.][debug] Opening http substream [stream.mp4mux-ffmpeg][debug] ffmpeg command: \streamlink-portable-master\Streamlink for Windows (Compiled)\Releases\Streamlink\Dependencies\ffmpeg\ffmpeg.exe -nostats -y -i \\.\pipe\ffmpeg-7860-872 -i \\.\pipe\ffmpeg-7860-444 -c:v copy -c:a copy -map 0 -map 1 -f matroska pipe:1 [stream.mp4mux-ffmpeg][debug] Starting copy to pipe: \\.\pipe\ffmpeg-7860-872 [stream.mp4mux-ffmpeg][debug] Starting copy to pipe: \\.\pipe\ffmpeg-7860-444 [cli][debug] Pre-buffering 8192 bytes [cli][debug] Checking file output [cli][debug] Writing stream to output [stream.mp4mux-ffmpeg][debug] Pipe copy complete: \\.\pipe\ffmpeg-7860-444 [stream.mp4mux-ffmpeg][debug] Pipe copy complete: \\.\pipe\ffmpeg-7860-872 [stream.mp4mux-ffmpeg][debug] Closing ffmpeg thread [stream.mp4mux-ffmpeg][debug] Closed all the substreams [cli][info] Stream ended [cli][info] Closing currently open stream... [stream.mp4mux-ffmpeg][debug] Closing ffmpeg thread [stream.mp4mux-ffmpeg][debug] Closed all the substreams [End of Streamlink for Windows with ExitCode 0] ``` ### Comments, screenshots, etc. ... [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
the HTTPStream url is just 5 sec long, it won't continue without a refresh but the refresh is 5 sec as well. https://github.com/streamlink/streamlink/blob/5d81d68c7a47e931f050632ae7cddb3b044971b4/src/streamlink/plugins/youtube.py#L288-L289 the behavior was maybe different before. --- the `muxed stream` _1080p60_ won't work, but you could try a `hls stream` _1080p_ for now.
2018-03-16T21:05:04
streamlink/streamlink
1,578
streamlink__streamlink-1578
[ "1577" ]
c2368bea030c50beb794821b01b92bad5e21c5fb
diff --git a/src/streamlink/plugins/rtve.py b/src/streamlink/plugins/rtve.py --- a/src/streamlink/plugins/rtve.py +++ b/src/streamlink/plugins/rtve.py @@ -1,5 +1,6 @@ import base64 import re +from functools import partial from Crypto.Cipher import Blowfish @@ -59,7 +60,7 @@ class Rtve(Plugin): https?://(?:www\.)?rtve\.es/(?:directo|noticias|television|deportes|alacarta|drmn)/.*?/? """, re.VERBOSE) cdn_schema = validate.Schema( - validate.transform(parse_xml), + validate.transform(partial(parse_xml, invalid_char_entities=True)), validate.xml_findall(".//preset"), [ validate.union({ diff --git a/src/streamlink/utils/__init__.py b/src/streamlink/utils/__init__.py --- a/src/streamlink/utils/__init__.py +++ b/src/streamlink/utils/__init__.py @@ -7,7 +7,7 @@ except ImportError: # pragma: no cover import xml.etree.ElementTree as ET -from streamlink.compat import urljoin, urlparse, parse_qsl, is_py2, urlunparse +from streamlink.compat import urljoin, urlparse, parse_qsl, is_py2, urlunparse, is_py3 from streamlink.exceptions import PluginError from streamlink.utils.named_pipe import NamedPipe @@ -67,7 +67,7 @@ def parse_json(data, name="JSON", exception=PluginError, schema=None): return json_data -def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None): +def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None, invalid_char_entities=False): """Wrapper around ElementTree.fromstring with some extras. Provides these extra features: @@ -77,9 +77,14 @@ def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=N """ if is_py2 and isinstance(data, unicode): data = data.encode("utf8") + elif is_py3: + data = bytearray(data, "utf8") if ignore_ns: - data = re.sub(" xmlns=\"(.+?)\"", "", data) + data = re.sub(br" xmlns=\"(.+?)\"", b"", data) + + if invalid_char_entities: + data = re.sub(br'&(?!(?:#(?:[0-9]+|[Xx][0-9A-Fa-f]+)|[A-Za-z0-9]+);)', b'&amp;', data) try: tree = ET.fromstring(data)
diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -76,6 +76,20 @@ def test_parse_xml_validate(self): self.assertEqual(expected.tag, actual.tag) self.assertEqual(expected.attrib, actual.attrib) + def test_parse_xml_entities_fail(self): + self.assertRaises(PluginError, + parse_xml, u"""<test foo="bar &"/>""") + + + def test_parse_xml_entities(self): + expected = ET.Element("test", {"foo": "bar &"}) + actual = parse_xml(u"""<test foo="bar &"/>""", + schema=validate.Schema(xml_element(tag="test", attrib={"foo": text})), + invalid_char_entities=True) + self.assertEqual(expected.tag, actual.tag) + self.assertEqual(expected.attrib, actual.attrib) + + def test_parse_qsd(self): self.assertEqual( {"test": "1", "foo": "bar"},
Plugin: Rtve.es: Unable to parse XML: not well-formed (invalid token) ### Checklist - [x] This is a bug report. ### Description Rtve plugin always gives XML parsing error for all video urls. ### Reproduction steps / Explicit stream URLs to test 1. http://www.rtve.es/alacarta/videos/telediario/telediario-15-horas-26-03-18/4540424/ 2. http://www.rtve.es/alacarta/videos/aguila-roja/aguila-roja-t9-capitulo-116/3771566/ 3. http://www.rtve.es/directo/la-1 ### Logs ``` [plugin.rtve][debug] Found content with id: 4540424 Plugin error: Unable to parse XML: not well-formed (invalid token): line 1, column 762 (b"<?xml version='1.0'?><quality><pr ...) Process finished with exit code 1 ``` ### Comments, screenshots, etc. xml contains `&` characters, replacing with `&amp;` gets it working. Resolved by modifying streamlink\utils\__init__.py and adding `data = re.sub("&", "&amp;", data.decode('utf8'))` ``` [plugin.rtve][debug] Found content with id: 4540424 OrderedDict([('540p_http', <HTTPStream('http://mvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/8/1522075587483.mp4')>), ('360p_http', <HTTPStream('http://mvod.lvlt.rtve.es/resources/TE_NGVA/mp4/1/1/1522075683411.mp4')>), ('270p_http', <HTTPStream('http://mvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/0/1522075727303.mp4')>), ('270p_alt', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/0/1522075727303.mp4/1522075727303-audio=48001-video=620000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('270p', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/3/0/1522075727303.mp4/1522075727303-audio=48001-video=620000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('360p_alt', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/1/1/1522075683411.mp4/1522075683411-audio=64001-video=720000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('360p', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/1/1/1522075683411.mp4/1522075683411-audio=64001-video=720000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('540p_alt', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/8/1522075587483.mp4/1522075587483-audio=64001-video=1400000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('540p', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/3/8/1522075587483.mp4/1522075587483-audio=64001-video=1400000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('worst', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/0/1522075727303.mp4/1522075727303-audio=48001-video=620000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('best', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/3/8/1522075587483.mp4/1522075587483-audio=64001-video=1400000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>)]) Process finished with exit code 0 ``` **Don't know if this breaks other plugins as I only use this one.** ``` def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None): """Wrapper around ElementTree.fromstring with some extras Provides these extra features: - Handles incorrectly encoded XML - Allows stripping namespace information - Wraps errors in custom exception with a snippet of the data in the message """ if is_py2 and isinstance(data, unicode): data = data.encode("utf8") if ignore_ns: data = re.sub(" xmlns=\"(.+?)\"", "", data) data = re.sub("&", "&amp;", data.decode('utf8')) try: tree = ET.fromstring(data) except Exception as err: snippet = repr(data) if len(snippet) > 35: snippet = snippet[:35] + " ..." raise exception("Unable to parse {0}: {1} ({2})".format(name, err, snippet)) if schema: tree = schema.validate(tree, name=name, exception=exception) return tree ```
Hmm, that is annoying. Replacing `&` with `&amp;` will certainly break something else unfortunately... We might be able to replace any `&` that is not part of a character entity with `&amp;` though.
2018-03-27T10:04:14
streamlink/streamlink
1,583
streamlink__streamlink-1583
[ "1456" ]
e64f10593be429ad0c143c93aaf745552f5b9e03
diff --git a/src/streamlink/plugins/vaughnlive.py b/src/streamlink/plugins/vaughnlive.py --- a/src/streamlink/plugins/vaughnlive.py +++ b/src/streamlink/plugins/vaughnlive.py @@ -38,10 +38,10 @@ class VaughnLive(Plugin): range(1, 6))] origin = "https://vaughnlive.tv" rtmp_server_map = { - "594140c69edad": "66.90.93.42", - "585c4cab1bef1": "66.90.93.34", - "5940d648b3929": "66.90.93.42", - "5941854b39bc4": "198.255.0.10" + "594140c69edad": "192.240.105.171:1935", + "585c4cab1bef1": "192.240.105.171:1935", + "5940d648b3929": "192.240.105.171:1935", + "5941854b39bc4": "192.240.105.171:1935" } name_remap = {"#vl": "live", "#btv": "btv", "#pt": "pt", "#igb": "instagib", "#vtv": "vtv"} domain_map = {"vaughnlive": "#vl", "breakers": "#btv", "instagib": "#igb", "vapers": "#vtv", "pearltime": "#pt"} @@ -99,6 +99,7 @@ def _get_streams(self): if not is_live: self.logger.info("Stream is currently off air") else: + self.logger.info("Stream powered by VaughnSoft - remember to support them.") for s in self._get_rtmp_streams(server, domain, channel, token): yield s
Vaughnlive changed IP's to break Streamlink This will be a very brief bug report... As of tonight the head vaughnlive.py references IPs which were disconnected by vaughn to thwart streamlinking. I've observed vaughn serving video now from "66.90.93.44","66.90.93.35" and have personally gotten it to work overwriting the IP's in rtmp_server_map with those two alternating. I would submit the commit but I think some more testing is needed as I only use streamlink with one occasional stream and don't know how far those IPs will get more frequent SL users. #1187 contains lengthy discussion on the history of the war vaughn has waged against streamlink, this is probably not the last time the IPs will change.
The question at this point is whether it's really worth maintaining the plugin. 99% of the content on Vaughn is stolen, so is it worth continuing? If someone wants to tackle it they can (I know @beardypig has been heading this up in the past) but I really don't care to keep wasting time on this site or a variety of others that are restreaming illegally. @jshir These changes aren't made with the intention to break Streamlink. They are part of the ongoing migration to a HTML5-based player. @gravyboat Why do you say it's stolen content? Most streams on the site's several subdomains are casts from personal cams. The casters send their streams directly to the vaughnlive servers. There are actually a bunch of other sites stealing streams from vaughnlive through unauthorized embeds. The streaming server IPs have been changing frequently over the past few days. Currently, there is only one active server. Setting all entries in the `rtmp_server_map` to `66.90.93.36:1935` will resolve the issue until the next change, which could happen at any moment. @fadster Last time I checked out the site there were a lot of restreams of news stations, cable broadcasts, sports events, etc. Maybe it has changed since then. Is it possible to automate retrieving of rtmp server address ? @karlo2105 it should be. Seems like it could be retrieved on demand once, and only attempt another check if unable to contact again. I might fork and see what I can come up with. I think it's easier to get vaughnlive now than before. Any update on this? @johnpolite I've removed your comment as it refers to a direct way to watch stolen content and I don't want us to potentially get in trouble. In addition you should report this to the vaughnlive site owner so they can suspend that user for an illegal restream. Thanks for trying to help people though! Who knows what is legal or illegal on the internet? Less spreading of fake news - Fox News, is not a bad idea though. @johnpolite how to check ips? tks pls help me @jshir Tks . Can u give me file Vaughn.py ? thank so much Is this still broken? @thinkpad4 Probably. No one has updated the plugin as far as I'm aware. Damn. Ok, thanks Did the server map change? It looks like the new IP could be 66.90.93.42, but I'm still getting time outs. So maybe I'm missing the port? 192.240.105.171:1935 is working for me now. @TVGPlayer Right on! Thanks man! EDIT: Okay I give up. How did you find that? I'm looking everywhere and getting no where. @techmouse Email me at [email protected].
2018-03-29T10:08:21
streamlink/streamlink
1,606
streamlink__streamlink-1606
[ "1579" ]
cb926fb4751974fa1841f0239dadf00fea005873
diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py --- a/src/streamlink/plugins/tf1.py +++ b/src/streamlink/plugins/tf1.py @@ -1,6 +1,7 @@ from __future__ import print_function import re +from streamlink.compat import urlparse, parse_qsl from streamlink.plugin import Plugin from streamlink.plugin.api import http, useragents from streamlink.stream import HDSStream @@ -41,8 +42,9 @@ def _get_hls_streams(self, channel): m = self.embed_re.search(embed_page.text) if m: - hls_stream_url = m.group(1) - + o = urlparse(m.group(1)) + prms = dict(parse_qsl(o.query)) + hls_stream_url = "{0}://{1}{2}?hdnea={3}".format(o.scheme, o.netloc, o.path, prms["hdnea"]) try: for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): yield s
tf1 plugin better stream Hi, Are you sure there isn't better stream than 360p for TF1 ? [cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/tf1/direct [cli][info] Available streams: 496k (worst), 234p_alt, 234p, 896k, 360p_alt, 360p (best) I have a far better quality with a web browser than best.
It's always difficult answering issues when people don't fill out the template. Please do this next time, so it is clear to us and everyone else which Streamlink version you are using. > Available streams: 496k (worst), 234p_alt, 234p, 896k, 360p_alt, 360p (best) In order to select the "best" stream, all of the available streams first need to be sorted by their "weight". Since there are different kind of formats being returned from the master playlist (resolution based with an unknown bitrate and bitrate based with an unknown resolution), Streamlink somehow needs to convert them into a common format. That's being done here: https://github.com/streamlink/streamlink/blob/0.11.0/src/streamlink/plugin/plugin.py#L51-L88 As you can see, the streams which are described by their bitrate ("k" suffix) get their weight from the bitrate divided by `BIT_RATE_WEIGHT_RATIO`, which is equal to `2.8`, and streams which are described by their resolution ("p" suffix) get their weight from the video height (plus frame rate, if available). The number `2.8` was defined by Chrippa 5 years ago and hasn't been changed since, see ddad859c9d6c5c791722536f8051222ba255d3fa. This formula is basically just an assumption of how big the resolution of a stream might be according to its bitrate, but it's not an ideal solution. The stream_weight method need to get overridden in the plugin to fix this issue, or someone could make the `BIT_RATE_WEIGHT_RATIO` more dynamic, but for now, you can solve your issue by simply selecting the intended stream (896k) instead of "best"... It looks like 896k is also 360p, so probably they are the same - one is HDS and the other is HLS. It's possible that there are other stream types available, that aren't supported by streamlink that are higher quality. Maybe @BZHDeveloper will have some more information. no better qualities for TF1 live, sorry :) see m3u8 info >#EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=496000,RESOLUTION=416x234,CODECS="avc1.66.30, mp4a.40.2" >#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=496000,RESOLUTION=416x234,CODECS="avc1.66.30, mp4a.40.2" >#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=896000,RESOLUTION=640x360,CODECS="avc1.66.30, mp4a.40.2" >#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=896000,RESOLUTION=640x360,CODECS="avc1.66.30, mp4a.40.2" Closing thanks to the comment by @BZHDeveloper. NOTE (after investigation) : TF1 group now use MPD format for his livestreams it's possible ``` [cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/tf1/direct [cli][info] Available streams: 496k (worst), 234p_alt, 234p, 896k, 360p_alt, 360p, 1328k, 576p_alt, 576p, 720p_alt, 720p, 2328k (best) ``` you need to change the url parameters OLD URL: http://.../...?hdnea=...&n=...&\_\_b\_\_=...&b=... NEW URL: http://.../...?hdnea=...
2018-04-16T06:26:30