Skip to content

Commit c1aa9b9

Browse files
authored
Merge pull request #640 from tcely/patch-4
Automated channel_id extraction
2 parents 4a24fd1 + ed38171 commit c1aa9b9

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

tubesync/sync/views.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,11 +291,36 @@ def get_success_url(self):
291291
url = reverse_lazy('sync:add-source')
292292
fields_to_populate = self.prepopulate_fields.get(self.source_type)
293293
fields = {}
294+
value = self.key
295+
use_channel_id = (
296+
'youtube-channel' == self.source_type_str and
297+
'@' == self.key[0]
298+
)
299+
if use_channel_id:
300+
old_key = self.key
301+
old_source_type = self.source_type
302+
old_source_type_str = self.source_type_str
303+
304+
self.source_type_str = 'youtube-channel-id'
305+
self.source_type = self.source_types.get(self.source_type_str, None)
306+
index_url = Source.create_index_url(self.source_type, self.key, 'videos')
307+
try:
308+
self.key = youtube.get_channel_id(
309+
index_url.replace('/channel/', '/')
310+
)
311+
except youtube.YouTubeError as e:
312+
# It did not work, revert to previous behavior
313+
self.key = old_key
314+
self.source_type = old_source_type
315+
self.source_type_str = old_source_type_str
316+
294317
for field in fields_to_populate:
295318
if field == 'source_type':
296319
fields[field] = self.source_type
297-
elif field in ('key', 'name', 'directory'):
320+
elif field == 'key':
298321
fields[field] = self.key
322+
elif field in ('name', 'directory'):
323+
fields[field] = value
299324
return append_uri_params(url, fields)
300325

301326

tubesync/sync/youtube.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,32 @@ def get_yt_opts():
4545
opts.update({'cookiefile': cookie_file_path})
4646
return opts
4747

48+
def get_channel_id(url):
49+
# yt-dlp --simulate --no-check-formats --playlist-items 1
50+
# --print 'pre_process:%(playlist_channel_id,playlist_id,channel_id)s'
51+
opts = get_yt_opts()
52+
opts.update({
53+
'skip_download': True,
54+
'simulate': True,
55+
'logger': log,
56+
'extract_flat': True, # Change to False to get detailed info
57+
'check_formats': False,
58+
'playlist_items': '1',
59+
})
60+
61+
with yt_dlp.YoutubeDL(opts) as y:
62+
try:
63+
response = y.extract_info(url, download=False)
64+
except yt_dlp.utils.DownloadError as e:
65+
raise YouTubeError(f'Failed to extract channel ID for "{url}": {e}') from e
66+
else:
67+
try:
68+
channel_id = response['channel_id']
69+
except Exception as e:
70+
raise YouTubeError(f'Failed to extract channel ID for "{url}": {e}') from e
71+
else:
72+
return channel_id
73+
4874
def get_channel_image_info(url):
4975
opts = get_yt_opts()
5076
opts.update({

0 commit comments

Comments
 (0)