Skip to content

Commit

Permalink
Fix TT blocking
Browse files Browse the repository at this point in the history
Add TikTokVM
Partial fix for TikTokUser
  • Loading branch information
dirkf committed Apr 25, 2022
1 parent b428754 commit 2f65e20
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 57 deletions.
1 change: 1 addition & 0 deletions youtube_dl/extractor/extractors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,7 @@
from .tiktok import (
TikTokIE,
TikTokUserIE,
TikTokVMIE,
)
from .tinypic import TinyPicIE
from .tmz import (
Expand Down
163 changes: 106 additions & 57 deletions youtube_dl/extractor/tiktok.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,56 @@
# coding: utf-8
from __future__ import unicode_literals

import re

from .common import InfoExtractor
from .generic import GenericIE
from ..compat import (
compat_str,
compat_urllib_request,
compat_kwargs,
)
from ..utils import (
dict_get,
ExtractorError,
float_or_none,
HEADRequest,
get_element_by_id,
int_or_none,
str_or_none,
try_get,
url_or_none,
)


# 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):
def _download_webpage(
self, url_or_request, video_id, note=None, errnote=None,
fatal=True, tries=1, timeout=5, encoding=None, data=None,
headers={}, query={}, expected_status=None, setup=True):

if setup:
url = url_or_request.geturl() if isinstance(url_or_request, compat_urllib_request.Request) else url_or_request
# dummy request to set cookies
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(
url_or_request, video_id, note=note, errnote=errnote,
fatal=fatal, tries=tries, timeout=timeout, encoding=encoding, data=data,
headers=headers, query=query, expected_status=expected_status)
IE_DESC = 'Abstract base for TikTok extractors'
IE_NAME = 'tiktok:base'

@vanilla_UA_request
def _request_webpage(self, *args, **kwargs):
return super(TikTokBaseIE, self)._request_webpage(*args, **kwargs)

def _get_SIGI_STATE(self, video_id, html):
state = self._parse_json(
get_element_by_id('SIGI_STATE', html)
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):
video = try_get(data, lambda x: x['video'], dict)
Expand Down Expand Up @@ -102,18 +118,20 @@ def _extract_video(self, data, video_id=None):


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 = [{
'url': 'https://www.tiktok.com/@zureeal/video/6606727368545406213',
'md5': '163ceff303bb52de60e6887fe399e6cd',
'info_dict': {
'id': '6606727368545406213',
'ext': 'mp4',
'title': 'md5:24acc456b62b938a7e2dd88e978b20d9',
'title': 'md5:363e08ccb6c691314710429f379bffe5',
'description': '#bowsette#mario#cosplay#uk#lgbt#gaming#asian#bowsettecosplay',
'thumbnail': r're:^https?://.*',
'duration': 15,
'uploader': 'md5:24acc456b62b938a7e2dd88e978b20d9',
'uploader': 'md5:363e08ccb6c691314710429f379bffe5',
'uploader_id': '188294915489964032',
'timestamp': 1538248586,
'upload_date': '20180929',
Expand All @@ -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):
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(
r'''(?s)<script\s[^>]*?\bid\s*=\s*(?P<q>"|'|\b)sigi-persisted-data(?P=q)[^>]*>[^=]*=\s*(?P<json>{.+?})\s*(?:;[^<]+)?</script''',
webpage, 'sigi data', default='{}', group='json'), video_id)
data = try_get(page_props, lambda x: x['ItemModule'][video_id]['video'], dict)
if data:
page_props = self._get_SIGI_STATE(video_id, webpage)
if try_get(page_props, lambda x: x['ItemModule'][video_id]['video'], dict):
data = page_props['ItemModule'][video_id]
if data.get('privateItem'):
raise ExtractorError('This video is private', expected=True)
return self._extract_video(data, video_id)

page_props = self._parse_json(self._search_regex(
r'<script[^>]+\bid=["\']__NEXT_DATA__[^>]+>\s*({.+?})\s*</script',
webpage, 'data'), video_id)['props']['pageProps']
# old page format - may still be served?
page_props = self._parse_json(
get_element_by_id('__NEXT_DATA__', webpage),
video_id)['props']['pageProps']
data = try_get(page_props, lambda x: x['itemInfo']['itemStruct'], dict)
if not data and page_props.get('statusCode') == 10216:
raise ExtractorError('This video is private', expected=True)
return self._extract_video(data, video_id)


class TikTokUserIE(TikTokBaseIE):
_VALID_URL = r'https://(?:www\.)?tiktok\.com/@(?P<id>[^/?#&]+)'
class TikTokUserIE(TikTokIE):
IE_DESC = 'TikTok user profile extractor'
IE_NAME = 'tiktok:user'
_VALID_URL = r'https?://(?:(?:www|m)\.)?tiktok\.com/@(?P<id>[^/?#&]+)'
_TESTS = [{
'url': 'https://www.tiktok.com/@zureeal',
'info_dict': {
'id': '188294915489964032',
},
'playlist_mincount': 24,
'playlist_mincount': 30,
'expected_warnings': [
'More videos are available',
],
}]

@classmethod
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):
user_id = self._match_id(url)

webpage = self._download_webpage(url, 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''',
webpage, 'sigi data', default='{}', group='json'), user_id)
webpage = self._download_webpage(url.replace('://m.', '://www.'), user_id)

page_props = self._get_SIGI_STATE(user_id, webpage)
user_data = try_get(page_props, lambda x: x['UserModule']['users'], dict)
entries = []
if user_data:
num_id = try_get(
user_data.values(),
lambda x: [user['id'] for user in x if user['uniqueId'] == user_id][0],
compat_str)
item_data = try_get(page_props, lambda x: x['ItemModule'], dict)
if item_data:
item_data = item_data.values()
for data in item_data or []:
if data.get('privateItem'):
continue
item = self._extract_video(data, user_id)
if item:
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, ))
lambda x: [user['id'] for user in x if user['uniqueId'] == user_id and user['id'].isdigit()][0])
item_data = try_get(page_props, lambda x: x['ItemList']['user-post'], dict) or {}
item_list = dict_get(item_data, ('list', 'browserList'))
if not item_list:
item_list = try_get(item_data, lambda x: [y['id'] for y in x['preloadList']], list)
entries = ['tiktok:%s:%s' % (user_id, x, ) for x in item_list or []]
if item_data.get('hasMore', False):
self._downloader.report_warning('More videos are available but the current extractor doesn\'t know how to find them')

result = entries and self.playlist_from_matches(entries, num_id, ie='TikTok')
if result:
result['display_id'] = user_id
return result

"""
# this no longer works 2022-01
data = self._download_json(
'https://m.tiktok.com/h5/share/usr/list/%s/' % user_id, user_id,
query={'_signature': '_'})
entries = []
for aweme in data['aweme_list']:
try:
entry = self._extract_video(aweme)
Expand All @@ -205,3 +230,27 @@ def _real_extract(self, url):
entries.append(entry)
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)

0 comments on commit 2f65e20

Please sign in to comment.