subscription.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. #
  2. # This file is part of stov, written by Helmut Pozimski in 2012.
  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 sys
  18. import gettext
  19. import sqlite3
  20. if sys.version_info >= (3,):
  21. import urllib.request as urllib2
  22. else:
  23. import urllib2
  24. import youtubeAPI
  25. import youtube
  26. from outputhelper import printf
  27. class sub(object):
  28. def __init__(self, type, name, conf, search="", id=0, title="", directory=""):
  29. self.__ID = id
  30. self.__title = title
  31. self.__type = type
  32. self.__name = name
  33. self.__search = search
  34. self.__directory = directory
  35. self.__APIURL = ""
  36. self.__conf = conf
  37. self.DownloadedVideos = []
  38. self.FailedVideos = 0
  39. if self.__name != "delete":
  40. self.__ConstructAPIURL()
  41. def GetTitle(self):
  42. return self.__title
  43. def Delete(self):
  44. """Deletes all videos from the subscription from the database and deletes
  45. the subscription itself once it's done.
  46. """
  47. try:
  48. self.__connection = sqlite3.connect(self.__conf.dbpath)
  49. except sqlite3.OperationalError:
  50. printf(_("Could not write to database, subscription "
  51. "was NOT deleted. Please check permissions and try again."),
  52. outputlevel="default", level=self.__conf.outputlevel, descriptor="stderr")
  53. else:
  54. self.__cursor = self.__connection.cursor()
  55. self.__deletevideos = "DELETE FROM videos WHERE subscription_id=?"
  56. self.__cursor.execute(self.__deletevideos, (self.__ID,))
  57. self.__deletesubscription = "DELETE FROM subscriptions WHERE id=?"
  58. self.__cursor.execute(self.__deletesubscription, (self.__ID,))
  59. self.__connection.commit()
  60. printf(_("Subscription deleted successfully!"), outputlevel="default",
  61. level=self.__conf.outputlevel, descriptor="stdout")
  62. self.__connection.close()
  63. def UpdateVideos(self):
  64. """Retrieves the current videos from the youtube API and adds them
  65. to the database if they where not already added earlier
  66. """
  67. self.__ParseAPIData()
  68. self.__processed = []
  69. try:
  70. self.__connection = sqlite3.connect(self.__conf.dbpath)
  71. self.__cursor = self.__connection.cursor()
  72. except sqlite3.OperationalError:
  73. printf(_("Could not write to database, "
  74. "new video was NOT added! Please check permissions and try again."),
  75. outputlevel="default", level=self.__conf.outputlevel, descriptor="stderr")
  76. for i in self.__ParsedResponse.videos:
  77. printf(_('Checking if video "%s" exists in the database') % i.title,
  78. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  79. self.__ytid = i.ytid
  80. if self.__search != "" and self.__conf.values["check_title"] == "yes":
  81. if self.__search not in i.title:
  82. printf(_("You have requested title checking and the title of the video "
  83. "does not match with the search string, ignoring it"),
  84. outputlevel="verbose", level=self.__conf.outputlevel,
  85. descriptor="stderr")
  86. continue
  87. self.__videoquery = "SELECT id FROM videos WHERE ytid=?"
  88. self.__cursor.execute(self.__videoquery, (self.__ytid,))
  89. self.__tmpid = self.__cursor.fetchall()
  90. if self.__tmpid == []:
  91. printf(_("Video %s not found in database, inserting...") % i.title,
  92. outputlevel="verbose", level=self.__conf.outputlevel,
  93. descriptor="stderr")
  94. self.__query = "INSERT INTO videos (title, description, \
  95. ytid, subscription_id, downloaded) VALUES (?, ?, ?, ?, ?)"
  96. self.__data = (i.title, i.description, self.__ytid, self.__ID, 0)
  97. self.__cursor.execute(self.__query, self.__data)
  98. self.__connection.commit()
  99. self.__connection.close()
  100. def GetVideos(self):
  101. """Retrieves all videos in the subscription from the database and saves
  102. them in an the internal list so they can be accessed by the object
  103. """
  104. self.__videos = []
  105. try:
  106. self.__connection = sqlite3.connect(self.__conf.dbpath)
  107. self.__cursor = self.__connection.cursor()
  108. except sqlite3.OperationalError:
  109. printf(_("Could not access database. "
  110. "Please check permissions and try again."),
  111. outputlevel="default", level=self.__conf.outputlevel, descriptor="stderr")
  112. printf(_("Getting all videos for subscription %s from database")
  113. % self.__title, outputlevel="verbose", level=self.__conf.outputlevel,
  114. descriptor="stderr")
  115. self.__videoquerybysubscription = "SELECT id, title, description, \
  116. ytid, downloaded, failcnt FROM videos WHERE subscription_id=?"
  117. self.__cursor.execute(self.__videoquerybysubscription, (self.__ID,))
  118. self.__videodata = self.__cursor.fetchall()
  119. for i in self.__videodata:
  120. printf(_("Got video %s") % i[1],
  121. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  122. self.__videos.append(youtube.video(id=i[0],
  123. title=i[1], description=i[2], ytid=i[3],
  124. downloaded=i[4], failcount=i[5], conf=self.__conf))
  125. self.__connection.close()
  126. def DownloadVideos(self, itag_value):
  127. """Uses the DownloadVideo method of the video object to download all
  128. videos contained in the subscription and adds them to the list of
  129. downloaded videos if the download succeeds.
  130. """
  131. for video in self.__videos:
  132. if video.downloaded == 0:
  133. if video.DownloadVideo(self.__directory, itag_value) is True:
  134. self.DownloadedVideos.append(video.title)
  135. else:
  136. self.FailedVideos = self.FailedVideos + 1
  137. """Prints a list of all videos contained in the subscription"""
  138. def PrintVideos(self):
  139. printf(_("Videos in subscription ") + self.__title + ":\n",
  140. outputlevel="default", level=self.__conf.outputlevel, descriptor="stdout")
  141. for i in self.__videos:
  142. if i.downloaded == 0:
  143. printf(i.title + _(" (pending)"), outputlevel="default",
  144. level=self.__conf.outputlevel, descriptor="stdout")
  145. elif i.downloaded == 1:
  146. printf(i.title + _(" (downloaded)"), outputlevel="default",
  147. level=self.__conf.outputlevel, descriptor="stdout")
  148. elif i.downloaded == -1:
  149. printf(i.title + _(" (failed)"), outputlevel="default",
  150. level=self.__conf.outputlevel, descriptor="stdout")
  151. def AddSub(self):
  152. """Adds a new subscription to the database"""
  153. self.__ParseAPIData()
  154. try:
  155. self.__connection = sqlite3.connect(self.__conf.dbpath)
  156. except sqlite3.OperationalError:
  157. printf(_("Could not write to database, new "
  158. "subscription was NOT added! Please check permissions and try again."),
  159. outputlevel="default", level=self.__conf.outputlevel, descriptor="stderr")
  160. else:
  161. self.__cursor = self.__connection.cursor()
  162. self.__title = self.__ParsedResponse.title
  163. printf(_("Found subscription title %s") % self.__title,
  164. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  165. self.__directory = self.__name + "_" + self.__search.replace(" ", "_")
  166. printf(_("Directory: %s") % self.__directory,
  167. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  168. self.__query = "INSERT INTO subscriptions (title, type, searchstring, \
  169. directory, name) VALUES (?, ?, ?, ?, ?)"
  170. self.__data = (self.__title, self.__type, self.__search,
  171. self.__directory, self.__name)
  172. printf(_("Writing subscription info into database..."),
  173. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  174. self.__cursor.execute(self.__query, self.__data)
  175. self.__connection.commit()
  176. self.__query = "SELECT id from subscriptions where title=?"
  177. self.__data = (self.__title, )
  178. self.__cursor.execute(self.__query, self.__data)
  179. self.__ID = self.__cursor.fetchone()
  180. self.__ID = self.__ID[0]
  181. printf(_("Subscription got internal ID %s") % self.__ID,
  182. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  183. self.__connection.close()
  184. def __ParseAPIData(self):
  185. """Retrieves the youtube API data and parses them so they can be used
  186. by the object
  187. """
  188. try:
  189. printf(_("Connectiong to youtube API."),
  190. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  191. self.__ConnectAPI = urllib2.urlopen(self.__APIURL)
  192. printf(_("Connection established, reading data."),
  193. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  194. self.__APIResponse = self.__ConnectAPI.read()
  195. self.__ConnectAPI.close()
  196. except IOError:
  197. printf(_("Could not get API data, maybe the API "
  198. "is down or you have given wrong parameters"
  199. ", please check and try again!"),
  200. outputlevel="default", level=self.__conf.outputlevel, descriptor="stderr")
  201. sys.exit(1)
  202. else:
  203. printf(_("Parsing youtube API response."),
  204. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  205. parser = youtubeAPI.Parser(self.__APIResponse)
  206. self.__ParsedResponse = parser.parse()
  207. def __ConstructAPIURL(self):
  208. """Constructs the API URL which is used to retrieve API data"""
  209. if self.__type == "channel":
  210. self.__APIURL = "https://gdata.youtube.com/feeds/api/users/"\
  211. + urllib2.quote(self.__name) + "/uploads/" + "?v=2"\
  212. + "&max-results=%s" % self.__conf.values["maxvideos"]
  213. if self.__search != "":
  214. self.__APIURL = self.__APIURL + "&q=" + "%22"\
  215. + urllib2.quote(self.__search) + "%22"
  216. elif self.__type == "search":
  217. self.__APIURL = "http://gdata.youtube.com/feeds/api/videos?q="\
  218. + urllib2.quote(self.__search) + "&v=2"\
  219. + "&max-results=%s" % self.__conf.values["maxvideos"]
  220. elif self.__type == "playlist":
  221. self.__APIURL = "https://gdata.youtube.com/feeds/api/playlists/"\
  222. + "%20" + urllib2.quote(self.__name) + "%20" + "?v=2"\
  223. + "&max-results=%s" % self.__conf.values["maxvideos"]
  224. else:
  225. printf(_("None or invalid subscription type given, "
  226. "please check the type option and try again"),
  227. outputlevel="default", level=self.__conf.outputlevel, descriptor="stderr")
  228. printf(_("Constructed the following API URL: %s") % self.__APIURL,
  229. outputlevel="verbose", level=self.__conf.outputlevel, descriptor="stderr")
  230. def CheckAndDelete(self):
  231. """Checks if a video still exists in the current API response and deletes
  232. it if it doesn't
  233. """
  234. self.__ParseAPIData()
  235. self.GetVideos()
  236. self.__id_list = []
  237. for entry in self.__ParsedResponse.videos:
  238. self.__id_list.append(entry.ytid)
  239. for item in self.__videos:
  240. if item.ytid not in self.__id_list:
  241. if item.delete() is True:
  242. printf(_("Video %s deleted from the database!") % item.title,
  243. outputlevel="verbose", level=self.__conf.outputlevel,
  244. descriptor="stdout")
  245. else:
  246. printf(_("Videos %s could not be deleted from the database"),
  247. outputlevel="verbose", level=self.__conf.outputlevel,
  248. descriptor="stderr")