zdf_mediathek.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #
  2. # This file is part of stov, written by Helmut Pozimski 2012-2017.
  3. #
  4. # stov is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, version 2 of the License.
  7. #
  8. # stov is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with stov. If not, see <http://www.gnu.org/licenses/>.
  15. # -*- coding: utf8 -*-
  16. """ This module implements support for subscriptions from the ZDF Mediathek"""
  17. import json
  18. import logging
  19. import urllib.request
  20. from datetime import datetime, timedelta
  21. from lib_stov import stov_exceptions
  22. LOGGER = logging.getLogger("stov")
  23. class ZDFChannel(object):
  24. """Stores the relevant attributes of a ZDF Mediathek channel"""
  25. def __init__(self, title, videos=None):
  26. if videos is None:
  27. videos = []
  28. self.title = title
  29. self.videos = videos
  30. self.type = "channel"
  31. class ZDFVideo(object):
  32. """Stores the relevant attributes of a single video in the ZDF
  33. Mediathek
  34. """
  35. def __init__(self, title, url):
  36. self.title = title
  37. self.video_id = url
  38. class Connector(object):
  39. """Connector class performing operations against the API"""
  40. def __init__(self, subscription_type, name, conf, search=""):
  41. if subscription_type == "user":
  42. self._type = "channel"
  43. else:
  44. self._type = subscription_type
  45. self._name = name
  46. self._conf = conf
  47. self._search = search
  48. if self._type != "channel":
  49. raise stov_exceptions.TypeNotSupported()
  50. def _fetch_videos(self, existing_videos):
  51. """ Fetches the videos of the day before from the ZDF API and returns
  52. a list of newly added videos.
  53. :param existing_videos: videos that already exist in the database
  54. :type existing_videos: list
  55. :return: List of all newly retrieved videos
  56. :rtype: list
  57. """
  58. name_found = False
  59. videos_list = []
  60. new_videos = []
  61. today = datetime.today()
  62. for i in range(7, -1, -1):
  63. connection = urllib.request.urlopen(
  64. "https://zdf-cdn.live.cellular.de/mediathekV2/broadcast-"
  65. "missed/%s"
  66. % (today-timedelta(days=i)).strftime("%Y-%m-%d"))
  67. data = connection.read().decode("utf-8")
  68. response = json.loads(data)
  69. for cluster in response["broadcastCluster"]:
  70. for broadcast in cluster["teaser"]:
  71. try:
  72. name_found = self._name in broadcast["brandTitle"]
  73. except KeyError:
  74. name_found = self._name in broadcast["headline"]
  75. if name_found:
  76. if self._search:
  77. if self._search in broadcast["titel"]:
  78. new_videos.append((broadcast["sharingUrl"],
  79. broadcast["titel"]))
  80. else:
  81. new_videos.append((broadcast["sharingUrl"],
  82. broadcast["titel"]))
  83. if new_videos:
  84. for broadcast in new_videos:
  85. video_exists = False
  86. if existing_videos:
  87. for existing_video in existing_videos:
  88. if broadcast[0] == existing_video.site_id:
  89. video_exists = True
  90. break
  91. if not video_exists:
  92. videos_list.append(ZDFVideo(broadcast[1], broadcast[0]))
  93. return videos_list
  94. def parse_api_data(self, existing_videos):
  95. """ Takes the existing videos passed to it and wraps them into a
  96. channel object.
  97. :param existing_videos: list of existing_videos
  98. :type existing_videos: list
  99. :return: Channel object
  100. :rtype: ZDFChannel
  101. """
  102. videos = self._fetch_videos(existing_videos)
  103. channel = ZDFChannel(self._name, videos)
  104. return channel
  105. @staticmethod
  106. def construct_video_url(url):
  107. """
  108. Compatibility method, just returns the url
  109. :param url: The url to return
  110. :type url: str
  111. :return: url
  112. :rtype: str
  113. """
  114. return url
  115. @staticmethod
  116. def get_quality_parameter(config):
  117. """
  118. Determines which quality value results from codec and resolution
  119. settings and returns it
  120. :param config: configuration object
  121. :type config: lib_stov.configuration.Conf
  122. :return: itag value
  123. :rtype: str
  124. """
  125. LOGGER.debug(_("Trying to determine the itag value for youtube-dl from"
  126. " your quality and codec settings."))
  127. quality_value = ""
  128. if config.values["videocodec"] == "flv":
  129. if config.values["maxresolution"] == "480p":
  130. quality_value = "hds-1489"
  131. elif config.values["videocodec"] == "mp4":
  132. if config.values["maxresolution"] == "720p":
  133. quality_value = "hls-3286"
  134. if quality_value:
  135. LOGGER.debug(_("Found value: %s."), quality_value)
  136. return quality_value + "/" + config.values["videocodec"]
  137. else:
  138. LOGGER.debug(_("Could not determine an itag value "
  139. "from the configuration"))
  140. return "hls-3286" + "/" + config.values["videocodec"]