subscription.py 12 KB

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