Add support for captions in Reddit albums

Albums with captions:
- https://redd.it/zlu89r
- https://redd.it/tejlvr
- https://redd.it/teju6i
- https://redd.it/tepyv9

Album with only one caption: https://redd.it/zmhu48
Album with no caption: https://redd.it/t3urgf
This commit is contained in:
blankie 2022-12-15 17:19:05 +07:00
parent a4519a1089
commit 82d662363c
Signed by: blankie
GPG Key ID: CC15FC822C7F61F5
1 changed files with 20 additions and 14 deletions

View File

@ -402,20 +402,26 @@ async def main():
elif getattr(random_post, 'is_gallery', None):
files = []
captions = []
if getattr(random_post, 'gallery_data', None):
gallery_keys = map(lambda i: i[1], sorted(map(lambda i: (i['id'], i['media_id']), random_post.gallery_data['items']), key=lambda i: i[0]))
else:
gallery_keys = random_post.media_metadata.keys()
for a, i in enumerate(gallery_keys):
i = random_post.media_metadata[i]
if i['status'] == 'valid':
filename = os.path.join(tempdir, str(time.time()))
for j in ('u', 'mp4', 'gif'):
if j in i['s']:
await _download_file(filename, i['s'][j])
break
captions.append(f'{text}\n#{a + 1}')
files.append(filename)
gallery_data = sorted(random_post.gallery_data['items'], key=lambda i: i['id'])
# no enumerate() because we want to update the count only if the media's status is valid
count = 1
for gallery_data_item in gallery_data:
media_metadata_item = random_post.media_metadata[gallery_data_item['media_id']]
if media_metadata_item['status'] != 'valid':
continue
filename = os.path.join(tempdir, str(time.time()))
for media_type in ('u', 'mp4', 'gif'):
if media_type not in media_metadata_item['s']:
continue
await _download_file(filename, media_metadata_item['s'][media_type])
break
caption = f'{text}\n#{count}'
real_caption = (gallery_data_item.get('caption') or '').strip()
if real_caption:
caption += f': {html.escape(real_caption)}'
captions.append(caption)
files.append(filename)
count += 1
url = None
if url:
parsed = list(urlparse(url))