1
0
mirror of https://github.com/ytdl-org/youtube-dl.git synced 2024-11-16 14:27:53 +00:00

Fix TT blocking

Add TikTokVM
Partial fix for TikTokUser
This commit is contained in:
dirkf 2022-04-25 15:24:32 +01:00
parent b428754fa9
commit 2f65e205e1
2 changed files with 105 additions and 55 deletions

View File

@ -1249,6 +1249,7 @@ from .threeqsdn import ThreeQSDNIE
from .tiktok import ( from .tiktok import (
TikTokIE, TikTokIE,
TikTokUserIE, TikTokUserIE,
TikTokVMIE,
) )
from .tinypic import TinyPicIE from .tinypic import TinyPicIE
from .tmz import ( from .tmz import (

View File

@ -1,15 +1,18 @@
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals from __future__ import unicode_literals
import re
from .common import InfoExtractor from .common import InfoExtractor
from .generic import GenericIE
from ..compat import ( from ..compat import (
compat_str, compat_kwargs,
compat_urllib_request,
) )
from ..utils import ( from ..utils import (
dict_get,
ExtractorError, ExtractorError,
float_or_none, float_or_none,
HEADRequest, get_element_by_id,
int_or_none, int_or_none,
str_or_none, str_or_none,
try_get, try_get,
@ -17,24 +20,37 @@ from ..utils import (
) )
# decorator enforces UA that TT doesn't block
def vanilla_UA_request(func):
vanilla_UA = 'Mozilla/5.0'
def wrapped(*args, **kwargs):
headers = kwargs.get('headers', {})
if 'User-Agent' not in headers:
headers['User-Agent'] = vanilla_UA
kwargs.update({'headers': headers, })
kwargs = compat_kwargs(kwargs)
return func(*args, **kwargs)
return wrapped
class TikTokBaseIE(InfoExtractor): class TikTokBaseIE(InfoExtractor):
def _download_webpage( IE_DESC = 'Abstract base for TikTok extractors'
self, url_or_request, video_id, note=None, errnote=None, IE_NAME = 'tiktok:base'
fatal=True, tries=1, timeout=5, encoding=None, data=None,
headers={}, query={}, expected_status=None, setup=True):
if setup: @vanilla_UA_request
url = url_or_request.geturl() if isinstance(url_or_request, compat_urllib_request.Request) else url_or_request def _request_webpage(self, *args, **kwargs):
# dummy request to set cookies return super(TikTokBaseIE, self)._request_webpage(*args, **kwargs)
self._request_webpage(
HEADRequest(url), video_id,
note=False, errnote='Could not send HEAD request to %s' % url,
fatal=False, headers=headers)
return super(TikTokBaseIE, self)._download_webpage( def _get_SIGI_STATE(self, video_id, html):
url_or_request, video_id, note=note, errnote=errnote, state = self._parse_json(
fatal=fatal, tries=tries, timeout=timeout, encoding=encoding, data=data, get_element_by_id('SIGI_STATE', html)
headers=headers, query=query, expected_status=expected_status) or self._search_regex(
r'''(?s)<script\s[^>]*?\bid\s*=\s*(?P<q>"|'|\b)sigi-persisted-data(?P=q)[^>]*>[^=]*=\s*(?P<json>{.+?})\s*(?:;[^<]+)?</script''',
html, 'sigi data', default='{}', group='json'), video_id)
return state if isinstance(state, dict) else {}
def _extract_video(self, data, video_id=None): def _extract_video(self, data, video_id=None):
video = try_get(data, lambda x: x['video'], dict) video = try_get(data, lambda x: x['video'], dict)
@ -102,18 +118,20 @@ class TikTokBaseIE(InfoExtractor):
class TikTokIE(TikTokBaseIE): class TikTokIE(TikTokBaseIE):
_VALID_URL = r'https?://(?:www\.)?tiktok\.com/@[^/]+/video/(?P<id>\d+)' IE_DESC = 'TikTok video extractor'
IE_NAME = 'tiktok'
_VALID_URL = r'(?:https?://(?:(?:www|m)\.)?tiktok\.com/@[^/]+/video/|tiktok:(?P<user_id>[^/?#&]+):)(?P<id>\d+)'
_TESTS = [{ _TESTS = [{
'url': 'https://www.tiktok.com/@zureeal/video/6606727368545406213', 'url': 'https://www.tiktok.com/@zureeal/video/6606727368545406213',
'md5': '163ceff303bb52de60e6887fe399e6cd', 'md5': '163ceff303bb52de60e6887fe399e6cd',
'info_dict': { 'info_dict': {
'id': '6606727368545406213', 'id': '6606727368545406213',
'ext': 'mp4', 'ext': 'mp4',
'title': 'md5:24acc456b62b938a7e2dd88e978b20d9', 'title': 'md5:363e08ccb6c691314710429f379bffe5',
'description': '#bowsette#mario#cosplay#uk#lgbt#gaming#asian#bowsettecosplay', 'description': '#bowsette#mario#cosplay#uk#lgbt#gaming#asian#bowsettecosplay',
'thumbnail': r're:^https?://.*', 'thumbnail': r're:^https?://.*',
'duration': 15, 'duration': 15,
'uploader': 'md5:24acc456b62b938a7e2dd88e978b20d9', 'uploader': 'md5:363e08ccb6c691314710429f379bffe5',
'uploader_id': '188294915489964032', 'uploader_id': '188294915489964032',
'timestamp': 1538248586, 'timestamp': 1538248586,
'upload_date': '20180929', 'upload_date': '20180929',
@ -124,78 +142,85 @@ class TikTokIE(TikTokBaseIE):
} }
}] }]
def _real_initialize(self):
# Setup session (will set necessary cookies)
self._request_webpage(
'https://www.tiktok.com/', None, note='Setting up session')
def _real_extract(self, url): def _real_extract(self, url):
video_id = self._match_id(url) m = re.match(self._VALID_URL, url).groupdict()
video_id = m['id']
if 'user_id' in m:
url = 'https://www.tiktok.com/@%(user_id)s/video/%(id)s/' % m
webpage = self._download_webpage(url, video_id) webpage = self._download_webpage(url.replace('://m.', '://www.'), video_id)
page_props = self._parse_json(self._search_regex( page_props = self._get_SIGI_STATE(video_id, webpage)
r'''(?s)<script\s[^>]*?\bid\s*=\s*(?P<q>"|'|\b)sigi-persisted-data(?P=q)[^>]*>[^=]*=\s*(?P<json>{.+?})\s*(?:;[^<]+)?</script''', if try_get(page_props, lambda x: x['ItemModule'][video_id]['video'], dict):
webpage, 'sigi data', default='{}', group='json'), video_id)
data = try_get(page_props, lambda x: x['ItemModule'][video_id]['video'], dict)
if data:
data = page_props['ItemModule'][video_id] data = page_props['ItemModule'][video_id]
if data.get('privateItem'): if data.get('privateItem'):
raise ExtractorError('This video is private', expected=True) raise ExtractorError('This video is private', expected=True)
return self._extract_video(data, video_id) return self._extract_video(data, video_id)
page_props = self._parse_json(self._search_regex( # old page format - may still be served?
r'<script[^>]+\bid=["\']__NEXT_DATA__[^>]+>\s*({.+?})\s*</script', page_props = self._parse_json(
webpage, 'data'), video_id)['props']['pageProps'] get_element_by_id('__NEXT_DATA__', webpage),
video_id)['props']['pageProps']
data = try_get(page_props, lambda x: x['itemInfo']['itemStruct'], dict) data = try_get(page_props, lambda x: x['itemInfo']['itemStruct'], dict)
if not data and page_props.get('statusCode') == 10216: if not data and page_props.get('statusCode') == 10216:
raise ExtractorError('This video is private', expected=True) raise ExtractorError('This video is private', expected=True)
return self._extract_video(data, video_id) return self._extract_video(data, video_id)
class TikTokUserIE(TikTokBaseIE): class TikTokUserIE(TikTokIE):
_VALID_URL = r'https://(?:www\.)?tiktok\.com/@(?P<id>[^/?#&]+)' IE_DESC = 'TikTok user profile extractor'
IE_NAME = 'tiktok:user'
_VALID_URL = r'https?://(?:(?:www|m)\.)?tiktok\.com/@(?P<id>[^/?#&]+)'
_TESTS = [{ _TESTS = [{
'url': 'https://www.tiktok.com/@zureeal', 'url': 'https://www.tiktok.com/@zureeal',
'info_dict': { 'info_dict': {
'id': '188294915489964032', 'id': '188294915489964032',
}, },
'playlist_mincount': 24, 'playlist_mincount': 30,
'expected_warnings': [
'More videos are available',
],
}] }]
@classmethod @classmethod
def suitable(cls, url): def suitable(cls, url):
return False if TikTokIE.suitable(url) else super(TikTokUserIE, cls).suitable(url) return False if TikTokIE.suitable(url) else super(TikTokBaseIE, cls).suitable(url)
def _real_extract(self, url): def _real_extract(self, url):
user_id = self._match_id(url) user_id = self._match_id(url)
webpage = self._download_webpage(url, user_id) webpage = self._download_webpage(url.replace('://m.', '://www.'), user_id)
page_props = self._parse_json(self._search_regex(
r'''(?s)<script\s[^>]*?\bid\s*=\s*(?P<q>"|'|\b)sigi-persisted-data(?P=q)[^>]*>[^=]*=\s*(?P<json>{.+?})\s*(?:;[^<]+)?</script''', page_props = self._get_SIGI_STATE(user_id, webpage)
webpage, 'sigi data', default='{}', group='json'), user_id)
user_data = try_get(page_props, lambda x: x['UserModule']['users'], dict) user_data = try_get(page_props, lambda x: x['UserModule']['users'], dict)
entries = []
if user_data: if user_data:
num_id = try_get( num_id = try_get(
user_data.values(), user_data.values(),
lambda x: [user['id'] for user in x if user['uniqueId'] == user_id][0], lambda x: [user['id'] for user in x if user['uniqueId'] == user_id and user['id'].isdigit()][0])
compat_str) item_data = try_get(page_props, lambda x: x['ItemList']['user-post'], dict) or {}
item_data = try_get(page_props, lambda x: x['ItemModule'], dict) item_list = dict_get(item_data, ('list', 'browserList'))
if item_data: if not item_list:
item_data = item_data.values() item_list = try_get(item_data, lambda x: [y['id'] for y in x['preloadList']], list)
for data in item_data or []: entries = ['tiktok:%s:%s' % (user_id, x, ) for x in item_list or []]
if data.get('privateItem'): if item_data.get('hasMore', False):
continue self._downloader.report_warning('More videos are available but the current extractor doesn\'t know how to find them')
item = self._extract_video(data, user_id)
if item: result = entries and self.playlist_from_matches(entries, num_id, ie='TikTok')
entries.append(item)
result = entries and self.playlist_result(entries, num_id)
if not result:
item_data = try_get(page_props, lambda x: x['ItemList']['user-post']['list'], list)
result = self.playlist_from_matches(item_data, playlist_id=num_id, getter=lambda m: 'tiktok:%s' % (m, ))
if result: if result:
result['display_id'] = user_id result['display_id'] = user_id
return result return result
"""
# this no longer works 2022-01
data = self._download_json( data = self._download_json(
'https://m.tiktok.com/h5/share/usr/list/%s/' % user_id, user_id, 'https://m.tiktok.com/h5/share/usr/list/%s/' % user_id, user_id,
query={'_signature': '_'}) query={'_signature': '_'})
entries = []
for aweme in data['aweme_list']: for aweme in data['aweme_list']:
try: try:
entry = self._extract_video(aweme) entry = self._extract_video(aweme)
@ -205,3 +230,27 @@ class TikTokUserIE(TikTokBaseIE):
entries.append(entry) entries.append(entry)
return self.playlist_result(entries, user_id) return self.playlist_result(entries, user_id)
"""
class TikTokVMIE(GenericIE):
IE_DESC = 'Resolver for TikTok shortcuts'
IE_NAME = 'tiktok:shortcut'
_VALID_URL = r'https?://(?:vm\.tiktok\.com|m\.tiktok\.com/v)/(?P<id>[^/?#&.]+)'
_TESTS = [{
'url': 'https://vm.tiktok.com/ZMLesneqK/',
'info_dict': {
'id': '7054218882072055046',
'ext': 'mp4',
'title': 'EddY',
'upload_date': '20220117',
'description': 'Hilft bestimmt gegen nervige Anrufer! 😂 #telefon #call #prank #fail #sprecher #stimme #voice #band #ansage #sound #comedy #unterhaltung #scammer #fy',
'timestamp': 1642438324,
'uploader': 'EddY',
'uploader_id': '6850021004246467590',
},
}]
@vanilla_UA_request
def _request_webpage(self, *args, **kwargs):
return super(GenericIE, self)._request_webpage(*args, **kwargs)