2020-05-29 06:42:11 +12:00
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import urllib.request
|
2021-02-06 21:35:50 +13:00
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
from bs4 import BeautifulSoup
|
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
from src.downloaders.downloaderUtils import getExtension, getFile
|
2020-05-29 06:42:11 +12:00
|
|
|
from src.downloaders.gifDeliveryNetwork import GifDeliveryNetwork
|
2021-02-06 21:35:50 +13:00
|
|
|
from src.errors import NotADownloadableLinkError
|
|
|
|
from src.utils import GLOBAL
|
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2020-05-29 06:42:11 +12:00
|
|
|
class Gfycat:
|
2021-02-06 21:35:50 +13:00
|
|
|
def __init__(self, directory, post):
|
2020-05-29 06:42:11 +12:00
|
|
|
try:
|
2021-02-06 21:35:50 +13:00
|
|
|
post['MEDIAURL'] = self.getLink(post['CONTENTURL'])
|
2020-05-29 06:42:11 +12:00
|
|
|
except IndexError:
|
|
|
|
raise NotADownloadableLinkError("Could not read the page source")
|
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
post['EXTENSION'] = getExtension(post['MEDIAURL'])
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
if not os.path.exists(directory):
|
|
|
|
os.makedirs(directory)
|
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
filename = GLOBAL.config['filename'].format(**post) + post["EXTENSION"]
|
|
|
|
short_filename = post['POSTID'] + post['EXTENSION']
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
getFile(filename, short_filename, directory, post['MEDIAURL'])
|
2020-05-29 06:42:11 +12:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def getLink(url):
|
|
|
|
"""Extract direct link to the video from page's source
|
|
|
|
and return it
|
|
|
|
"""
|
|
|
|
if '.webm' in url or '.mp4' in url or '.gif' in url:
|
|
|
|
return url
|
|
|
|
|
|
|
|
if url[-1:] == '/':
|
|
|
|
url = url[:-1]
|
|
|
|
|
|
|
|
url = "https://gfycat.com/" + url.split('/')[-1]
|
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
page_source = (urllib.request.urlopen(url).read().decode())
|
2020-05-29 06:42:11 +12:00
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
soup = BeautifulSoup(page_source, "html.parser")
|
|
|
|
attributes = {"data-react-helmet": "true", "type": "application/ld+json"}
|
2021-02-25 22:32:06 +13:00
|
|
|
content = soup.find("script", attrs=attributes)
|
2020-05-29 06:42:11 +12:00
|
|
|
|
|
|
|
if content is None:
|
|
|
|
return GifDeliveryNetwork.getLink(url)
|
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
return json.loads(content.contents[0])["video"]["contentUrl"]
|