1
0

noapi.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #
  2. # This file is part of stov, written by Helmut Pozimski 2012-2015.
  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. from __future__ import unicode_literals
  17. import subprocess
  18. import sys
  19. import lxml.html
  20. if sys.version_info >= (3,):
  21. import urllib.request as urllib2
  22. else:
  23. import urllib2
  24. from lib_stov import stov_exceptions
  25. class YtChannel(object):
  26. def __init__(self):
  27. self.title = ""
  28. self.videos = []
  29. class YtVideo(object):
  30. def __init__(self, title, description, ytid):
  31. self.title = title
  32. self.description = description
  33. self.ytid = ytid
  34. class Connector(object):
  35. """This class will retrieve all the necessary data from youtube using
  36. youtube-dl, thus bypassing the API.
  37. """
  38. def __init__(self, type, name, conf, search=""):
  39. """Populates the object with all necessary data."""
  40. self._type = type
  41. self._name = name
  42. self._search = search
  43. self._conf = conf
  44. self._title = ""
  45. self._url = ""
  46. self._construct_url()
  47. def _construct_url(self):
  48. if self._type == "channel":
  49. self._url = "https://www.youtube.com/user/%s" \
  50. % urllib2.quote(self._name)
  51. elif self._type == "search":
  52. self._url = "https://www.youtube.com/results?search_query=%s"\
  53. % urllib2.quote(self._search)
  54. elif self._type == "playlist":
  55. self._url = "https://www.youtube.com/playlist?list=%s" \
  56. % urllib2.quote(self._name)
  57. def _fetch_title(self):
  58. """Retrieves the title of the HTML page to use as a title for the
  59. subscription."""
  60. data = urllib2.urlopen(self._url)
  61. parsed_html = lxml.html.parse(data)
  62. data.close()
  63. i = 0
  64. for item in parsed_html.iter("title"):
  65. if i == 0:
  66. self._title = item.text_content().strip().replace("\n", "")
  67. i += 1
  68. if self._search != "" and self._type == "channel":
  69. self._title += _(" search %s") % self._search
  70. def _fetch_videos(self, existing_videos):
  71. """Retrieves all the relevant videos in a subscription."""
  72. videos_list = []
  73. if self._conf.outputlevel == "verbose":
  74. stderr = sys.stderr
  75. else:
  76. stderr = open("/dev/null", "w")
  77. if self._type == "channel" and self._search != "":
  78. try:
  79. video_ids = subprocess.check_output([
  80. self._conf.values["youtube-dl"],
  81. "--max-downloads",
  82. self._conf.values["maxvideos"],
  83. "--match-title",
  84. self._search,
  85. "--get-id",
  86. self._url], stderr=stderr).strip()
  87. except subprocess.CalledProcessError as e:
  88. video_ids = e.output.strip()
  89. else:
  90. try:
  91. video_ids = subprocess.check_output([
  92. self._conf.values["youtube-dl"], "--max-downloads",
  93. self._conf.values["maxvideos"], "--get-id",
  94. self._url], stderr=stderr).strip()
  95. except subprocess.CalledProcessError as e:
  96. video_ids = e.output.strip()
  97. if len(video_ids) >= 1:
  98. for video_id in video_ids.split("\n"):
  99. video_exists = False
  100. if existing_videos:
  101. for existing_video in existing_videos:
  102. if video_id == existing_video.ytid:
  103. video_exists = True
  104. break
  105. if not video_exists:
  106. try:
  107. video_title = subprocess.check_output([
  108. self._conf.values["youtube-dl"], "--get-title",
  109. "https://www.youtube.com/watch?v=%s"
  110. % video_id], stderr=stderr).strip()
  111. video_description = subprocess.check_output([
  112. self._conf.values["youtube-dl"], "--get-description",
  113. "https://www.youtube.com/watch?v=%s"
  114. % video_id], stderr=stderr).strip()
  115. except subprocess.CalledProcessError:
  116. raise stov_exceptions.YoutubeDlCallFailed()
  117. else:
  118. videos_list.append(YtVideo(
  119. unicode(video_title, "utf-8"),
  120. unicode(video_description, "utf-8"),
  121. unicode(video_id)))
  122. return videos_list
  123. def ParseAPIData(self, existing_videos):
  124. """This method calls all necessary methods to retrieve the data
  125. and assembles them into a Channel object. The naming of this
  126. method was set according to the method in youtubeAPI to be
  127. compatible.
  128. """
  129. self._fetch_title()
  130. videos = self._fetch_videos(existing_videos)
  131. channel = YtChannel()
  132. channel.title = unicode(self._title)
  133. channel.videos = videos
  134. return channel