1
0
mirror of https://github.com/spaam/svtplay-dl.git synced 2024-11-27 21:54:17 +01:00
svtplay-dl/lib/svtplay_dl/service/svtplay.py

336 lines
12 KiB
Python
Raw Normal View History

2013-03-02 21:26:28 +01:00
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
2014-06-07 20:43:40 +02:00
import copy
import datetime
2019-08-25 00:27:31 +02:00
import hashlib
import json
2018-11-18 12:47:19 +01:00
import logging
2019-08-25 00:40:39 +02:00
import re
import time
2019-08-25 00:40:39 +02:00
from urllib.parse import parse_qs
from urllib.parse import urljoin
from urllib.parse import urlparse
2019-08-25 00:40:39 +02:00
from svtplay_dl.error import ServiceError
2016-03-26 21:38:31 +01:00
from svtplay_dl.fetcher.dash import dashparse
2019-08-25 00:40:39 +02:00
from svtplay_dl.fetcher.hls import hlsparse
from svtplay_dl.service import MetadataThumbMixin
from svtplay_dl.service import Service
from svtplay_dl.subtitle import subtitle
2019-08-25 00:40:39 +02:00
from svtplay_dl.utils.text import filenamify
URL_VIDEO_API = "https://api.svt.se/video/"
LIVE_CHANNELS = {
"svtbarn": "ch-barnkanalen",
"svt1": "ch-svt1",
"svt2": "ch-svt2",
"svt24": "ch-svt24",
"kunskapskanalen": "ch-kunskapskanalen",
}
2015-09-15 20:10:32 +02:00
2018-01-30 20:11:37 +01:00
class Svtplay(Service, MetadataThumbMixin):
2019-08-25 00:27:31 +02:00
supported_domains = ["svtplay.se", "svt.se", "beta.svtplay.se", "svtflow.se"]
info_search_expr = r"<script id=\"__NEXT_DATA__\" type=\"application\/json\">({.+})<\/script>"
def get(self):
parse = urlparse(self.url)
if parse.netloc == "www.svtplay.se" or parse.netloc == "svtplay.se":
if parse.path[:6] != "/video" and parse.path[:6] != "/klipp" and parse.path[:8] != "/kanaler":
yield ServiceError("This mode is not supported anymore. Need the url with the video.")
return
query = parse_qs(parse.query)
self.access = None
if "accessService" in query:
self.access = query["accessService"]
urldata = self.get_urldata()
2018-01-07 20:52:19 +01:00
if parse.path[:8] == "/kanaler":
ch = LIVE_CHANNELS[parse.path[parse.path.rfind("/") + 1 :]]
_url = urljoin(URL_VIDEO_API, ch)
res = self.http.get(_url)
2018-01-07 20:52:19 +01:00
try:
janson = res.json()
except json.decoder.JSONDecodeError:
2021-02-28 22:05:15 +01:00
yield ServiceError(f"Can't decode api request: {res.request.url}")
2018-01-07 20:52:19 +01:00
return
videos = self._get_video(janson)
2018-05-08 22:46:11 +02:00
self.config.set("live", True)
2019-08-25 00:33:51 +02:00
yield from videos
2018-01-07 20:52:19 +01:00
return
match = re.search(self.info_search_expr, urldata)
if not match:
yield ServiceError("Can't find video info.")
return
janson = json.loads(match.group(1))
video_data = None
vid = None
for data_entry in janson["props"]["urqlState"].values():
if "data" in data_entry:
entry = json.loads(data_entry["data"])
for key, data in entry.items():
if key == "detailsPage" and data and "moreDetails" in data:
video_data = data
vid = data["video"]["svtId"]
break
2021-03-12 00:12:34 +01:00
if not vid:
yield ServiceError("Can't find video id")
return
self.outputfilename(video_data)
self.extrametadata(video_data)
2018-01-07 20:52:19 +01:00
res = self.http.get(URL_VIDEO_API + vid)
try:
janson = res.json()
except json.decoder.JSONDecodeError:
2021-02-28 22:05:15 +01:00
yield ServiceError(f"Can't decode api request: {res.request.url}")
return
2017-05-08 00:14:05 +02:00
videos = self._get_video(janson)
2019-08-25 00:33:51 +02:00
yield from videos
2017-05-08 00:14:05 +02:00
def _get_video(self, janson):
if "subtitleReferences" in janson:
for i in janson["subtitleReferences"]:
if i["format"] == "webvtt" and "url" in i:
yield subtitle(copy.copy(self.config), "wrst", i["url"], output=self.output)
if "videoReferences" in janson:
if len(janson["videoReferences"]) == 0:
yield ServiceError("Media doesn't have any associated videos.")
return
for i in janson["videoReferences"]:
if i["url"].find(".m3u8") > 0:
yield from hlsparse(self.config, self.http.request("get", i["url"]), i["url"], self.output)
elif i["url"].find(".mpd") > 0:
yield from dashparse(self.config, self.http.request("get", i["url"]), i["url"], output=self.output)
2021-03-12 00:12:34 +01:00
def _last_chance(self):
videos = []
match = re.search(self.info_search_expr, self.get_urldata())
if not match:
logging.error("Can't find video info.")
return
janson = json.loads(match.group(1))
video_data = None
for data_entry in janson["props"]["urqlState"].values():
entry = json.loads(data_entry["data"])
2021-03-12 00:12:34 +01:00
for key, data in entry.items():
if key == "startForSvtPlay":
video_data = data
if not video_data:
return videos
2021-03-12 00:12:34 +01:00
for i in video_data["selections"][0]["items"]:
videos.append(i["item"]["urls"]["svtplay"])
return videos
2018-05-13 13:06:45 +02:00
def find_all_episodes(self, config):
parse = urlparse(self._url)
2017-05-07 14:47:15 +02:00
videos = []
tab = None
if parse.query:
query = parse_qs(parse.query)
if "tab" in query:
tab = query["tab"][0]
if re.search("sista-chansen", parse.path):
2021-03-12 00:12:34 +01:00
videos = self._last_chance()
else:
match = re.search(self.info_search_expr, self.get_urldata())
if not match:
logging.error("Can't find video info.")
return
janson = json.loads(match.group(1))
2021-03-12 00:12:34 +01:00
video_data = None
for data_entry in janson["props"]["urqlState"].values():
2021-04-14 08:22:09 +02:00
if "data" in data_entry:
entry = json.loads(data_entry["data"])
for key, data in entry.items():
if key == "detailsPage" and data and "heading" in data:
video_data = data
break
collections = []
videos = []
2021-03-12 00:12:34 +01:00
for i in video_data["associatedContent"]:
if tab:
if tab == i["id"]:
collections.append(i)
else:
if i["id"] == "upcoming":
continue
elif self.config.get("include_clips") and "clips" in i["id"]:
collections.append(i)
elif "clips" not in i["id"]:
collections.append(i)
if not collections:
logging.error("Can't find other episodes.")
for i in collections:
for epi in i["items"]:
if epi["item"]["urls"]["svtplay"] not in videos:
videos.append(epi["item"]["urls"]["svtplay"])
episodes = [urljoin("http://www.svtplay.se", x) for x in videos]
2018-05-13 13:06:45 +02:00
if config.get("all_last") > 0:
2019-08-25 00:27:31 +02:00
return episodes[-config.get("all_last") :]
return episodes
2018-05-13 13:06:45 +02:00
def outputfilename(self, data):
name = None
2018-05-13 13:06:45 +02:00
desc = None
2021-03-12 00:12:34 +01:00
name = data["moreDetails"]["heading"]
other = data["moreDetails"]["episodeHeading"]
vid = data["video"]["svtId"]
2018-01-13 20:27:40 +01:00
id = hashlib.sha256(vid.encode("utf-8")).hexdigest()[:7]
if name == other:
other = None
2017-02-15 23:15:50 +01:00
elif name is None:
name = other
other = None
elif other is None:
other = data["moreDetails"]["titleHeading"]
2018-05-13 13:06:45 +02:00
season, episode = self.seasoninfo(data)
if "accessibility" in data:
if data["accessibility"] == "AudioDescribed":
2018-05-13 13:06:45 +02:00
desc = "syntolkat"
if data["accessibility"] == "SignInterpreted":
2018-05-13 13:06:45 +02:00
desc = "teckentolkat"
if not other:
other = desc
2018-05-12 15:42:05 +02:00
elif desc:
2021-02-28 22:05:15 +01:00
other += f"-{desc}"
2018-05-13 13:06:45 +02:00
self.output["title"] = filenamify(name)
2018-05-13 13:06:45 +02:00
self.output["id"] = id
self.output["season"] = season
self.output["episode"] = episode
self.output["episodename"] = other
def seasoninfo(self, data):
season, episode = None, None
season_nr = self._find_season(data)
episode_nr = self._find_episode(data)
if season_nr is None or episode_nr is None:
return season, episode
2021-04-27 19:44:09 +02:00
season = f"{int(season_nr):02d}"
episode = f"{int(episode_nr):02d}"
return season, episode
def _find_season(self, data):
match = re.search(r"/säsong (\d+)/", data["analyticsIdentifiers"]["viewId"])
if match:
return match.group(1)
match = re.search(r"-sasong-(\d+)-", data["item"]["urls"]["svtplay"])
if match:
return match.group(1)
vid = data["video"]["svtId"]
for seasons in data["associatedContent"]:
for i in seasons["items"]:
if i["item"]["videoSvtId"] == vid and "positionInSeason" in i["item"]:
match = re.search(r"S.song (\d+)", i["item"]["positionInSeason"])
if match:
return match.group(1)
return None
def _find_episode(self, data):
match = re.search(r"/avsnitt (\d+)", data["analyticsIdentifiers"]["viewId"])
if match:
return match.group(1)
match = re.search(r"Avsnitt (\d+)", data["item"]["name"])
if match:
return match.group(1)
vid = data["video"]["svtId"]
for seasons in data["associatedContent"]:
for i in seasons["items"]:
if i["item"]["videoSvtId"] == vid and "positionInSeason" in i["item"]:
match = re.search(r"Avsnitt (\d+)", i["item"]["positionInSeason"])
if match:
return match.group(1)
if "description" in data:
match = re.search(r"Del (\d+) av (\d+)", data["description"])
if match:
return match.group(1)
return None
def extrametadata(self, episode):
self.output["tvshow"] = self.output["season"] is not None and self.output["episode"] is not None
if "validFrom" in episode:
def _fix_broken_timezone_implementation(value):
# cx_freeze cant include .zip file for dateutil and < py37 have issues with timezones with : in it
2019-09-29 23:45:16 +02:00
if "+" in value and ":" == value[-3:-2]:
value = value[:-3] + value[-2:]
return value
2021-03-12 00:12:34 +01:00
validfrom = episode["item"]["validFrom"]
2019-09-29 23:45:16 +02:00
if "+" in validfrom:
date = time.mktime(
datetime.datetime.strptime(
2021-03-12 00:12:34 +01:00
_fix_broken_timezone_implementation(episode["item"]["validFrom"].replace("Z", "")),
2020-12-26 13:10:56 +01:00
"%Y-%m-%dT%H:%M:%S%z",
).timetuple(),
)
2019-09-29 23:45:16 +02:00
else:
date = time.mktime(
datetime.datetime.strptime(
2021-03-12 00:12:34 +01:00
_fix_broken_timezone_implementation(episode["item"]["validFrom"].replace("Z", "")),
2020-12-26 13:10:56 +01:00
"%Y-%m-%dT%H:%M:%S",
).timetuple(),
2019-09-29 23:45:16 +02:00
)
self.output["publishing_datetime"] = int(date)
2021-03-12 00:12:34 +01:00
self.output["title_nice"] = episode["moreDetails"]["heading"]
try:
2021-03-12 00:12:34 +01:00
t = episode["item"]["parent"]["image"]["wide"]
except KeyError:
t = ""
if isinstance(t, dict):
url = "https://www.svtstatic.se/image/original/default/{id}/{changed}?format=auto&quality=100".format(**t)
self.output["showthumbnailurl"] = url
elif t:
# Get the image if size/format is not specified in the URL set it to large
url = t.format(format="large")
self.output["showthumbnailurl"] = url
try:
2021-03-12 00:12:34 +01:00
t = episode["images"]["wide"]
2018-07-22 11:46:15 +02:00
except KeyError:
t = ""
if isinstance(t, dict):
url = "https://www.svtstatic.se/image/original/default/{id}/{changed}?format=auto&quality=100".format(**t)
self.output["episodethumbnailurl"] = url
elif t:
# Get the image if size/format is not specified in the URL set it to large
url = t.format(format="large")
self.output["episodethumbnailurl"] = url
2021-03-12 00:12:34 +01:00
if "longDescription" in episode["item"]["parent"]:
self.output["showdescription"] = episode["item"]["parent"]["longDescription"]
2021-03-12 00:12:34 +01:00
if "description" in episode:
self.output["episodedescription"] = episode["description"]