2021-02-07 17:46:20 +13:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
import json
|
2021-03-20 01:28:41 +13:00
|
|
|
import re
|
2021-02-25 23:40:08 +13:00
|
|
|
from typing import Optional
|
2021-02-06 21:35:50 +13:00
|
|
|
|
2021-02-11 12:10:40 +13:00
|
|
|
from praw.models import Submission
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-04-23 23:06:16 +12:00
|
|
|
from bdfr.exceptions import SiteDownloaderError
|
2021-04-12 19:58:32 +12:00
|
|
|
from bdfr.resource import Resource
|
|
|
|
from bdfr.site_authenticator import SiteAuthenticator
|
2021-04-28 20:50:18 +12:00
|
|
|
from bdfr.site_downloaders.base_downloader import BaseDownloader
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-04-28 20:50:18 +12:00
|
|
|
class Redgifs(BaseDownloader):
|
2021-02-15 18:12:27 +13:00
|
|
|
def __init__(self, post: Submission):
|
|
|
|
super().__init__(post)
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2021-02-26 21:57:05 +13:00
|
|
|
def find_resources(self, authenticator: Optional[SiteAuthenticator] = None) -> list[Resource]:
|
2021-04-28 20:50:18 +12:00
|
|
|
media_url = self._get_link(self.post.url)
|
2021-07-27 16:02:30 +12:00
|
|
|
return [Resource(self.post, media_url, Resource.retry_download(media_url), '.mp4')]
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
@staticmethod
|
2021-02-07 17:46:20 +13:00
|
|
|
def _get_link(url: str) -> str:
|
2021-04-06 13:04:08 +12:00
|
|
|
try:
|
|
|
|
redgif_id = re.match(r'.*/(.*?)/?$', url).group(1)
|
|
|
|
except AttributeError:
|
|
|
|
raise SiteDownloaderError(f'Could not extract Redgifs ID from {url}')
|
|
|
|
|
2021-04-05 19:21:04 +12:00
|
|
|
headers = {
|
2021-04-28 20:37:49 +12:00
|
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
|
2021-04-28 20:30:26 +12:00
|
|
|
'Chrome/90.0.4430.93 Safari/537.36',
|
2021-04-05 19:21:04 +12:00
|
|
|
}
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-04-28 20:37:49 +12:00
|
|
|
content = Redgifs.retrieve_url(f'https://api.redgifs.com/v1/gfycats/{redgif_id}', headers=headers)
|
2020-05-29 06:42:11 +12:00
|
|
|
|
|
|
|
if content is None:
|
2021-04-06 13:04:08 +12:00
|
|
|
raise SiteDownloaderError('Could not read the page source')
|
|
|
|
|
|
|
|
try:
|
2021-04-28 20:37:49 +12:00
|
|
|
out = json.loads(content.text)['gfyItem']['mp4Url']
|
|
|
|
except (KeyError, AttributeError):
|
2021-04-06 13:04:08 +12:00
|
|
|
raise SiteDownloaderError('Failed to find JSON data in page')
|
|
|
|
except json.JSONDecodeError as e:
|
|
|
|
raise SiteDownloaderError(f'Received data was not valid JSON: {e}')
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-03-20 01:28:41 +13:00
|
|
|
return out
|