PageRenderTime 57ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/gdata/youtube/service.py

http://radioappz.googlecode.com/
Python | 1563 lines | 1510 code | 15 blank | 38 comment | 9 complexity | 5736947e06cf5174243c579adba11b1d MD5 | raw file
  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """YouTubeService extends GDataService to streamline YouTube operations.
  17. YouTubeService: Provides methods to perform CRUD operations on YouTube feeds.
  18. Extends GDataService.
  19. """
  20. __author__ = ('api.stephaniel@gmail.com (Stephanie Liu), '
  21. 'api.jhartmann@gmail.com (Jochen Hartmann)')
  22. try:
  23. from xml.etree import cElementTree as ElementTree
  24. except ImportError:
  25. try:
  26. import cElementTree as ElementTree
  27. except ImportError:
  28. try:
  29. from xml.etree import ElementTree
  30. except ImportError:
  31. from elementtree import ElementTree
  32. import os
  33. import atom
  34. import gdata
  35. import gdata.service
  36. import gdata.youtube
  37. YOUTUBE_SERVER = 'gdata.youtube.com'
  38. YOUTUBE_SERVICE = 'youtube'
  39. YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL = 'https://www.google.com/youtube/accounts/ClientLogin'
  40. YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime',
  41. 'flv', 'mp4', 'x-flv')
  42. YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month',
  43. 'all_time')
  44. YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating',
  45. 'relevance')
  46. YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude')
  47. YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6')
  48. YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured',
  49. 'top_rated', 'most_viewed','watch_on_mobile')
  50. YOUTUBE_UPLOAD_URI = 'http://uploads.gdata.youtube.com/feeds/api/users'
  51. YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken'
  52. YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos'
  53. YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users'
  54. YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists'
  55. YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds'
  56. YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated')
  57. YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  58. 'most_viewed')
  59. YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  60. 'recently_featured')
  61. YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  62. 'watch_on_mobile')
  63. YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  64. 'top_favorites')
  65. YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  66. 'most_recent')
  67. YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  68. 'most_discussed')
  69. YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  70. 'most_linked')
  71. YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS,
  72. 'most_responded')
  73. YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas'
  74. YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA
  75. YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
  76. 'complaint-reasons.cat')
  77. YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA,
  78. 'subscriptiontypes.cat')
  79. YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS',
  80. 'RIGHTS', 'SPAM')
  81. YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected')
  82. YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family')
  83. UNKOWN_ERROR = 1000
  84. YOUTUBE_BAD_REQUEST = 400
  85. YOUTUBE_CONFLICT = 409
  86. YOUTUBE_INTERNAL_SERVER_ERROR = 500
  87. YOUTUBE_INVALID_ARGUMENT = 601
  88. YOUTUBE_INVALID_CONTENT_TYPE = 602
  89. YOUTUBE_NOT_A_VIDEO = 603
  90. YOUTUBE_INVALID_KIND = 604
  91. class Error(Exception):
  92. """Base class for errors within the YouTube service."""
  93. pass
  94. class RequestError(Error):
  95. """Error class that is thrown in response to an invalid HTTP Request."""
  96. pass
  97. class YouTubeError(Error):
  98. """YouTube service specific error class."""
  99. pass
  100. class YouTubeService(gdata.service.GDataService):
  101. """Client for the YouTube service.
  102. Performs all documented Google Data YouTube API functions, such as inserting,
  103. updating and deleting videos, comments, playlist, subscriptions etc.
  104. YouTube Service requires authentication for any write, update or delete
  105. actions.
  106. Attributes:
  107. email: An optional string identifying the user. Required only for
  108. authenticated actions.
  109. password: An optional string identifying the user's password.
  110. source: An optional string identifying the name of your application.
  111. server: An optional address of the YouTube API server. gdata.youtube.com
  112. is provided as the default value.
  113. additional_headers: An optional dictionary containing additional headers
  114. to be passed along with each request. Use to store developer key.
  115. client_id: An optional string identifying your application, required for
  116. authenticated requests, along with a developer key.
  117. developer_key: An optional string value. Register your application at
  118. http://code.google.com/apis/youtube/dashboard to obtain a (free) key.
  119. """
  120. def __init__(self, email=None, password=None, source=None,
  121. server=YOUTUBE_SERVER, additional_headers=None, client_id=None,
  122. developer_key=None, **kwargs):
  123. """Creates a client for the YouTube service.
  124. Args:
  125. email: string (optional) The user's email address, used for
  126. authentication.
  127. password: string (optional) The user's password.
  128. source: string (optional) The name of the user's application.
  129. server: string (optional) The name of the server to which a connection
  130. will be opened. Default value: 'gdata.youtube.com'.
  131. client_id: string (optional) Identifies your application, required for
  132. authenticated requests, along with a developer key.
  133. developer_key: string (optional) Register your application at
  134. http://code.google.com/apis/youtube/dashboard to obtain a (free) key.
  135. **kwargs: The other parameters to pass to gdata.service.GDataService
  136. constructor.
  137. """
  138. gdata.service.GDataService.__init__(
  139. self, email=email, password=password, service=YOUTUBE_SERVICE,
  140. source=source, server=server, additional_headers=additional_headers,
  141. **kwargs)
  142. if client_id is not None:
  143. self.additional_headers['X-Gdata-Client'] = client_id
  144. if developer_key is not None:
  145. self.additional_headers['X-GData-Key'] = 'key=%s' % developer_key
  146. self.auth_service_url = YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL
  147. def GetYouTubeVideoFeed(self, uri):
  148. """Retrieve a YouTubeVideoFeed.
  149. Args:
  150. uri: A string representing the URI of the feed that is to be retrieved.
  151. Returns:
  152. A YouTubeVideoFeed if successfully retrieved.
  153. """
  154. return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
  155. def GetYouTubeVideoEntry(self, uri=None, video_id=None):
  156. """Retrieve a YouTubeVideoEntry.
  157. Either a uri or a video_id must be provided.
  158. Args:
  159. uri: An optional string representing the URI of the entry that is to
  160. be retrieved.
  161. video_id: An optional string representing the ID of the video.
  162. Returns:
  163. A YouTubeVideoFeed if successfully retrieved.
  164. Raises:
  165. YouTubeError: You must provide at least a uri or a video_id to the
  166. GetYouTubeVideoEntry() method.
  167. """
  168. if uri is None and video_id is None:
  169. raise YouTubeError('You must provide at least a uri or a video_id '
  170. 'to the GetYouTubeVideoEntry() method')
  171. elif video_id and not uri:
  172. uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id)
  173. return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
  174. def GetYouTubeContactFeed(self, uri=None, username='default'):
  175. """Retrieve a YouTubeContactFeed.
  176. Either a uri or a username must be provided.
  177. Args:
  178. uri: An optional string representing the URI of the contact feed that
  179. is to be retrieved.
  180. username: An optional string representing the username. Defaults to the
  181. currently authenticated user.
  182. Returns:
  183. A YouTubeContactFeed if successfully retrieved.
  184. Raises:
  185. YouTubeError: You must provide at least a uri or a username to the
  186. GetYouTubeContactFeed() method.
  187. """
  188. if uri is None:
  189. uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts')
  190. return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString)
  191. def GetYouTubeContactEntry(self, uri):
  192. """Retrieve a YouTubeContactEntry.
  193. Args:
  194. uri: A string representing the URI of the contact entry that is to
  195. be retrieved.
  196. Returns:
  197. A YouTubeContactEntry if successfully retrieved.
  198. """
  199. return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString)
  200. def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None):
  201. """Retrieve a YouTubeVideoCommentFeed.
  202. Either a uri or a video_id must be provided.
  203. Args:
  204. uri: An optional string representing the URI of the comment feed that
  205. is to be retrieved.
  206. video_id: An optional string representing the ID of the video for which
  207. to retrieve the comment feed.
  208. Returns:
  209. A YouTubeVideoCommentFeed if successfully retrieved.
  210. Raises:
  211. YouTubeError: You must provide at least a uri or a video_id to the
  212. GetYouTubeVideoCommentFeed() method.
  213. """
  214. if uri is None and video_id is None:
  215. raise YouTubeError('You must provide at least a uri or a video_id '
  216. 'to the GetYouTubeVideoCommentFeed() method')
  217. elif video_id and not uri:
  218. uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments')
  219. return self.Get(
  220. uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString)
  221. def GetYouTubeVideoCommentEntry(self, uri):
  222. """Retrieve a YouTubeVideoCommentEntry.
  223. Args:
  224. uri: A string representing the URI of the comment entry that is to
  225. be retrieved.
  226. Returns:
  227. A YouTubeCommentEntry if successfully retrieved.
  228. """
  229. return self.Get(
  230. uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString)
  231. def GetYouTubeUserFeed(self, uri=None, username=None):
  232. """Retrieve a YouTubeVideoFeed of user uploaded videos
  233. Either a uri or a username must be provided. This will retrieve list
  234. of videos uploaded by specified user. The uri will be of format
  235. "http://gdata.youtube.com/feeds/api/users/{username}/uploads".
  236. Args:
  237. uri: An optional string representing the URI of the user feed that is
  238. to be retrieved.
  239. username: An optional string representing the username.
  240. Returns:
  241. A YouTubeUserFeed if successfully retrieved.
  242. Raises:
  243. YouTubeError: You must provide at least a uri or a username to the
  244. GetYouTubeUserFeed() method.
  245. """
  246. if uri is None and username is None:
  247. raise YouTubeError('You must provide at least a uri or a username '
  248. 'to the GetYouTubeUserFeed() method')
  249. elif username and not uri:
  250. uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads')
  251. return self.Get(uri, converter=gdata.youtube.YouTubeUserFeedFromString)
  252. def GetYouTubeUserEntry(self, uri=None, username=None):
  253. """Retrieve a YouTubeUserEntry.
  254. Either a uri or a username must be provided.
  255. Args:
  256. uri: An optional string representing the URI of the user entry that is
  257. to be retrieved.
  258. username: An optional string representing the username.
  259. Returns:
  260. A YouTubeUserEntry if successfully retrieved.
  261. Raises:
  262. YouTubeError: You must provide at least a uri or a username to the
  263. GetYouTubeUserEntry() method.
  264. """
  265. if uri is None and username is None:
  266. raise YouTubeError('You must provide at least a uri or a username '
  267. 'to the GetYouTubeUserEntry() method')
  268. elif username and not uri:
  269. uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username)
  270. return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString)
  271. def GetYouTubePlaylistFeed(self, uri=None, username='default'):
  272. """Retrieve a YouTubePlaylistFeed (a feed of playlists for a user).
  273. Either a uri or a username must be provided.
  274. Args:
  275. uri: An optional string representing the URI of the playlist feed that
  276. is to be retrieved.
  277. username: An optional string representing the username. Defaults to the
  278. currently authenticated user.
  279. Returns:
  280. A YouTubePlaylistFeed if successfully retrieved.
  281. Raises:
  282. YouTubeError: You must provide at least a uri or a username to the
  283. GetYouTubePlaylistFeed() method.
  284. """
  285. if uri is None:
  286. uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists')
  287. return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString)
  288. def GetYouTubePlaylistEntry(self, uri):
  289. """Retrieve a YouTubePlaylistEntry.
  290. Args:
  291. uri: A string representing the URI of the playlist feed that is to
  292. be retrieved.
  293. Returns:
  294. A YouTubePlaylistEntry if successfully retrieved.
  295. """
  296. return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString)
  297. def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None):
  298. """Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist).
  299. Either a uri or a playlist_id must be provided.
  300. Args:
  301. uri: An optional string representing the URI of the playlist video feed
  302. that is to be retrieved.
  303. playlist_id: An optional string representing the Id of the playlist whose
  304. playlist video feed is to be retrieved.
  305. Returns:
  306. A YouTubePlaylistVideoFeed if successfully retrieved.
  307. Raises:
  308. YouTubeError: You must provide at least a uri or a playlist_id to the
  309. GetYouTubePlaylistVideoFeed() method.
  310. """
  311. if uri is None and playlist_id is None:
  312. raise YouTubeError('You must provide at least a uri or a playlist_id '
  313. 'to the GetYouTubePlaylistVideoFeed() method')
  314. elif playlist_id and not uri:
  315. uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id)
  316. return self.Get(
  317. uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString)
  318. def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None):
  319. """Retrieve a YouTubeVideoResponseFeed.
  320. Either a uri or a playlist_id must be provided.
  321. Args:
  322. uri: An optional string representing the URI of the video response feed
  323. that is to be retrieved.
  324. video_id: An optional string representing the ID of the video whose
  325. response feed is to be retrieved.
  326. Returns:
  327. A YouTubeVideoResponseFeed if successfully retrieved.
  328. Raises:
  329. YouTubeError: You must provide at least a uri or a video_id to the
  330. GetYouTubeVideoResponseFeed() method.
  331. """
  332. if uri is None and video_id is None:
  333. raise YouTubeError('You must provide at least a uri or a video_id '
  334. 'to the GetYouTubeVideoResponseFeed() method')
  335. elif video_id and not uri:
  336. uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses')
  337. return self.Get(
  338. uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString)
  339. def GetYouTubeVideoResponseEntry(self, uri):
  340. """Retrieve a YouTubeVideoResponseEntry.
  341. Args:
  342. uri: A string representing the URI of the video response entry that
  343. is to be retrieved.
  344. Returns:
  345. A YouTubeVideoResponseEntry if successfully retrieved.
  346. """
  347. return self.Get(
  348. uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString)
  349. def GetYouTubeSubscriptionFeed(self, uri=None, username='default'):
  350. """Retrieve a YouTubeSubscriptionFeed.
  351. Either the uri of the feed or a username must be provided.
  352. Args:
  353. uri: An optional string representing the URI of the feed that is to
  354. be retrieved.
  355. username: An optional string representing the username whose subscription
  356. feed is to be retrieved. Defaults to the currently authenticted user.
  357. Returns:
  358. A YouTubeVideoSubscriptionFeed if successfully retrieved.
  359. """
  360. if uri is None:
  361. uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions')
  362. return self.Get(
  363. uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString)
  364. def GetYouTubeSubscriptionEntry(self, uri):
  365. """Retrieve a YouTubeSubscriptionEntry.
  366. Args:
  367. uri: A string representing the URI of the entry that is to be retrieved.
  368. Returns:
  369. A YouTubeVideoSubscriptionEntry if successfully retrieved.
  370. """
  371. return self.Get(
  372. uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
  373. def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None):
  374. """Retrieve a YouTubeRelatedVideoFeed.
  375. Either a uri for the feed or a video_id is required.
  376. Args:
  377. uri: An optional string representing the URI of the feed that is to
  378. be retrieved.
  379. video_id: An optional string representing the ID of the video for which
  380. to retrieve the related video feed.
  381. Returns:
  382. A YouTubeRelatedVideoFeed if successfully retrieved.
  383. Raises:
  384. YouTubeError: You must provide at least a uri or a video_id to the
  385. GetYouTubeRelatedVideoFeed() method.
  386. """
  387. if uri is None and video_id is None:
  388. raise YouTubeError('You must provide at least a uri or a video_id '
  389. 'to the GetYouTubeRelatedVideoFeed() method')
  390. elif video_id and not uri:
  391. uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related')
  392. return self.Get(
  393. uri, converter=gdata.youtube.YouTubeVideoFeedFromString)
  394. def GetTopRatedVideoFeed(self):
  395. """Retrieve the 'top_rated' standard video feed.
  396. Returns:
  397. A YouTubeVideoFeed if successfully retrieved.
  398. """
  399. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI)
  400. def GetMostViewedVideoFeed(self):
  401. """Retrieve the 'most_viewed' standard video feed.
  402. Returns:
  403. A YouTubeVideoFeed if successfully retrieved.
  404. """
  405. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI)
  406. def GetRecentlyFeaturedVideoFeed(self):
  407. """Retrieve the 'recently_featured' standard video feed.
  408. Returns:
  409. A YouTubeVideoFeed if successfully retrieved.
  410. """
  411. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI)
  412. def GetWatchOnMobileVideoFeed(self):
  413. """Retrieve the 'watch_on_mobile' standard video feed.
  414. Returns:
  415. A YouTubeVideoFeed if successfully retrieved.
  416. """
  417. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI)
  418. def GetTopFavoritesVideoFeed(self):
  419. """Retrieve the 'top_favorites' standard video feed.
  420. Returns:
  421. A YouTubeVideoFeed if successfully retrieved.
  422. """
  423. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI)
  424. def GetMostRecentVideoFeed(self):
  425. """Retrieve the 'most_recent' standard video feed.
  426. Returns:
  427. A YouTubeVideoFeed if successfully retrieved.
  428. """
  429. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI)
  430. def GetMostDiscussedVideoFeed(self):
  431. """Retrieve the 'most_discussed' standard video feed.
  432. Returns:
  433. A YouTubeVideoFeed if successfully retrieved.
  434. """
  435. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI)
  436. def GetMostLinkedVideoFeed(self):
  437. """Retrieve the 'most_linked' standard video feed.
  438. Returns:
  439. A YouTubeVideoFeed if successfully retrieved.
  440. """
  441. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI)
  442. def GetMostRespondedVideoFeed(self):
  443. """Retrieve the 'most_responded' standard video feed.
  444. Returns:
  445. A YouTubeVideoFeed if successfully retrieved.
  446. """
  447. return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI)
  448. def GetUserFavoritesFeed(self, username='default'):
  449. """Retrieve the favorites feed for a given user.
  450. Args:
  451. username: An optional string representing the username whose favorites
  452. feed is to be retrieved. Defaults to the currently authenticated user.
  453. Returns:
  454. A YouTubeVideoFeed if successfully retrieved.
  455. """
  456. favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username,
  457. 'favorites')
  458. return self.GetYouTubeVideoFeed(favorites_feed_uri)
  459. def InsertVideoEntry(self, video_entry, filename_or_handle,
  460. youtube_username='default',
  461. content_type='video/quicktime'):
  462. """Upload a new video to YouTube using the direct upload mechanism.
  463. Needs authentication.
  464. Args:
  465. video_entry: The YouTubeVideoEntry to upload.
  466. filename_or_handle: A file-like object or file name where the video
  467. will be read from.
  468. youtube_username: An optional string representing the username into whose
  469. account this video is to be uploaded to. Defaults to the currently
  470. authenticated user.
  471. content_type: An optional string representing internet media type
  472. (a.k.a. mime type) of the media object. Currently the YouTube API
  473. supports these types:
  474. o video/mpeg
  475. o video/quicktime
  476. o video/x-msvideo
  477. o video/mp4
  478. o video/x-flv
  479. Returns:
  480. The newly created YouTubeVideoEntry if successful.
  481. Raises:
  482. AssertionError: video_entry must be a gdata.youtube.VideoEntry instance.
  483. YouTubeError: An error occurred trying to read the video file provided.
  484. gdata.service.RequestError: An error occurred trying to upload the video
  485. to the API server.
  486. """
  487. # We need to perform a series of checks on the video_entry and on the
  488. # file that we plan to upload, such as checking whether we have a valid
  489. # video_entry and that the file is the correct type and readable, prior
  490. # to performing the actual POST request.
  491. try:
  492. assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry))
  493. except AssertionError:
  494. raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT,
  495. 'body':'`video_entry` must be a gdata.youtube.VideoEntry instance',
  496. 'reason':'Found %s, not VideoEntry' % type(video_entry)
  497. })
  498. #majtype, mintype = content_type.split('/')
  499. #
  500. #try:
  501. # assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES)
  502. #except (ValueError, AssertionError):
  503. # raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE,
  504. # 'body':'This is not a valid content type: %s' % content_type,
  505. # 'reason':'Accepted content types: %s' %
  506. # ['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]})
  507. if (isinstance(filename_or_handle, (str, unicode))
  508. and os.path.exists(filename_or_handle)):
  509. mediasource = gdata.MediaSource()
  510. mediasource.setFile(filename_or_handle, content_type)
  511. elif hasattr(filename_or_handle, 'read'):
  512. import StringIO
  513. if hasattr(filename_or_handle, 'seek'):
  514. filename_or_handle.seek(0)
  515. file_handle = StringIO.StringIO(filename_or_handle.read())
  516. name = 'video'
  517. if hasattr(filename_or_handle, 'name'):
  518. name = filename_or_handle.name
  519. mediasource = gdata.MediaSource(file_handle, content_type,
  520. content_length=file_handle.len, file_name=name)
  521. else:
  522. raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':
  523. '`filename_or_handle` must be a path name or a file-like object',
  524. 'reason': ('Found %s, not path name or object '
  525. 'with a .read() method' % type(filename_or_handle))})
  526. upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username,
  527. 'uploads')
  528. self.additional_headers['Slug'] = mediasource.file_name
  529. # Using a nested try statement to retain Python 2.4 compatibility
  530. try:
  531. try:
  532. return self.Post(video_entry, uri=upload_uri, media_source=mediasource,
  533. converter=gdata.youtube.YouTubeVideoEntryFromString)
  534. except gdata.service.RequestError, e:
  535. raise YouTubeError(e.args[0])
  536. finally:
  537. del(self.additional_headers['Slug'])
  538. def CheckUploadStatus(self, video_entry=None, video_id=None):
  539. """Check upload status on a recently uploaded video entry.
  540. Needs authentication. Either video_entry or video_id must be provided.
  541. Args:
  542. video_entry: An optional YouTubeVideoEntry whose upload status to check
  543. video_id: An optional string representing the ID of the uploaded video
  544. whose status is to be checked.
  545. Returns:
  546. A tuple containing (video_upload_state, detailed_message) or None if
  547. no status information is found.
  548. Raises:
  549. YouTubeError: You must provide at least a video_entry or a video_id to the
  550. CheckUploadStatus() method.
  551. """
  552. if video_entry is None and video_id is None:
  553. raise YouTubeError('You must provide at least a uri or a video_id '
  554. 'to the CheckUploadStatus() method')
  555. elif video_id and not video_entry:
  556. video_entry = self.GetYouTubeVideoEntry(video_id=video_id)
  557. control = video_entry.control
  558. if control is not None:
  559. draft = control.draft
  560. if draft is not None:
  561. if draft.text == 'yes':
  562. yt_state = control.extension_elements[0]
  563. if yt_state is not None:
  564. state_value = yt_state.attributes['name']
  565. message = ''
  566. if yt_state.text is not None:
  567. message = yt_state.text
  568. return (state_value, message)
  569. def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI):
  570. """Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry.
  571. Needs authentication.
  572. Args:
  573. video_entry: The YouTubeVideoEntry to upload (meta-data only).
  574. uri: An optional string representing the URI from where to fetch the
  575. token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI.
  576. Returns:
  577. A tuple containing the URL to which to post your video file, along
  578. with the youtube token that must be included with your upload in the
  579. form of: (post_url, youtube_token).
  580. """
  581. try:
  582. response = self.Post(video_entry, uri)
  583. except gdata.service.RequestError, e:
  584. raise YouTubeError(e.args[0])
  585. tree = ElementTree.fromstring(response)
  586. for child in tree:
  587. if child.tag == 'url':
  588. post_url = child.text
  589. elif child.tag == 'token':
  590. youtube_token = child.text
  591. return (post_url, youtube_token)
  592. def UpdateVideoEntry(self, video_entry):
  593. """Updates a video entry's meta-data.
  594. Needs authentication.
  595. Args:
  596. video_entry: The YouTubeVideoEntry to update, containing updated
  597. meta-data.
  598. Returns:
  599. An updated YouTubeVideoEntry on success or None.
  600. """
  601. for link in video_entry.link:
  602. if link.rel == 'edit':
  603. edit_uri = link.href
  604. return self.Put(video_entry, uri=edit_uri,
  605. converter=gdata.youtube.YouTubeVideoEntryFromString)
  606. def DeleteVideoEntry(self, video_entry):
  607. """Deletes a video entry.
  608. Needs authentication.
  609. Args:
  610. video_entry: The YouTubeVideoEntry to be deleted.
  611. Returns:
  612. True if entry was deleted successfully.
  613. """
  614. for link in video_entry.link:
  615. if link.rel == 'edit':
  616. edit_uri = link.href
  617. return self.Delete(edit_uri)
  618. def AddRating(self, rating_value, video_entry):
  619. """Add a rating to a video entry.
  620. Needs authentication.
  621. Args:
  622. rating_value: The integer value for the rating (between 1 and 5).
  623. video_entry: The YouTubeVideoEntry to be rated.
  624. Returns:
  625. True if the rating was added successfully.
  626. Raises:
  627. YouTubeError: rating_value must be between 1 and 5 in AddRating().
  628. """
  629. if rating_value < 1 or rating_value > 5:
  630. raise YouTubeError('rating_value must be between 1 and 5 in AddRating()')
  631. entry = gdata.GDataEntry()
  632. rating = gdata.youtube.Rating(min='1', max='5')
  633. rating.extension_attributes['name'] = 'value'
  634. rating.extension_attributes['value'] = str(rating_value)
  635. entry.extension_elements.append(rating)
  636. for link in video_entry.link:
  637. if link.rel == YOUTUBE_RATING_LINK_REL:
  638. rating_uri = link.href
  639. return self.Post(entry, uri=rating_uri)
  640. def AddComment(self, comment_text, video_entry):
  641. """Add a comment to a video entry.
  642. Needs authentication. Note that each comment that is posted must contain
  643. the video entry that it is to be posted to.
  644. Args:
  645. comment_text: A string representing the text of the comment.
  646. video_entry: The YouTubeVideoEntry to be commented on.
  647. Returns:
  648. True if the comment was added successfully.
  649. """
  650. content = atom.Content(text=comment_text)
  651. comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content)
  652. comment_post_uri = video_entry.comments.feed_link[0].href
  653. return self.Post(comment_entry, uri=comment_post_uri)
  654. def AddVideoResponse(self, video_id_to_respond_to, video_response):
  655. """Add a video response.
  656. Needs authentication.
  657. Args:
  658. video_id_to_respond_to: A string representing the ID of the video to be
  659. responded to.
  660. video_response: YouTubeVideoEntry to be posted as a response.
  661. Returns:
  662. True if video response was posted successfully.
  663. """
  664. post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to,
  665. 'responses')
  666. return self.Post(video_response, uri=post_uri)
  667. def DeleteVideoResponse(self, video_id, response_video_id):
  668. """Delete a video response.
  669. Needs authentication.
  670. Args:
  671. video_id: A string representing the ID of video that contains the
  672. response.
  673. response_video_id: A string representing the ID of the video that was
  674. posted as a response.
  675. Returns:
  676. True if video response was deleted succcessfully.
  677. """
  678. delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses',
  679. response_video_id)
  680. return self.Delete(delete_uri)
  681. def AddComplaint(self, complaint_text, complaint_term, video_id):
  682. """Add a complaint for a particular video entry.
  683. Needs authentication.
  684. Args:
  685. complaint_text: A string representing the complaint text.
  686. complaint_term: A string representing the complaint category term.
  687. video_id: A string representing the ID of YouTubeVideoEntry to
  688. complain about.
  689. Returns:
  690. True if posted successfully.
  691. Raises:
  692. YouTubeError: Your complaint_term is not valid.
  693. """
  694. if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS:
  695. raise YouTubeError('Your complaint_term is not valid')
  696. content = atom.Content(text=complaint_text)
  697. category = atom.Category(term=complaint_term,
  698. scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME)
  699. complaint_entry = gdata.GDataEntry(content=content, category=[category])
  700. post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints')
  701. return self.Post(complaint_entry, post_uri)
  702. def AddVideoEntryToFavorites(self, video_entry, username='default'):
  703. """Add a video entry to a users favorite feed.
  704. Needs authentication.
  705. Args:
  706. video_entry: The YouTubeVideoEntry to add.
  707. username: An optional string representing the username to whose favorite
  708. feed you wish to add the entry. Defaults to the currently
  709. authenticated user.
  710. Returns:
  711. The posted YouTubeVideoEntry if successfully posted.
  712. """
  713. post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites')
  714. return self.Post(video_entry, post_uri,
  715. converter=gdata.youtube.YouTubeVideoEntryFromString)
  716. def DeleteVideoEntryFromFavorites(self, video_id, username='default'):
  717. """Delete a video entry from the users favorite feed.
  718. Needs authentication.
  719. Args:
  720. video_id: A string representing the ID of the video that is to be removed
  721. username: An optional string representing the username of the user's
  722. favorite feed. Defaults to the currently authenticated user.
  723. Returns:
  724. True if entry was successfully deleted.
  725. """
  726. edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites',
  727. video_id)
  728. return self.Delete(edit_link)
  729. def AddPlaylist(self, playlist_title, playlist_description,
  730. playlist_private=None):
  731. """Add a new playlist to the currently authenticated users account.
  732. Needs authentication.
  733. Args:
  734. playlist_title: A string representing the title for the new playlist.
  735. playlist_description: A string representing the description of the
  736. playlist.
  737. playlist_private: An optional boolean, set to True if the playlist is
  738. to be private.
  739. Returns:
  740. The YouTubePlaylistEntry if successfully posted.
  741. """
  742. playlist_entry = gdata.youtube.YouTubePlaylistEntry(
  743. title=atom.Title(text=playlist_title),
  744. description=gdata.youtube.Description(text=playlist_description))
  745. if playlist_private:
  746. playlist_entry.private = gdata.youtube.Private()
  747. playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default',
  748. 'playlists')
  749. return self.Post(playlist_entry, playlist_post_uri,
  750. converter=gdata.youtube.YouTubePlaylistEntryFromString)
  751. def UpdatePlaylist(self, playlist_id, new_playlist_title,
  752. new_playlist_description, playlist_private=None,
  753. username='default'):
  754. """Update a playlist with new meta-data.
  755. Needs authentication.
  756. Args:
  757. playlist_id: A string representing the ID of the playlist to be updated.
  758. new_playlist_title: A string representing a new title for the playlist.
  759. new_playlist_description: A string representing a new description for the
  760. playlist.
  761. playlist_private: An optional boolean, set to True if the playlist is
  762. to be private.
  763. username: An optional string representing the username whose playlist is
  764. to be updated. Defaults to the currently authenticated user.
  765. Returns:
  766. A YouTubePlaylistEntry if the update was successful.
  767. """
  768. updated_playlist = gdata.youtube.YouTubePlaylistEntry(
  769. title=atom.Title(text=new_playlist_title),
  770. description=gdata.youtube.Description(text=new_playlist_description))
  771. if playlist_private:
  772. updated_playlist.private = gdata.youtube.Private()
  773. playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username,
  774. playlist_id)
  775. return self.Put(updated_playlist, playlist_put_uri,
  776. converter=gdata.youtube.YouTubePlaylistEntryFromString)
  777. def DeletePlaylist(self, playlist_uri):
  778. """Delete a playlist from the currently authenticated users playlists.
  779. Needs authentication.
  780. Args:
  781. playlist_uri: A string representing the URI of the playlist that is
  782. to be deleted.
  783. Returns:
  784. True if successfully deleted.
  785. """
  786. return self.Delete(playlist_uri)
  787. def AddPlaylistVideoEntryToPlaylist(
  788. self, playlist_uri, video_id, custom_video_title=None,
  789. custom_video_description=None):
  790. """Add a video entry to a playlist, optionally providing a custom title
  791. and description.
  792. Needs authentication.
  793. Args:
  794. playlist_uri: A string representing the URI of the playlist to which this
  795. video entry is to be added.
  796. video_id: A string representing the ID of the video entry to add.
  797. custom_video_title: An optional string representing a custom title for
  798. the video (only shown on the playlist).
  799. custom_video_description: An optional string representing a custom
  800. description for the video (only shown on the playlist).
  801. Returns:
  802. A YouTubePlaylistVideoEntry if successfully posted.
  803. """
  804. playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
  805. atom_id=atom.Id(text=video_id))
  806. if custom_video_title:
  807. playlist_video_entry.title = atom.Title(text=custom_video_title)
  808. if custom_video_description:
  809. playlist_video_entry.description = gdata.youtube.Description(
  810. text=custom_video_description)
  811. return self.Post(playlist_video_entry, playlist_uri,
  812. converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
  813. def UpdatePlaylistVideoEntryMetaData(
  814. self, playlist_uri, playlist_entry_id, new_video_title,
  815. new_video_description, new_video_position):
  816. """Update the meta data for a YouTubePlaylistVideoEntry.
  817. Needs authentication.
  818. Args:
  819. playlist_uri: A string representing the URI of the playlist that contains
  820. the entry to be updated.
  821. playlist_entry_id: A string representing the ID of the entry to be
  822. updated.
  823. new_video_title: A string representing the new title for the video entry.
  824. new_video_description: A string representing the new description for
  825. the video entry.
  826. new_video_position: An integer representing the new position on the
  827. playlist for the video.
  828. Returns:
  829. A YouTubePlaylistVideoEntry if the update was successful.
  830. """
  831. playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry(
  832. title=atom.Title(text=new_video_title),
  833. description=gdata.youtube.Description(text=new_video_description),
  834. position=gdata.youtube.Position(text=str(new_video_position)))
  835. playlist_put_uri = playlist_uri + '/' + playlist_entry_id
  836. return self.Put(playlist_video_entry, playlist_put_uri,
  837. converter=gdata.youtube.YouTubePlaylistVideoEntryFromString)
  838. def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id):
  839. """Delete a playlist video entry from a playlist.
  840. Needs authentication.
  841. Args:
  842. playlist_uri: A URI representing the playlist from which the playlist
  843. video entry is to be removed from.
  844. playlist_video_entry_id: A string representing id of the playlist video
  845. entry that is to be removed.
  846. Returns:
  847. True if entry was successfully deleted.
  848. """
  849. delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id)
  850. return self.Delete(delete_uri)
  851. def AddSubscriptionToChannel(self, username_to_subscribe_to,
  852. my_username = 'default'):
  853. """Add a new channel subscription to the currently authenticated users
  854. account.
  855. Needs authentication.
  856. Args:
  857. username_to_subscribe_to: A string representing the username of the
  858. channel to which we want to subscribe to.
  859. my_username: An optional string representing the name of the user which
  860. we want to subscribe. Defaults to currently authenticated user.
  861. Returns:
  862. A new YouTubeSubscriptionEntry if successfully posted.
  863. """
  864. subscription_category = atom.Category(
  865. scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
  866. term='channel')
  867. subscription_username = gdata.youtube.Username(
  868. text=username_to_subscribe_to)
  869. subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
  870. category=subscription_category,
  871. username=subscription_username)
  872. post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
  873. 'subscriptions')
  874. return self.Post(subscription_entry, post_uri,
  875. converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
  876. def AddSubscriptionToFavorites(self, username, my_username = 'default'):
  877. """Add a new subscription to a users favorites to the currently
  878. authenticated user's account.
  879. Needs authentication
  880. Args:
  881. username: A string representing the username of the user's favorite feed
  882. to subscribe to.
  883. my_username: An optional string representing the username of the user
  884. that is to be subscribed. Defaults to currently authenticated user.
  885. Returns:
  886. A new YouTubeSubscriptionEntry if successful.
  887. """
  888. subscription_category = atom.Category(
  889. scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
  890. term='favorites')
  891. subscription_username = gdata.youtube.Username(text=username)
  892. subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
  893. category=subscription_category,
  894. username=subscription_username)
  895. post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
  896. 'subscriptions')
  897. return self.Post(subscription_entry, post_uri,
  898. converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
  899. def AddSubscriptionToQuery(self, query, my_username = 'default'):
  900. """Add a new subscription to a specific keyword query to the currently
  901. authenticated user's account.
  902. Needs authentication
  903. Args:
  904. query: A string representing the keyword query to subscribe to.
  905. my_username: An optional string representing the username of the user
  906. that is to be subscribed. Defaults to currently authenticated user.
  907. Returns:
  908. A new YouTubeSubscriptionEntry if successful.
  909. """
  910. subscription_category = atom.Category(
  911. scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
  912. term='query')
  913. subscription_query_string = gdata.youtube.QueryString(text=query)
  914. subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
  915. category=subscription_category,
  916. query_string=subscription_query_string)
  917. post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
  918. 'subscriptions')
  919. return self.Post(subscription_entry, post_uri,
  920. converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
  921. def DeleteSubscription(self, subscription_uri):
  922. """Delete a subscription from the currently authenticated user's account.
  923. Needs authentication.
  924. Args:
  925. subscription_uri: A string representing the URI of the subscription that
  926. is to be deleted.
  927. Returns:
  928. True if deleted successfully.
  929. """
  930. return self.Delete(subscription_uri)
  931. def AddContact(self, contact_username, my_username='default'):
  932. """Add a new contact to the currently authenticated user's contact feed.
  933. Needs authentication.
  934. Args:
  935. contact_username: A string representing the username of the contact
  936. that you wish to add.
  937. my_username: An optional string representing the username to whose
  938. contact the new contact is to be added.
  939. Returns:
  940. A YouTubeContactEntry if added successfully.
  941. """
  942. contact_category = atom.Category(
  943. scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat',
  944. term = 'Friends')
  945. contact_username = gdata.youtube.Username(text=contact_username)
  946. contact_entry = gdata.youtube.YouTubeContactEntry(
  947. category=contact_category,
  948. username=contact_username)
  949. contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
  950. 'contacts')
  951. return self.Post(contact_entry, contact_post_uri,
  952. converter=gdata.youtube.YouTubeContactEntryFromString)
  953. def UpdateContact(self, contact_username, new_contact_status,
  954. new_contact_category, my_username='default'):
  955. """Update a contact, providing a new status and a new category.
  956. Needs authentication.
  957. Args:
  958. contact_username: A string representing the username of the contact
  959. that is to be updated.
  960. new_contact_status: A string representing the new status of the contact.
  961. This can either be set to 'accepted' or 'rejected'.
  962. new_contact_category: A string representing the new category for the
  963. contact, either 'Friends' or 'Family'.
  964. my_username: An optional string representing the username of the user
  965. whose contact feed we are modifying. Defaults to the currently
  966. authenticated user.
  967. Returns:
  968. A YouTubeContactEntry if updated succesfully.
  969. Raises:
  970. YouTubeError: New contact status must be within the accepted values. Or
  971. new contact category must be within the accepted categories.
  972. """
  973. if new_contact_status not in YOUTUBE_CONTACT_STATUS:
  974. raise YouTubeError('New contact status must be one of %s' %
  975. (' '.join(YOUTUBE_CONTACT_STATUS)))
  976. if new_contact_category not in YOUTUBE_CONTACT_CATEGORY:
  977. raise YouTubeError('New contact category must be one of %s' %
  978. (' '.join(YOUTUBE_CONTACT_CATEGORY)))
  979. contact_category = atom.Category(
  980. scheme='http://gdata.youtube.com/schemas/2007/contact.cat',
  981. term=new_contact_category)
  982. contact_status = gdata.youtube.Status(text=new_contact_status)
  983. contact_entry = gdata.youtube.YouTubeContactEntry(
  984. category=contact_category,
  985. status=contact_status)
  986. contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
  987. 'contacts', contact_username)
  988. return self.Put(contact_entry, contact_put_uri,
  989. converter=gdata.youtube.YouTubeContactEntryFromString)
  990. def DeleteContact(self, contact_username, my_username='default'):
  991. """Delete a contact from a users contact feed.
  992. Needs authentication.
  993. Args:
  994. contact_username: A string representing the username of the contact
  995. that is to be deleted.
  996. my_username: An optional string representing the username of the user's
  997. contact feed from which to delete the contact. Defaults to the
  998. currently authenticated user.
  999. Returns:
  1000. True if the contact was deleted successfully
  1001. """
  1002. contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
  1003. 'contacts', contact_username)
  1004. return self.Delete(contact_edit_uri)
  1005. def _GetDeveloperKey(self):
  1006. """Getter for Developer Key property.
  1007. Returns:
  1008. If the developer key has been set, a string representing the developer key
  1009. is returned or None.
  1010. """
  1011. if 'X-GData-Key' in self.additional_headers:
  1012. return self.additional_headers['X-GData-Key'][4:]
  1013. else:
  1014. return None
  1015. def _SetDeveloperKey(self, developer_key):
  1016. """Setter for Developer Key property.
  1017. Sets the developer key in the 'X-GData-Key' header. The actual value that
  1018. is set is 'key=' plus the developer_key that was passed.
  1019. """
  1020. self.additional_headers['X-GData-Key'] = 'key=' + developer_key
  1021. developer_key = property(_GetDeveloperKey, _SetDeveloperKey,
  1022. doc="""The Developer Key property""")
  1023. def _GetClientId(self):
  1024. """Getter for Client Id property.
  1025. Returns:
  1026. If the client_id has been set, a string representing it is returned
  1027. or None.
  1028. """
  1029. if 'X-Gdata-Client' in self.additional_headers:
  1030. return self.additional_headers['X-Gdata-Client']
  1031. else:
  1032. return None
  1033. def _SetClientId(self, client_id):
  1034. """Setter for Client Id property.
  1035. Sets the 'X-Gdata-Client' header.
  1036. """
  1037. self.additional_headers['X-Gdata-Client'] = client_id
  1038. client_id = property(_GetClientId, _SetClientId,
  1039. doc="""The ClientId property""")
  1040. def Query(self, uri):
  1041. """Performs a query and returns a resulting feed or entry.
  1042. Args:
  1043. uri: A string representing the URI of the feed that is to be queried.
  1044. Returns:
  1045. On success, a tuple in the form:
  1046. (boolean succeeded=True, ElementTree._Element result)
  1047. On failure, a tuple in the form:
  1048. (boolean succeeded=False, {'status': HTTP status code from server,
  1049. 'reason': HTTP reason from the server,
  1050. 'body': HTTP body of the server's response})
  1051. """
  1052. result = self.Get(uri)
  1053. return result
  1054. def YouTubeQuery(self, query):
  1055. """Performs a YouTube specific query and returns a resulting feed or entry.
  1056. Args:
  1057. query: A Query object or one if its sub-classes (YouTubeVideoQuery,
  1058. YouTubeUserQuery or YouTubePlaylistQuery).
  1059. Returns:
  1060. Depending on the type of Query object submitted returns either a
  1061. YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the
  1062. Query object provided was not YouTube-related, a tuple is returned.
  1063. On success the tuple will be in this form:
  1064. (boolean succeeded=True, ElementTree._Element result)
  1065. On failure, the tuple will be in this form:
  1066. (boolean succeeded=False, {'status': HTTP status code from server,
  1067. 'reason': HTTP reason from the server,
  1068. 'body': HTTP body of the server response})
  1069. """
  1070. result = self.Query(query.ToUri())
  1071. if isinstance(query, YouTubeVideoQuery):
  1072. return gdata.youtube.YouTubeVideoFeedFromString(result.ToString())
  1073. elif isinstance(query, YouTubeUserQuery):
  1074. return gdata.youtube.YouTubeUserFeedFromString(result.ToString())
  1075. elif isinstance(query, YouTubePlaylistQuery):
  1076. return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString())
  1077. else:
  1078. return result
  1079. class YouTubeVideoQuery(gdata.service.Query):
  1080. """Subclasses gdata.service.Query to represent a YouTube Data API query.
  1081. Attributes are set dynamically via properties. Properties correspond to
  1082. the standard Google Data API query parameters with YouTube Data API
  1083. extensions. Please refer to the API documentation for details.
  1084. Attributes:
  1085. vq: The vq parameter, which is only supported for video feeds, specifies a
  1086. search query term. Refer to API documentation for further details.
  1087. orderby: The orderby parameter, which is only supported for video feeds,
  1088. specifies the value that will be used to sort videos in the search
  1089. result set. Valid values for this parameter are relevance, published,
  1090. viewCount and rating.
  1091. time: The time parameter, which is only available for the top_rated,
  1092. top_favorites, most_viewed, most_discussed, most_linked and
  1093. most_responded standard feeds, restricts the search to videos uploaded
  1094. within the specified time. Valid values for this parameter are today
  1095. (1 day), this_week (7 days), this_month (1 month) and all_time.
  1096. The default value for this parameter is all_time.
  1097. format: The format parameter specifies that videos must be available in a
  1098. particular video format. Refer to the API documentation for details.
  1099. racy: The racy parameter allows a search result set to include restricted
  1100. content as well as standard content. Valid values for this parameter
  1101. are include and exclude. By default, restricted content is excluded.
  1102. lr: The lr parameter restricts the search to videos that have a title,
  1103. description or keywords in a specific language. Valid values for the lr
  1104. parameter are ISO 639-1 two-letter language codes.
  1105. restriction: The restriction parameter identifies the IP address that
  1106. should be used to filter videos that can only be played in specific
  1107. countries.
  1108. location: A string of geo coordinates. Note that this is not used when the
  1109. search is performed but rather to filter the returned videos for ones
  1110. that match to the location entered.
  1111. feed: str (optional) The base URL which is the beginning of the query URL.
  1112. defaults to 'http://%s/feeds/videos' % (YOUTUBE_SERVER)
  1113. """
  1114. def __init__(self, video_id=None, feed_type=None, text_query=None,
  1115. params=None, categories=None, feed=None):
  1116. if feed_type in YOUTUBE_STANDARDFEEDS and feed is None:
  1117. feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type)
  1118. elif (feed_type is 'responses' or feed_type is 'comments' and video_id
  1119. and feed is None):
  1120. feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id,
  1121. feed_type)
  1122. elif feed is None:
  1123. feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER)
  1124. gdata.service.Query.__init__(self, feed, text_query=text_query,
  1125. params=params, categories=categories)
  1126. def _GetVideoQuery(self):
  1127. if 'vq' in self:
  1128. return self['vq']
  1129. else:
  1130. return None
  1131. def _SetVideoQuery(self, val):
  1132. self['vq'] = val
  1133. vq = property(_GetVideoQuery, _SetVideoQuery,
  1134. doc="""The video query (vq) query parameter""")
  1135. def _GetOrderBy(self):
  1136. if 'orderby' in self:
  1137. return self['orderby']
  1138. else:
  1139. return None
  1140. def _SetOrderBy(self, val):
  1141. if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS:
  1142. if val.startswith('relevance_lang_') is False:
  1143. raise YouTubeError('OrderBy must be one of: %s ' %
  1144. ' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS))
  1145. self['orderby'] = val
  1146. orderby = property(_GetOrderBy, _SetOrderBy,
  1147. doc="""The orderby query parameter""")
  1148. def _GetTime(self):
  1149. if 'time' in self:
  1150. return self['time']
  1151. else:
  1152. return None
  1153. def _SetTime(self, val):
  1154. if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS:
  1155. raise YouTubeError('Time must be one of: %s ' %
  1156. ' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS))
  1157. self['time'] = val
  1158. time = property(_GetTime, _SetTime,
  1159. doc="""The time query parameter""")
  1160. def _GetFormat(self):
  1161. if 'format' in self:
  1162. return self['format']
  1163. else:
  1164. return None
  1165. def _SetFormat(self, val):
  1166. if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS:
  1167. raise YouTubeError('Format must be one of: %s ' %
  1168. ' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS))
  1169. self['format'] = val
  1170. format = property(_GetFormat, _SetFormat,
  1171. doc="""The format query parameter""")
  1172. def _GetRacy(self):
  1173. if 'racy' in self:
  1174. return self['racy']
  1175. else:
  1176. return None
  1177. def _SetRacy(self, val):
  1178. if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS:
  1179. raise YouTubeError('Racy must be one of: %s ' %
  1180. ' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS))
  1181. self['racy'] = val
  1182. racy = property(_GetRacy, _SetRacy,
  1183. doc="""The racy query parameter""")
  1184. def _GetLanguageRestriction(self):
  1185. if 'lr' in self:
  1186. return self['lr']
  1187. else:
  1188. return None
  1189. def _SetLanguageRestriction(self, val):
  1190. self['lr'] = val
  1191. lr = property(_GetLanguageRestriction, _SetLanguageRestriction,
  1192. doc="""The lr (language restriction) query parameter""")
  1193. def _GetIPRestriction(self):
  1194. if 'restriction' in self:
  1195. return self['restriction']
  1196. else:
  1197. return None
  1198. def _SetIPRestriction(self, val):
  1199. self['restriction'] = val
  1200. restriction = property(_GetIPRestriction, _SetIPRestriction,
  1201. doc="""The restriction query parameter""")
  1202. def _GetLocation(self):
  1203. if 'location' in self:
  1204. return self['location']
  1205. else:
  1206. return None
  1207. def _SetLocation(self, val):
  1208. self['location'] = val
  1209. location = property(_GetLocation, _SetLocation,
  1210. doc="""The location query parameter""")
  1211. class YouTubeUserQuery(YouTubeVideoQuery):
  1212. """Subclasses YouTubeVideoQuery to perform user-specific queries.
  1213. Attributes are set dynamically via properties. Properties correspond to
  1214. the standard Google Data API query parameters with YouTube Data API
  1215. extensions.
  1216. """
  1217. def __init__(self, username=None, feed_type=None, subscription_id=None,
  1218. text_query=None, params=None, categories=None):
  1219. uploads_favorites_playlists = ('uploads', 'favorites', 'playlists')
  1220. if feed_type is 'subscriptions' and subscription_id and username:
  1221. feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username,
  1222. feed_type, subscription_id)
  1223. elif feed_type is 'subscriptions' and not subscription_id and username:
  1224. feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
  1225. feed_type)
  1226. elif feed_type in uploads_favorites_playlists:
  1227. feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username,
  1228. feed_type)
  1229. else:
  1230. feed = "http://%s/feeds/users" % (YOUTUBE_SERVER)
  1231. YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
  1232. params=params, categories=categories)
  1233. class YouTubePlaylistQuery(YouTubeVideoQuery):
  1234. """Subclasses YouTubeVideoQuery to perform playlist-specific queries.
  1235. Attributes are set dynamically via properties. Properties correspond to
  1236. the standard Google Data API query parameters with YouTube Data API
  1237. extensions.
  1238. """
  1239. def __init__(self, playlist_id, text_query=None, params=None,
  1240. categories=None):
  1241. if playlist_id:
  1242. feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id)
  1243. else:
  1244. feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER)
  1245. YouTubeVideoQuery.__init__(self, feed, text_query=text_query,
  1246. params=params, categories=categories)