faset over fra Z3950 til google books

This commit is contained in:
2010-09-23 13:57:37 +00:00
parent d173b9396e
commit 644e79f9b5
221 changed files with 60948 additions and 27273 deletions

View File

@@ -0,0 +1,684 @@
#!/usr/bin/python
#
# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = ('api.stephaniel@gmail.com (Stephanie Liu)'
', api.jhartmann@gmail.com (Jochen Hartmann)')
import atom
import gdata
import gdata.media as Media
import gdata.geo as Geo
YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007'
YOUTUBE_FORMAT = '{http://gdata.youtube.com/schemas/2007}format'
YOUTUBE_DEVELOPER_TAG_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'developertags.cat')
YOUTUBE_SUBSCRIPTION_TYPE_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE,
'subscriptiontypes.cat')
class Username(atom.AtomBase):
"""The YouTube Username element"""
_tag = 'username'
_namespace = YOUTUBE_NAMESPACE
class QueryString(atom.AtomBase):
"""The YouTube QueryString element"""
_tag = 'queryString'
_namespace = YOUTUBE_NAMESPACE
class FirstName(atom.AtomBase):
"""The YouTube FirstName element"""
_tag = 'firstName'
_namespace = YOUTUBE_NAMESPACE
class LastName(atom.AtomBase):
"""The YouTube LastName element"""
_tag = 'lastName'
_namespace = YOUTUBE_NAMESPACE
class Age(atom.AtomBase):
"""The YouTube Age element"""
_tag = 'age'
_namespace = YOUTUBE_NAMESPACE
class Books(atom.AtomBase):
"""The YouTube Books element"""
_tag = 'books'
_namespace = YOUTUBE_NAMESPACE
class Gender(atom.AtomBase):
"""The YouTube Gender element"""
_tag = 'gender'
_namespace = YOUTUBE_NAMESPACE
class Company(atom.AtomBase):
"""The YouTube Company element"""
_tag = 'company'
_namespace = YOUTUBE_NAMESPACE
class Hobbies(atom.AtomBase):
"""The YouTube Hobbies element"""
_tag = 'hobbies'
_namespace = YOUTUBE_NAMESPACE
class Hometown(atom.AtomBase):
"""The YouTube Hometown element"""
_tag = 'hometown'
_namespace = YOUTUBE_NAMESPACE
class Location(atom.AtomBase):
"""The YouTube Location element"""
_tag = 'location'
_namespace = YOUTUBE_NAMESPACE
class Movies(atom.AtomBase):
"""The YouTube Movies element"""
_tag = 'movies'
_namespace = YOUTUBE_NAMESPACE
class Music(atom.AtomBase):
"""The YouTube Music element"""
_tag = 'music'
_namespace = YOUTUBE_NAMESPACE
class Occupation(atom.AtomBase):
"""The YouTube Occupation element"""
_tag = 'occupation'
_namespace = YOUTUBE_NAMESPACE
class School(atom.AtomBase):
"""The YouTube School element"""
_tag = 'school'
_namespace = YOUTUBE_NAMESPACE
class Relationship(atom.AtomBase):
"""The YouTube Relationship element"""
_tag = 'relationship'
_namespace = YOUTUBE_NAMESPACE
class Recorded(atom.AtomBase):
"""The YouTube Recorded element"""
_tag = 'recorded'
_namespace = YOUTUBE_NAMESPACE
class Statistics(atom.AtomBase):
"""The YouTube Statistics element."""
_tag = 'statistics'
_namespace = YOUTUBE_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['viewCount'] = 'view_count'
_attributes['videoWatchCount'] = 'video_watch_count'
_attributes['subscriberCount'] = 'subscriber_count'
_attributes['lastWebAccess'] = 'last_web_access'
_attributes['favoriteCount'] = 'favorite_count'
def __init__(self, view_count=None, video_watch_count=None,
favorite_count=None, subscriber_count=None, last_web_access=None,
extension_elements=None, extension_attributes=None, text=None):
self.view_count = view_count
self.video_watch_count = video_watch_count
self.subscriber_count = subscriber_count
self.last_web_access = last_web_access
self.favorite_count = favorite_count
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Status(atom.AtomBase):
"""The YouTube Status element"""
_tag = 'status'
_namespace = YOUTUBE_NAMESPACE
class Position(atom.AtomBase):
"""The YouTube Position element. The position in a playlist feed."""
_tag = 'position'
_namespace = YOUTUBE_NAMESPACE
class Racy(atom.AtomBase):
"""The YouTube Racy element."""
_tag = 'racy'
_namespace = YOUTUBE_NAMESPACE
class Description(atom.AtomBase):
"""The YouTube Description element."""
_tag = 'description'
_namespace = YOUTUBE_NAMESPACE
class Private(atom.AtomBase):
"""The YouTube Private element."""
_tag = 'private'
_namespace = YOUTUBE_NAMESPACE
class NoEmbed(atom.AtomBase):
"""The YouTube VideoShare element. Whether a video can be embedded or not."""
_tag = 'noembed'
_namespace = YOUTUBE_NAMESPACE
class Comments(atom.AtomBase):
"""The GData Comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.feed_link = feed_link
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class Rating(atom.AtomBase):
"""The GData Rating element"""
_tag = 'rating'
_namespace = gdata.GDATA_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['min'] = 'min'
_attributes['max'] = 'max'
_attributes['numRaters'] = 'num_raters'
_attributes['average'] = 'average'
def __init__(self, min=None, max=None,
num_raters=None, average=None, extension_elements=None,
extension_attributes=None, text=None):
self.min = min
self.max = max
self.num_raters = num_raters
self.average = average
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class YouTubePlaylistVideoEntry(gdata.GDataEntry):
"""Represents a YouTubeVideoEntry on a YouTubePlaylist."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}position' % YOUTUBE_NAMESPACE] = ('position', Position)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, feed_link=None, description=None,
rating=None, comments=None, statistics=None,
location=None, position=None, media=None,
extension_elements=None, extension_attributes=None):
self.feed_link = feed_link
self.description = description
self.rating = rating
self.comments = comments
self.statistics = statistics
self.location = location
self.position = position
self.media = media
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubeVideoCommentEntry(gdata.GDataEntry):
"""Represents a comment on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class YouTubeSubscriptionEntry(gdata.GDataEntry):
"""Represents a subscription entry on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}queryString' % YOUTUBE_NAMESPACE] = (
'query_string', QueryString)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, username=None, query_string=None, feed_link=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.query_string = query_string
self.feed_link = feed_link
def GetSubscriptionType(self):
"""Retrieve the type of this subscription.
Returns:
A string that is either 'channel, 'query' or 'favorites'
"""
for category in self.category:
if category.scheme == YOUTUBE_SUBSCRIPTION_TYPE_SCHEME:
return category.term
class YouTubeVideoResponseEntry(gdata.GDataEntry):
"""Represents a video response. """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None,
extension_elements=None, extension_attributes=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.media = media or Media.Group()
class YouTubeContactEntry(gdata.GDataEntry):
"""Represents a contact entry."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}status' % YOUTUBE_NAMESPACE] = ('status', Status)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, status=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated)
self.username = username
self.status = status
class YouTubeVideoEntry(gdata.GDataEntry):
"""Represents a video on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}recorded' % YOUTUBE_NAMESPACE] = ('recorded', Recorded)
_children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy)
_children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group)
_children['{%s}where' % gdata.geo.GEORSS_NAMESPACE] = ('geo', Geo.Where)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None, rating=None,
noembed=None, statistics=None, racy=None, media=None, geo=None,
recorded=None, comments=None, extension_elements=None,
extension_attributes=None):
self.rating = rating
self.noembed = noembed
self.statistics = statistics
self.racy = racy
self.comments = comments
self.media = media or Media.Group()
self.geo = geo
self.recorded = recorded
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
def GetSwfUrl(self):
"""Return the URL for the embeddable Video
Returns:
URL of the embeddable video
"""
if self.media.content:
for content in self.media.content:
if content.extension_attributes[YOUTUBE_FORMAT] == '5':
return content.url
else:
return None
def AddDeveloperTags(self, developer_tags):
"""Add a developer tag for this entry.
Developer tags can only be set during the initial upload.
Arguments:
developer_tags: A list of developer tags as strings.
Returns:
A list of all developer tags for this video entry.
"""
for tag_text in developer_tags:
self.media.category.append(gdata.media.Category(
text=tag_text, label=tag_text, scheme=YOUTUBE_DEVELOPER_TAG_SCHEME))
return self.GetDeveloperTags()
def GetDeveloperTags(self):
"""Retrieve developer tags for this video entry."""
developer_tags = []
for category in self.media.category:
if category.scheme == YOUTUBE_DEVELOPER_TAG_SCHEME:
developer_tags.append(category)
if len(developer_tags) > 0:
return developer_tags
def GetYouTubeCategoryAsString(self):
"""Convenience method to return the YouTube category as string.
YouTubeVideoEntries can contain multiple Category objects with differing
schemes. This method returns only the category with the correct
scheme, ignoring developer tags.
"""
for category in self.media.category:
if category.scheme != YOUTUBE_DEVELOPER_TAG_SCHEME:
return category.text
class YouTubeUserEntry(gdata.GDataEntry):
"""Represents a user on YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username)
_children['{%s}firstName' % YOUTUBE_NAMESPACE] = ('first_name', FirstName)
_children['{%s}lastName' % YOUTUBE_NAMESPACE] = ('last_name', LastName)
_children['{%s}age' % YOUTUBE_NAMESPACE] = ('age', Age)
_children['{%s}books' % YOUTUBE_NAMESPACE] = ('books', Books)
_children['{%s}gender' % YOUTUBE_NAMESPACE] = ('gender', Gender)
_children['{%s}company' % YOUTUBE_NAMESPACE] = ('company', Company)
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}hobbies' % YOUTUBE_NAMESPACE] = ('hobbies', Hobbies)
_children['{%s}hometown' % YOUTUBE_NAMESPACE] = ('hometown', Hometown)
_children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location)
_children['{%s}movies' % YOUTUBE_NAMESPACE] = ('movies', Movies)
_children['{%s}music' % YOUTUBE_NAMESPACE] = ('music', Music)
_children['{%s}occupation' % YOUTUBE_NAMESPACE] = ('occupation', Occupation)
_children['{%s}school' % YOUTUBE_NAMESPACE] = ('school', School)
_children['{%s}relationship' % YOUTUBE_NAMESPACE] = ('relationship',
Relationship)
_children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
_children['{%s}thumbnail' % gdata.media.MEDIA_NAMESPACE] = ('thumbnail',
Media.Thumbnail)
def __init__(self, author=None, category=None, content=None, atom_id=None,
link=None, published=None, title=None, updated=None,
username=None, first_name=None, last_name=None, age=None,
books=None, gender=None, company=None, description=None,
hobbies=None, hometown=None, location=None, movies=None,
music=None, occupation=None, school=None, relationship=None,
statistics=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.username = username
self.first_name = first_name
self.last_name = last_name
self.age = age
self.books = books
self.gender = gender
self.company = company
self.description = description
self.hobbies = hobbies
self.hometown = hometown
self.location = location
self.movies = movies
self.music = music
self.occupation = occupation
self.school = school
self.relationship = relationship
self.statistics = statistics
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published,
title=title, updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class YouTubeVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a video feed on YouTube."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [YouTubeVideoEntry])
class YouTubePlaylistEntry(gdata.GDataEntry):
"""Represents a playlist in YouTube."""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}description' % YOUTUBE_NAMESPACE] = ('description',
Description)
_children['{%s}private' % YOUTUBE_NAMESPACE] = ('private',
Private)
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
[gdata.FeedLink])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None, title=None,
updated=None, private=None, feed_link=None,
description=None, extension_elements=None,
extension_attributes=None):
self.description = description
self.private = private
self.feed_link = feed_link
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id,
link=link, published=published, title=title,
updated=updated,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
class YouTubePlaylistFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a user's playlists """
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistEntry])
class YouTubePlaylistVideoFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video entry on a playlist."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubePlaylistVideoEntry])
class YouTubeContactFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users contacts."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeContactEntry])
class YouTubeSubscriptionFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of a users subscriptions."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeSubscriptionEntry])
class YouTubeVideoCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of comments for a video."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoCommentEntry])
class YouTubeVideoResponseFeed(gdata.GDataFeed, gdata.LinkFinder):
"""Represents a feed of video responses."""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[YouTubeVideoResponseEntry])
def YouTubeVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoEntry, xml_string)
def YouTubeContactFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactFeed, xml_string)
def YouTubeContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeContactEntry, xml_string)
def YouTubeVideoCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentFeed, xml_string)
def YouTubeVideoCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoCommentEntry, xml_string)
def YouTubeUserFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string)
def YouTubeUserEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeUserEntry, xml_string)
def YouTubePlaylistFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistFeed, xml_string)
def YouTubePlaylistVideoFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoFeed, xml_string)
def YouTubePlaylistEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistEntry, xml_string)
def YouTubePlaylistVideoEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubePlaylistVideoEntry, xml_string)
def YouTubeSubscriptionFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionFeed, xml_string)
def YouTubeSubscriptionEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeSubscriptionEntry, xml_string)
def YouTubeVideoResponseFeedFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseFeed, xml_string)
def YouTubeVideoResponseEntryFromString(xml_string):
return atom.CreateClassFromXMLString(YouTubeVideoResponseEntry, xml_string)

View File

@@ -0,0 +1,264 @@
#!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains a client to communicate with the YouTube servers.
A quick and dirty port of the YouTube GDATA 1.0 Python client
libraries to version 2.0 of the GDATA library.
"""
# __author__ = 's.@google.com (John Skidgel)'
import logging
import gdata.client
import gdata.youtube.data
import atom.data
import atom.http_core
# Constants
# -----------------------------------------------------------------------------
YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL = 'https://www.google.com/youtube/accounts/ClientLogin'
YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime',
'flv')
YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month',
'all_time')
YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating',
'relevance')
YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude')
YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6')
YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured',
'top_rated', 'most_viewed','watch_on_mobile')
YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken'
YOUTUBE_SERVER = 'gdata.youtube.com/feeds/api'
YOUTUBE_SERVICE = 'youtube'
YOUTUBE_VIDEO_FEED_URI = 'http://%s/videos' % YOUTUBE_SERVER
YOUTUBE_USER_FEED_URI = 'http://%s/users/' % YOUTUBE_SERVER
# Takes a youtube video ID.
YOUTUBE_CAPTION_FEED_URI = 'http://gdata.youtube.com/feeds/api/videos/%s/captions'
# Takes a youtube video ID and a caption track ID.
YOUTUBE_CAPTION_URI = 'http://gdata.youtube.com/feeds/api/videos/%s/captiondata/%s'
YOUTUBE_CAPTION_MIME_TYPE = 'application/vnd.youtube.timedtext; charset=UTF-8'
# Classes
# -----------------------------------------------------------------------------
class Error(Exception):
"""Base class for errors within the YouTube service."""
pass
class RequestError(Error):
"""Error class that is thrown in response to an invalid HTTP Request."""
pass
class YouTubeError(Error):
"""YouTube service specific error class."""
pass
class YouTubeClient(gdata.client.GDClient):
"""Client for the YouTube service.
Performs a partial list of Google Data YouTube API functions, such as
retrieving the videos feed for a user and the feed for a video.
YouTube Service requires authentication for any write, update or delete
actions.
"""
api_version = '2'
auth_service = YOUTUBE_SERVICE
auth_scopes = ['http://%s' % YOUTUBE_SERVER, 'https://%s' % YOUTUBE_SERVER]
def get_videos(self, uri=YOUTUBE_VIDEO_FEED_URI, auth_token=None,
desired_class=gdata.youtube.data.VideoFeed,
**kwargs):
"""Retrieves a YouTube video feed.
Args:
uri: A string representing the URI of the feed that is to be retrieved.
Returns:
A YouTubeVideoFeed if successfully retrieved.
"""
return self.get_feed(uri, auth_token=auth_token,
desired_class=desired_class,
**kwargs)
GetVideos = get_videos
def get_user_feed(self, uri=None, username=None):
"""Retrieve a YouTubeVideoFeed of user uploaded videos.
Either a uri or a username must be provided. This will retrieve list
of videos uploaded by specified user. The uri will be of format
"http://gdata.youtube.com/feeds/api/users/{username}/uploads".
Args:
uri: An optional string representing the URI of the user feed that is
to be retrieved.
username: An optional string representing the username.
Returns:
A YouTubeUserFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a username to the
GetYouTubeUserFeed() method.
"""
if uri is None and username is None:
raise YouTubeError('You must provide at least a uri or a username '
'to the GetYouTubeUserFeed() method')
elif username and not uri:
uri = '%s%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads')
return self.get_feed(uri, desired_class=gdata.youtube.data.VideoFeed)
GetUserFeed = get_user_feed
def get_video_entry(self, uri=None, video_id=None,
auth_token=None, **kwargs):
"""Retrieve a YouTubeVideoEntry.
Either a uri or a video_id must be provided.
Args:
uri: An optional string representing the URI of the entry that is to
be retrieved.
video_id: An optional string representing the ID of the video.
Returns:
A YouTubeVideoFeed if successfully retrieved.
Raises:
YouTubeError: You must provide at least a uri or a video_id to the
GetYouTubeVideoEntry() method.
"""
if uri is None and video_id is None:
raise YouTubeError('You must provide at least a uri or a video_id '
'to the get_youtube_video_entry() method')
elif video_id and uri is None:
uri = '%s/%s' % (YOUTUBE_VIDEO_FEED_URI, video_id)
return self.get_feed(uri,
desired_class=gdata.youtube.data.VideoEntry,
auth_token=auth_token,
**kwargs)
GetVideoEntry = get_video_entry
def get_caption_feed(self, uri):
"""Retrieve a Caption feed of tracks.
Args:
uri: A string representing the caption feed's URI to be retrieved.
Returns:
A YouTube CaptionFeed if successfully retrieved.
"""
return self.get_feed(uri, desired_class=gdata.youtube.data.CaptionFeed)
GetCaptionFeed = get_caption_feed
def get_caption_track(self, track_url, client_id,
developer_key, auth_token=None, **kwargs):
http_request = atom.http_core.HttpRequest(uri = track_url, method = 'GET')
dev_key = 'key=' + developer_key
authsub = 'AuthSub token="' + str(auth_token) + '"'
http_request.headers = {
'Authorization': authsub,
'X-GData-Client': client_id,
'X-GData-Key': dev_key
}
return self.request(http_request=http_request, **kwargs)
GetCaptionTrack = get_caption_track
def create_track(self, video_id, title, language, body, client_id,
developer_key, auth_token=None, title_type='text', **kwargs):
"""Creates a closed-caption track and adds to an existing YouTube video.
"""
new_entry = gdata.youtube.data.TrackEntry(
content = gdata.youtube.data.TrackContent(text = body, lang = language))
uri = YOUTUBE_CAPTION_FEED_URI % video_id
http_request = atom.http_core.HttpRequest(uri = uri, method = 'POST')
dev_key = 'key=' + developer_key
authsub = 'AuthSub token="' + str(auth_token) + '"'
http_request.headers = {
'Content-Type': YOUTUBE_CAPTION_MIME_TYPE,
'Content-Language': language,
'Slug': title,
'Authorization': authsub,
'GData-Version': self.api_version,
'X-GData-Client': client_id,
'X-GData-Key': dev_key
}
http_request.add_body_part(body, http_request.headers['Content-Type'])
return self.request(http_request = http_request,
desired_class = new_entry.__class__, **kwargs)
CreateTrack = create_track
def delete_track(self, video_id, track, client_id, developer_key,
auth_token=None, **kwargs):
"""Deletes a track."""
if isinstance(track, gdata.youtube.data.TrackEntry):
track_id_text_node = track.get_id().split(':')
track_id = track_id_text_node[3]
else:
track_id = track
uri = YOUTUBE_CAPTION_URI % (video_id, track_id)
http_request = atom.http_core.HttpRequest(uri = uri, method = 'DELETE')
dev_key = 'key=' + developer_key
authsub = 'AuthSub token="' + str(auth_token) + '"'
http_request.headers = {
'Authorization': authsub,
'GData-Version': self.api_version,
'X-GData-Client': client_id,
'X-GData-Key': dev_key
}
return self.request(http_request=http_request, **kwargs)
DeleteTrack = delete_track
def update_track(self, video_id, track, body, client_id, developer_key,
auth_token=None, **kwargs):
"""Updates a closed-caption track for an existing YouTube video.
"""
track_id_text_node = track.get_id().split(':')
track_id = track_id_text_node[3]
uri = YOUTUBE_CAPTION_URI % (video_id, track_id)
http_request = atom.http_core.HttpRequest(uri = uri, method = 'PUT')
dev_key = 'key=' + developer_key
authsub = 'AuthSub token="' + str(auth_token) + '"'
http_request.headers = {
'Content-Type': YOUTUBE_CAPTION_MIME_TYPE,
'Authorization': authsub,
'GData-Version': self.api_version,
'X-GData-Client': client_id,
'X-GData-Key': dev_key
}
http_request.add_body_part(body, http_request.headers['Content-Type'])
return self.request(http_request = http_request,
desired_class = track.__class__, **kwargs)
UpdateTrack = update_track

View File

@@ -0,0 +1,502 @@
#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains the data classes of the YouTube Data API"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import atom.core
import atom.data
import gdata.data
import gdata.geo.data
import gdata.media.data
import gdata.opensearch.data
import gdata.youtube.data
YT_TEMPLATE = '{http://gdata.youtube.com/schemas/2007/}%s'
class ComplaintEntry(gdata.data.GDEntry):
"""Describes a complaint about a video"""
class ComplaintFeed(gdata.data.GDFeed):
"""Describes complaints about a video"""
entry = [ComplaintEntry]
class RatingEntry(gdata.data.GDEntry):
"""A rating about a video"""
rating = gdata.data.Rating
class RatingFeed(gdata.data.GDFeed):
"""Describes ratings for a video"""
entry = [RatingEntry]
class YouTubeMediaContent(gdata.media.data.MediaContent):
"""Describes a you tube media content"""
_qname = gdata.media.data.MEDIA_TEMPLATE % 'content'
format = 'format'
class YtAge(atom.core.XmlElement):
"""User's age"""
_qname = YT_TEMPLATE % 'age'
class YtBooks(atom.core.XmlElement):
"""User's favorite books"""
_qname = YT_TEMPLATE % 'books'
class YtCompany(atom.core.XmlElement):
"""User's company"""
_qname = YT_TEMPLATE % 'company'
class YtDescription(atom.core.XmlElement):
"""Description"""
_qname = YT_TEMPLATE % 'description'
class YtDuration(atom.core.XmlElement):
"""Video duration"""
_qname = YT_TEMPLATE % 'duration'
seconds = 'seconds'
class YtFirstName(atom.core.XmlElement):
"""User's first name"""
_qname = YT_TEMPLATE % 'firstName'
class YtGender(atom.core.XmlElement):
"""User's gender"""
_qname = YT_TEMPLATE % 'gender'
class YtHobbies(atom.core.XmlElement):
"""User's hobbies"""
_qname = YT_TEMPLATE % 'hobbies'
class YtHometown(atom.core.XmlElement):
"""User's hometown"""
_qname = YT_TEMPLATE % 'hometown'
class YtLastName(atom.core.XmlElement):
"""User's last name"""
_qname = YT_TEMPLATE % 'lastName'
class YtLocation(atom.core.XmlElement):
"""Location"""
_qname = YT_TEMPLATE % 'location'
class YtMovies(atom.core.XmlElement):
"""User's favorite movies"""
_qname = YT_TEMPLATE % 'movies'
class YtMusic(atom.core.XmlElement):
"""User's favorite music"""
_qname = YT_TEMPLATE % 'music'
class YtNoEmbed(atom.core.XmlElement):
"""Disables embedding for the video"""
_qname = YT_TEMPLATE % 'noembed'
class YtOccupation(atom.core.XmlElement):
"""User's occupation"""
_qname = YT_TEMPLATE % 'occupation'
class YtPlaylistId(atom.core.XmlElement):
"""Playlist id"""
_qname = YT_TEMPLATE % 'playlistId'
class YtPosition(atom.core.XmlElement):
"""Video position on the playlist"""
_qname = YT_TEMPLATE % 'position'
class YtPrivate(atom.core.XmlElement):
"""Flags the entry as private"""
_qname = YT_TEMPLATE % 'private'
class YtQueryString(atom.core.XmlElement):
"""Keywords or query string associated with a subscription"""
_qname = YT_TEMPLATE % 'queryString'
class YtRacy(atom.core.XmlElement):
"""Mature content"""
_qname = YT_TEMPLATE % 'racy'
class YtRecorded(atom.core.XmlElement):
"""Date when the video was recorded"""
_qname = YT_TEMPLATE % 'recorded'
class YtRelationship(atom.core.XmlElement):
"""User's relationship status"""
_qname = YT_TEMPLATE % 'relationship'
class YtSchool(atom.core.XmlElement):
"""User's school"""
_qname = YT_TEMPLATE % 'school'
class YtStatistics(atom.core.XmlElement):
"""Video and user statistics"""
_qname = YT_TEMPLATE % 'statistics'
favorite_count = 'favoriteCount'
video_watch_count = 'videoWatchCount'
view_count = 'viewCount'
last_web_access = 'lastWebAccess'
subscriber_count = 'subscriberCount'
class YtStatus(atom.core.XmlElement):
"""Status of a contact"""
_qname = YT_TEMPLATE % 'status'
class YtUserProfileStatistics(YtStatistics):
"""User statistics"""
_qname = YT_TEMPLATE % 'statistics'
class YtUsername(atom.core.XmlElement):
"""Youtube username"""
_qname = YT_TEMPLATE % 'username'
class FriendEntry(gdata.data.BatchEntry):
"""Describes a contact in friend list"""
username = YtUsername
status = YtStatus
email = gdata.data.Email
class FriendFeed(gdata.data.BatchFeed):
"""Describes user's friends"""
entry = [FriendEntry]
class YtVideoStatistics(YtStatistics):
"""Video statistics"""
_qname = YT_TEMPLATE % 'statistics'
class ChannelEntry(gdata.data.GDEntry):
"""Describes a video channel"""
class ChannelFeed(gdata.data.GDFeed):
"""Describes channels"""
entry = [ChannelEntry]
class FavoriteEntry(gdata.data.BatchEntry):
"""Describes a favorite video"""
class FavoriteFeed(gdata.data.BatchFeed):
"""Describes favorite videos"""
entry = [FavoriteEntry]
class YouTubeMediaCredit(gdata.media.data.MediaCredit):
"""Describes a you tube media credit"""
_qname = gdata.media.data.MEDIA_TEMPLATE % 'credit'
type = 'type'
class YouTubeMediaRating(gdata.media.data.MediaRating):
"""Describes a you tube media rating"""
_qname = gdata.media.data.MEDIA_TEMPLATE % 'rating'
country = 'country'
class YtAboutMe(atom.core.XmlElement):
"""User's self description"""
_qname = YT_TEMPLATE % 'aboutMe'
class UserProfileEntry(gdata.data.BatchEntry):
"""Describes an user's profile"""
relationship = YtRelationship
description = YtDescription
location = YtLocation
statistics = YtUserProfileStatistics
school = YtSchool
music = YtMusic
first_name = YtFirstName
gender = YtGender
occupation = YtOccupation
hometown = YtHometown
company = YtCompany
movies = YtMovies
books = YtBooks
username = YtUsername
about_me = YtAboutMe
last_name = YtLastName
age = YtAge
thumbnail = gdata.media.data.MediaThumbnail
hobbies = YtHobbies
class UserProfileFeed(gdata.data.BatchFeed):
"""Describes a feed of user's profile"""
entry = [UserProfileEntry]
class YtAspectRatio(atom.core.XmlElement):
"""The aspect ratio of a media file"""
_qname = YT_TEMPLATE % 'aspectRatio'
class YtBasePublicationState(atom.core.XmlElement):
"""Status of an unpublished entry"""
_qname = YT_TEMPLATE % 'state'
help_url = 'helpUrl'
class YtPublicationState(YtBasePublicationState):
"""Status of an unpublished video"""
_qname = YT_TEMPLATE % 'state'
name = 'name'
reason_code = 'reasonCode'
class YouTubeAppControl(atom.data.Control):
"""Describes a you tube app control"""
_qname = (atom.data.APP_TEMPLATE_V1 % 'control',
atom.data.APP_TEMPLATE_V2 % 'control')
state = YtPublicationState
class YtCaptionPublicationState(YtBasePublicationState):
"""Status of an unpublished caption track"""
_qname = YT_TEMPLATE % 'state'
reason_code = 'reasonCode'
name = 'name'
class YouTubeCaptionAppControl(atom.data.Control):
"""Describes a you tube caption app control"""
_qname = atom.data.APP_TEMPLATE_V2 % 'control'
state = YtCaptionPublicationState
class CaptionTrackEntry(gdata.data.GDEntry):
"""Describes a caption track"""
class CaptionTrackFeed(gdata.data.GDFeed):
"""Describes caption tracks"""
entry = [CaptionTrackEntry]
class YtCountHint(atom.core.XmlElement):
"""Hint as to how many entries the linked feed contains"""
_qname = YT_TEMPLATE % 'countHint'
class PlaylistLinkEntry(gdata.data.BatchEntry):
"""Describes a playlist"""
description = YtDescription
playlist_id = YtPlaylistId
count_hint = YtCountHint
private = YtPrivate
class PlaylistLinkFeed(gdata.data.BatchFeed):
"""Describes list of playlists"""
entry = [PlaylistLinkEntry]
class YtModerationStatus(atom.core.XmlElement):
"""Moderation status"""
_qname = YT_TEMPLATE % 'moderationStatus'
class YtPlaylistTitle(atom.core.XmlElement):
"""Playlist title"""
_qname = YT_TEMPLATE % 'playlistTitle'
class SubscriptionEntry(gdata.data.BatchEntry):
"""Describes user's channel subscritpions"""
count_hint = YtCountHint
playlist_title = YtPlaylistTitle
thumbnail = gdata.media.data.MediaThumbnail
username = YtUsername
query_string = YtQueryString
playlist_id = YtPlaylistId
class SubscriptionFeed(gdata.data.BatchFeed):
"""Describes list of user's video subscriptions"""
entry = [SubscriptionEntry]
class YtSpam(atom.core.XmlElement):
"""Indicates that the entry probably contains spam"""
_qname = YT_TEMPLATE % 'spam'
class CommentEntry(gdata.data.BatchEntry):
"""Describes a comment for a video"""
spam = YtSpam
class CommentFeed(gdata.data.BatchFeed):
"""Describes comments for a video"""
entry = [CommentEntry]
class YtUploaded(atom.core.XmlElement):
"""Date/Time at which the video was uploaded"""
_qname = YT_TEMPLATE % 'uploaded'
class YtVideoId(atom.core.XmlElement):
"""Video id"""
_qname = YT_TEMPLATE % 'videoid'
class YouTubeMediaGroup(gdata.media.data.MediaGroup):
"""Describes a you tube media group"""
_qname = gdata.media.data.MEDIA_TEMPLATE % 'group'
videoid = YtVideoId
private = YtPrivate
duration = YtDuration
aspect_ratio = YtAspectRatio
uploaded = YtUploaded
class VideoEntryBase(gdata.data.GDEntry):
"""Elements that describe or contain videos"""
group = YouTubeMediaGroup
statistics = YtVideoStatistics
racy = YtRacy
recorded = YtRecorded
where = gdata.geo.data.GeoRssWhere
rating = gdata.data.Rating
noembed = YtNoEmbed
location = YtLocation
comments = gdata.data.Comments
class PlaylistEntry(gdata.data.BatchEntry):
"""Describes a video in a playlist"""
description = YtDescription
position = YtPosition
class PlaylistFeed(gdata.data.BatchFeed):
"""Describes videos in a playlist"""
private = YtPrivate
group = YouTubeMediaGroup
playlist_id = YtPlaylistId
entry = [PlaylistEntry]
class VideoEntry(gdata.data.BatchEntry):
"""Describes a video"""
class VideoFeed(gdata.data.BatchFeed):
"""Describes a video feed"""
entry = [VideoEntry]
class VideoMessageEntry(gdata.data.BatchEntry):
"""Describes a video message"""
description = YtDescription
class VideoMessageFeed(gdata.data.BatchFeed):
"""Describes videos in a videoMessage"""
entry = [VideoMessageEntry]
class UserEventEntry(gdata.data.GDEntry):
"""Describes a user event"""
playlist_id = YtPlaylistId
videoid = YtVideoId
username = YtUsername
query_string = YtQueryString
rating = gdata.data.Rating
class UserEventFeed(gdata.data.GDFeed):
"""Describes list of events"""
entry = [UserEventEntry]
class VideoModerationEntry(gdata.data.GDEntry):
"""Describes video moderation"""
moderation_status = YtModerationStatus
videoid = YtVideoId
class VideoModerationFeed(gdata.data.GDFeed):
"""Describes a video moderation feed"""
entry = [VideoModerationEntry]
class TrackContent(atom.data.Content):
lang = atom.data.XML_TEMPLATE % 'lang'
class TrackEntry(gdata.data.GDEntry):
"""Represents the URL for a caption track"""
content = TrackContent
def get_caption_track_id(self):
"""Extracts the ID of this caption track.
Returns:
The caption track's id as a string.
"""
if self.id.text:
match = CAPTION_TRACK_ID_PATTERN.match(self.id.text)
if match:
return match.group(2)
return None
GetCaptionTrackId = get_caption_track_id
class CaptionFeed(gdata.data.GDFeed):
"""Represents a caption feed for a video on YouTube."""
entry = [TrackEntry]

File diff suppressed because it is too large Load Diff