code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python #-*- coding: UTF-8 -*- import gobject import gtk import rb import rhythmdb import logging,logging.handlers from FolderViewSource import FolderViewSource log=logging.getLogger('FolderView') class FolderViewEntryType(rhythmdb.EntryType): def __init__(self): rhythmdb.EntryType.__init__(self, name = 'FolderViewEntryType') class FolderView (rb.Plugin): def __init__(self): rb.Plugin.__init__(self) log.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) console_handler.setFormatter(logging.Formatter('%(name)s %(levelname)-8s %(module)s::%(funcName)s - %(message)s')) log.addHandler(console_handler) def activate(self, shell): self.shell = shell group = rb.rb_source_group_get_by_name ("library") self.db = shell.get_property("db") try: self.entry_type = FolderViewEntryType() self.db.register_entry_type(self.entry_type) except NotImplementedError: self.entry_type = self.db.entry_register_type("FolderViewEntryType") self.entry_type.can_sync_metadata = True self.entry_type.save_to_disk = True self.entry_type.category = rhythmdb.ENTRY_STREAM self.source = gobject.new (FolderViewSource, shell=self.shell, name="Folder View", entry_type=self.entry_type, plugin=self, source_group=group ) self.source.set_property( "icon", self.get_folder_closed_icon()) shell.append_source(self.source, None) shell.register_entry_type_for_source(self.source, self.entry_type) def deactivate(self, shell): log.info("deactivate") self.db.entry_delete_by_type(self.entry_type) #self.db.commit() self.db = None self.entry_type = None self.source.delete_thyself() self.source = None def get_folder_closed_icon(self): """ Returns a pixbuf with the current theme closed folder icon """ icon_theme = gtk.icon_theme_get_default() try: icon = icon_theme.load_icon("gnome-fs-directory", 24, 0) return icon except gobject.GError, exc: #print "Can't load icon", exc try: icon = icon_theme.load_icon("gtk-directory", 24, 0) return icon except: #print "Can't load default icon" return None
Python
#!/usr/bin/env python #-*- coding: UTF-8 -*- import gobject import gtk import rb import rhythmdb import logging,logging.handlers from FolderViewSource import FolderViewSource log=logging.getLogger('FolderView') class FolderViewEntryType(rhythmdb.EntryType): def __init__(self): rhythmdb.EntryType.__init__(self, name = 'FolderViewEntryType') class FolderView (rb.Plugin): def __init__(self): rb.Plugin.__init__(self) log.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) console_handler.setFormatter(logging.Formatter('%(name)s %(levelname)-8s %(module)s::%(funcName)s - %(message)s')) log.addHandler(console_handler) def activate(self, shell): self.shell = shell group = rb.rb_source_group_get_by_name ("library") self.db = shell.get_property("db") try: self.entry_type = FolderViewEntryType() self.db.register_entry_type(self.entry_type) except NotImplementedError: self.entry_type = self.db.entry_register_type("FolderViewEntryType") self.entry_type.can_sync_metadata = True self.entry_type.save_to_disk = True self.entry_type.category = rhythmdb.ENTRY_STREAM self.source = gobject.new (FolderViewSource, shell=self.shell, name="Folder View", entry_type=self.entry_type, plugin=self, source_group=group ) self.source.set_property( "icon", self.get_folder_closed_icon()) shell.append_source(self.source, None) shell.register_entry_type_for_source(self.source, self.entry_type) def deactivate(self, shell): log.info("deactivate") self.db.entry_delete_by_type(self.entry_type) #self.db.commit() self.db = None self.entry_type = None self.source.delete_thyself() self.source = None def get_folder_closed_icon(self): """ Returns a pixbuf with the current theme closed folder icon """ icon_theme = gtk.icon_theme_get_default() try: icon = icon_theme.load_icon("gnome-fs-directory", 24, 0) return icon except gobject.GError, exc: #print "Can't load icon", exc try: icon = icon_theme.load_icon("gtk-directory", 24, 0) return icon except: #print "Can't load default icon" return None
Python
#!/usr/bin/env python #-*- coding: UTF-8 -*- import gobject import gtk import os import gio import urllib import gconf import rb,rhythmdb import treefilebrowser import logging,logging.handlers log=logging.getLogger('FolderView') LAST_PATH_KEY = '/rhythmbox.plugin.FolderView.lastpath' class FolderViewSource(rb.BrowserSource): #__gproperties__ = {'plugin': (rb.Plugin, 'plugin', 'plugin', gobject.PARAM_WRITABLE|gobject.PARAM_CONSTRUCT_ONLY),} def __init__(self): rb.BrowserSource.__init__(self) self.shell = None self.g_client = gconf.client_get_default() self.library_location = urllib.unquote(self.g_client.get_list('/apps/rhythmbox/library_locations', gconf.VALUE_STRING)[0]) def do_impl_activate(self): log.info('Activate') if self.shell == None: self.shell = self.get_property('shell') self.db = self.shell.get_property('db') self.entry_type = self.get_property('entry-type') self.entry_view = self.get_entry_view() self.filebrowser.set_active_dir(gconf.client_get_default().get_without_default(LAST_PATH_KEY).get_string()) ui_browse=self.shell.get_ui_manager().get_widget('/ToolBar/Browse') #ui_browse.set_sensitive(False) ui_browse.hide() #gconf.client_get_default().set_string(LAST_PATH_KEY,userName) rb.BrowserSource.do_impl_activate(self) def do_impl_deactivate(self): log.info('Deactivate') ui_browse=self.shell.get_ui_manager().get_widget('/ToolBar/Browse') ui_browse.show() rb.BrowserSource.do_impl_deactivate(self) #uim.get_widget('/ToolBar/Browse').set_sensitive(False) #def set_entry(self, uri): # entry = self.db.entry_lookup_by_location(uri) # if entry != None: # if self.db.entry_get(entry, rhythmdb.PROP_DURATION) != 0: # #self.props.query_model.add_entry(entry, 0) # self.db.query_append(self.query, (rhythmdb.QUERY_PROP_SUFFIX, rhythmdb.PROP_LOCATION, self.db.entry_get(entry, rhythmdb.PROP_LOCATION))) def on_treeview_cursor_changed(self, widget): for row in self.props.query_model: entry = row[0] self.props.query_model.remove_entry(entry) self.query = self.db.query_new() song_type = self.db.entry_type_get_by_name('song') path = self.filebrowser.get_selected() gconf.client_get_default().set_string(LAST_PATH_KEY,path) #for item in os.listdir(path): # filename = os.path.join(path, item) # if os.path.isfile(filename): # tmp = str(path_to_uri(filename)) #self.set_entry(path_to_uri(filename)) self.db.query_append(self.query, (rhythmdb.QUERY_PROP_EQUALS, rhythmdb.PROP_TYPE, song_type)) self.db.query_append(self.query, (rhythmdb.QUERY_PROP_PREFIX, rhythmdb.PROP_LOCATION, path_to_uri(path))) self.db.do_full_query_parsed(self.props.query_model, self.query) if self.shell.props.shell_player.props.playing: pass else: self.shell.props.shell_player.stop() def do_impl_pack_paned (self, paned): self.__paned_box = gtk.HPaned() self.filebrowser = treefilebrowser.TreeFileBrowser(self.library_location[7:]) self.scrolled = self.filebrowser.get_scrolled() self.scrolled.set_size_request(200,-1) self.treeview = self.filebrowser.get_view() self.treeview.connect('cursor-changed', self.on_treeview_cursor_changed) self.pack_start(self.__paned_box) self.__paned_box.add1(self.scrolled) self.__paned_box.add2(paned) def path_to_uri(path): gfile = gio.File(path) return gfile.get_uri() gobject.type_register(FolderViewSource)
Python
#!/usr/bin/env pypy import os, sys, logging, re import argparse import fnmatch configurations = {'lite', 'pro'} package_dirs = { 'lite': ('src/cx/hell/android/pdfview',), 'pro': ('src/cx/hell/android/pdfviewpro',) } file_replaces = { 'lite': ( 'cx.hell.android.pdfview.', '"cx.hell.android.pdfview"', 'package cx.hell.android.pdfview;', 'android:icon="@drawable/pdfviewer"', ), 'pro': ( 'cx.hell.android.pdfviewpro.', '"cx.hell.android.pdfviewpro"', 'package cx.hell.android.pdfviewpro;', 'android:icon="@drawable/apvpro_icon"', ), } def make_comment(file_type, line): """Add comment to line and return modified line, but try not to add comments to already commented out lines.""" if file_type in ('java', 'c'): return '// ' + line if not line.startswith('//') else line elif file_type in ('html', 'xml'): return '<!-- ' + line.strip() + ' -->\n' if not line.strip().startswith('<!--') else line else: raise Exception("unknown file type: %s" % file_type) def remove_comment(file_type, line): """Remove comment from line, but only if line is commented, otherwise return unchanged line.""" if file_type in ('java', 'c'): if line.startswith('// '): return line[3:] else: return line elif file_type in ('html', 'xml'): if line.strip().startswith('<!-- ') and line.strip().endswith(' -->'): return line.strip()[5:-4] + '\n' else: return line else: raise Exception("unknown file type: %s" % file_type) def handle_comments(conf, file_type, lines, filename): new_lines = [] re_cmd_starts = re.compile(r'(?:(//|<!--))\s+#ifdef\s+(?P<def>[a-zA-Z]+)') re_cmd_ends = re.compile(r'(?:(//|<!--))\s+#endif') required_defs = [] for i, line in enumerate(lines): m = re_cmd_starts.search(line) if m: required_def = m.group('def') logging.debug("line %s:%d %s matches as start of %s" % (filename, i+1, line.strip(), required_def)) required_defs.append(required_def) new_lines.append(line) continue m = re_cmd_ends.search(line) if m: logging.debug("line %s:%d %s matches as endif" % (filename, i+1, line.strip())) required_defs.pop() new_lines.append(line) continue if len(required_defs) == 0: new_lines.append(line) elif len(required_defs) == 1 and required_defs[0] == conf: new_line = remove_comment(file_type, line) new_lines.append(new_line) else: new_line = make_comment(file_type, line) new_lines.append(new_line) assert len(new_lines) == len(lines) return new_lines def find_files(dirname, name): matches = [] for root, dirnames, filenames in os.walk(dirname): for filename in fnmatch.filter(filenames, name): matches.append(os.path.join(root, filename)) return matches def fix_package_dirs(conf): for i, dirname in enumerate(package_dirs[conf]): logging.debug("trying to restore %s" % dirname) if os.path.exists(dirname): if os.path.isdir(dirname): logging.debug(" already exists") continue else: logging.error(" %s already exists, but is not dir" % dirname) continue # find other name found_dirname = None for other_conf, other_dirnames in package_dirs.items(): other_dirname = other_dirnames[i] if other_conf == conf: continue # skip this conf when looking for other conf if os.path.isdir(other_dirname): if found_dirname is None: found_dirname = other_dirname else: # source dir already found :/ raise Exception("too many possible dirs for this package: %s, %s" % (found_dirname, other_dirname)) if found_dirname is None: raise Exception("didn't find %s" % dirname) # now rename found_dirname to dirname os.rename(found_dirname, dirname) logging.debug("renamed %s to %s" % (found_dirname, dirname)) def handle_comments_in_files(conf, file_type, filenames): for filename in filenames: lines = open(filename).readlines() new_lines = handle_comments(conf, file_type, lines, filename) if lines != new_lines: logging.debug("file %s comments changed" % filename) f = open(filename, 'w') f.write(''.join(new_lines)) f.close() del f def replace_in_files(conf, filenames): #logging.debug("about replace to %s in %s" % (conf, ', '.join(filenames))) other_confs = [other_conf for other_conf in file_replaces.keys() if other_conf != conf] #logging.debug("there are %d other confs to replace from: %s" % (len(other_confs), ', '.join(other_confs))) for filename in filenames: new_lines = [] lines = open(filename).readlines() for line in lines: new_line = line for i, target_string in enumerate(file_replaces[conf]): for other_conf in other_confs: source_string = file_replaces[other_conf][i] new_line = new_line.replace(source_string, target_string) new_lines.append(new_line) if new_lines != lines: logging.debug("file %s changed, writing..." % filename) f = open(filename, 'w') f.write(''.join(new_lines)) f.close() del f else: logging.debug("file %s didn't change, no need to rewrite" % filename) def fix_java_files(conf): filenames = find_files('src', name='*.java') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'java', filenames) def fix_xml_files(conf): filenames = find_files('.', name='*.xml') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'xml', filenames) def fix_html_files(conf): filenames = find_files('res', name='*.html') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'html', filenames) def fix_c_files(conf): filenames = find_files('jni/pdfview2', name='*.c') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'c', filenames) filenames = find_files('jni/pdfview2', name='*.h') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'c', filenames) def fix_resources(conf): pass def main(): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') parser = argparse.ArgumentParser(description='Switch project configurations') parser.add_argument('--configuration', dest='configuration', default='lite') args = parser.parse_args() if not os.path.exists('AndroidManifest.xml'): raise Exception('android manifest not found, please run this script from main project directory') conf = args.configuration if conf not in configurations: raise Exception("invalid configuration: %s" % conf) fix_package_dirs(conf) fix_java_files(conf) fix_xml_files(conf) fix_html_files(conf) fix_c_files(conf) fix_resources(conf) if __name__ == '__main__': main()
Python
from PyQt4 import QtGui, QtCore from fonttreemodel import FontTreeModel class FontTreeView(QtGui.QTreeView): def __init__(self, parent=None, folder=None): QtGui.QListView.__init__(self, parent) self.model = FontTreeModel(self, folder) self.setModel(self.model) self.setColumnWidth(0, 20) self.setIndentation(0) def changeFolder(self, folder): #self.model.getFolder(folder) #the above crashes self.model = FontTreeModel(self, folder) self.setModel(self.model) self.hide() self.show()
Python
# qt4 modules from PyQt4 import QtCore, QtGui, uic # python modeuls import sys, os.path # python imaging modules import ImageQt, ImageDraw, ImageFont, Image # Load icons icon_resource_file = os.path.join(os.path.dirname(__file__),"icons.rcc") QtCore.QResource.registerResource(icon_resource_file) # Load UI (FontPreviewForm, FontPreviewBase) = uic.loadUiType(os.path.join(os.path.dirname(__file__), "fontpreview.ui")) def requiresRedraw(func): """Wrapper for methods which require the widget to redraw.""" def wrapper(self, *args, **kargs): result = func(self, *args, **kargs) self.update() return result return wrapper class FontPreviewWidget(FontPreviewBase): """Font preview widget.""" def __init__(self, parent=0, *args): """Init font preview widget.""" FontPreviewBase.__init__(self) FontPreviewForm().setupUi(self) self.setupUi() # Default values self.fontFile = None self.sampleText = "Sample Text" self.sampleSize = 20 def setupUi(self): """Setup UI elements.""" self.fontSizeInput = self.findChild(QtGui.QSpinBox, "fontSizeInput") self.connect(self.fontSizeInput, QtCore.SIGNAL("valueChanged (int)"), self._internal_setSampleSize) self.fontNameLabel = self.findChild(QtGui.QLabel, "fontName") @property def fontName(self): """@return font name (not the font file name).""" if self.fontFile is None: return u"No font set" return ", ".join(ImageFont.truetype(self.fontFile, self.sampleSize).getname()) @requiresRedraw def setFontFile(self, font): """Set preview font.""" self._font_file = font try: self.fontNameLabel.setText(self.fontName) except: self._font_file = None self.fontNameLabel.setText(u"Error loading font %s " % font) def getFontFile(self): """Get preview font.""" return self._font_file fontFile = property(getFontFile, setFontFile) @requiresRedraw def setSampleText(self, text): """Set text to be used in preview.""" self._text = text def getSampleText(self): """Get text to be used in preview.""" return self._text sampleText = property(getSampleText, setSampleText) @requiresRedraw def _internal_setSampleSize(self, size): """Set sample size (without updating spinbox editor).""" self._sample_size = size def setSampleSize(self, size): """Set sample size and update spinbox editor.""" self._internal_setSampleSize(size) self.fontSizeInput.setValue(size) def getSampleSize(self): """Get sample font size.""" return self._sample_size sampleSize = property(getSampleSize, setSampleSize) def drawSampleText(self, size): """Draw sample text and return a QImage. @param size size of image to draw text on """ font = ImageFont.truetype(self.fontFile, self.sampleSize) image = Image.new("RGBA", (size.width(), size.height())) draw = ImageDraw.Draw(image) draw.setink("black") draw.text((0, 0), self.sampleText, font=font) return ImageQt.ImageQt(image) def sizeHint(self): """See QT4 Reference.""" return QtCore.QSize(*self.getSampleTextSize()) def getSampleTextSize(self): """Get size of rendered sample text using python imaging library.""" try: font = ImageFont.truetype(self.fontFile, self.sampleSize) except TypeError: return (10,10) #return font.getsize(self.sampleText) (width, height) = font.getsize(self.sampleText) #return (10,10) return (min(400, width), height) def paintEvent(self, event): """See QT4 Reference.""" if self.fontFile is None: # No font to render return painter = QtGui.QPainter(self) # Center drawing coordinates painter.translate(self.width() / 2, self.height() / 2) # Draw font preview on a buffer sample_render_size = QtCore.QSize(*self.getSampleTextSize()) sample = self.drawSampleText(sample_render_size) # Paint preview buffer to widget painter.translate(- sample_render_size.width() / 2, - sample_render_size.height() / 2) painter.drawImage(0,0,sample) # Test if __name__ == "__main__": app = QtGui.QApplication(sys.argv) font_preview = FontPreviewWidget() font_preview.fontFile = "/home/download/Fonts pack/Fonts/A033000D.TTF" font_preview.sampleText = "Sample text" font_preview.sampleSize = 50 font_preview.show() sys.exit(app.exec_())
Python
import os from PyQt4 import QtCore, QtGui from fonttreeview import FontTreeView class BrowsePane(QtGui.QWidget): '''A pane containing combobox and a list view with fonts in the selected folder''' def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.layout = QtGui.QVBoxLayout() self.setLayout(self.layout) self.dirsComboBox = QtGui.QComboBox(self) #FIXME: for testing purposes self.dirsComboBox.addItem("/home/download/Fonts/Fonts") self.fontsView = FontTreeView(self, self.dirsComboBox.currentText()) self.layout.addWidget(self.dirsComboBox) self.layout.addWidget(self.fontsView) self.connect(self.dirsComboBox, QtCore.SIGNAL("activated (const QString&)"), self.fontsView.changeFolder) if __name__ == '__main__': app = QtGui.QApplication([]) bp = BrowsePane() bp.show() app.exec_()
Python
import sys import os from PyQt4 import QtCore, QtGui from browsepane import * from fontpreview import * class MainUi(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.layout = QtGui.QHBoxLayout(self) self.setLayout(self.layout) self.bp = BrowsePane(self) self.layout.addWidget(self.bp) self.font_preview = QtGui.QWidget(self) self.font_preview = FontPreviewWidget() self.font_preview.sampleText = "Sample text" self.font_preview.sampleSize = 50 self.layout.addWidget(self.font_preview) self.connect(self.bp.fontsView, QtCore.SIGNAL("pressed (const QModelIndex &)"), self.refresh_preview) def refresh_preview(self, index): if not index.isValid() or index.column() != 1: return self.font_preview.hide() self.font_preview.fontFile = os.path.join(self.bp.fontsView.model.folder, index.internalPointer().data(index.column())) self.font_preview.show() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = MainUi() window.show() app.exec_()
Python
import ImageFont import glob, os.path files = glob.glob("/home/download/Fonts pack/Fonts/*.[Tt][Tt][Ff]") for file in files: try: font = ImageFont.truetype(file, 10) print "%s %s" % (os.path.basename(file), font.getname()) except IOError: pass
Python
import os, os.path from PyQt4 import QtCore, QtGui import ImageFont class FontTreeModel(QtCore.QAbstractItemModel): def __init__(self, parent=None, folder=None): QtCore.QAbstractItemModel.__init__(self, parent) self.rootItem = RootItem(["", "Name"]) if folder: self.folder = str(folder) self.getFolder(self.folder) def getFolder(self, folder): '''gets ttf paths from a folder.''' self.rootItem.childItems = [] for item in os.listdir(folder): if os.path.splitext(item)[-1].lower() == '.ttf': self.rootItem.appendChild(RowItem(item, self.rootItem)) self.emit(QtCore.SIGNAL("dataChanged()")) def columnCount(self, parent): if parent.isValid(): return parent.internalPointer().columnCount() else: return self.rootItem.columnCount() def data(self, index, role): if not index.isValid(): return QtCore.QVariant() if role == QtCore.Qt.CheckStateRole: if index.internalPointer().isCheckable(index): return QtCore.QVariant(index.internalPointer().checkState[index.column()]) if role == QtCore.Qt.DisplayRole and index.column() == 1: item = index.internalPointer() fontfile = str(item.data(index.column())) font_fullpath = os.path.join(self.folder, fontfile) #print font_fullpath fontname = "%s [%s]" % ImageFont.truetype(font_fullpath, 10).getname() return QtCore.QVariant(QtCore.QString(fontname)) return QtCore.QVariant() def flags(self, index): if not index.isValid(): return QtCore.Qt.ItemIsEnabled if index.internalPointer().isCheckable(index): return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable def headerData(self, section, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: return QtCore.QVariant(self.tr(self.rootItem.data(section))) return QtCore.QVariant() def index(self, row, column, parent): if row < 0 or column < 0 or row >= self.rowCount(parent) or column >= self.columnCount(parent): return QtCore.QModelIndex() if not parent.isValid(): parentItem = self.rootItem else: parentItem = parent.internalPointer() childItem = parentItem.child(row) if childItem: return self.createIndex(row, column, childItem) else: return QtCore.QModelIndex() def parent(self, index): if not index.isValid(): return QtCore.QModelIndex() childItem = index.internalPointer() parentItem = childItem.parent() if parentItem == self.rootItem: return QtCore.QModelIndex() return self.createIndex(parentItem.row(), 0, parentItem) def rowCount(self, parent): if parent.column() > 0: return 0 if not parent.isValid(): parentItem = self.rootItem else: parentItem = parent.internalPointer() return parentItem.childCount() def setData(self, index, value, role=QtCore.Qt.EditRole): if not index.isValid(): return False if role == QtCore.Qt.CheckStateRole: item = index.internalPointer() if item.isCheckable(index): if item.checkState[index.column()] == QtCore.Qt.Unchecked: item.checkState[index.column()] = QtCore.Qt.Checked else: item.checkState[index.column()] = QtCore.Qt.Unchecked self.emit(QtCore.SIGNAL("dataChanged(const QModelIndex&, const QModelIndex&)"), index, index) return True return False class RootItem(object): def __init__(self, text, parent=None): self.parentItem = parent self.itemData = text self.childItems = [] def appendChild(self, item): self.childItems.append(item) def child(self, row): return self.childItems[row] def childCount(self): return len(self.childItems) def columnCount(self): return len(self.itemData) def data(self, column): return self.itemData[column] def parent(self): return self.parentItem def row(self): if self.parentItem: return self.parentItem.childItems.index(self) return 0 def isCheckable(self, index): return False class RowItem(RootItem): def __init__(self, path, parent): #TODO: parse path into name RootItem.__init__(self, ["", path], parent) self.font_name = path self.isChckable = [True, False] self.checkState = [False, None] def isCheckable(self, index): return self.isChckable[index.column()]
Python
''' Created on 15.01.2011 @author: kupriyanov ''' import os, webfonts, json, sys filename = "f:\\!Develop\\android\\mkFonts\\mkFontsParser\\test\\METADATA" dirname = "f:\\!Develop\\android\\mkFonts\\mkFontsParser\\test\\googlefontdirectory\\" fonts = { 'version': '1', 'homepage': 'http://code.google.com/webfonts', 'donate': '', 'mirrors': 'http://android.kupriyanov.com/apps/fonts/google/', 'preview': 'http://android.kupriyanov.com/apps/fonts/google/preview/', 'fonts':{}, 'designers':None} fonts_list = [] designers_list = [] designers_dict = {} ''' parse font data ''' for f in os.listdir(dirname): if os.path.isdir(os.path.join(dirname, f)): try: if f == 'designers': continue font = webfonts.parceFontMetadata(os.path.join(dirname, f)) fonts_list.insert(len(fonts_list), font['font']) ''' parse designer data ''' #try: font['designer'] = webfonts.parceDesignerMetadata(dirname, font['designer']) #except IOError: # sys.stderr.write('[e]Failed to parse designer BIO:' + font['designer'].get('name',dirname) + '\n') designers_list.insert(len(designers_list), font['designer']) designers_dict[font['designer']['name']] = font['designer'] except NameError: sys.stderr.write('[w]skip invisible font\n') except: sys.stderr.write('[w]KeyError\n') fonts['designers'] = designers_dict fonts['fonts'] = fonts_list #fonts = {'fonts': font['font'], 'designers' : font['designer']} output = json.dumps(fonts, ensure_ascii=False, sort_keys=False, indent=4) print output f = open(r'f:\\!Develop\\android\\mkFonts\\mkFonts\\assets\\googlefontdirectory_dev.json', 'w') f.write(output) f.close() ################################ if __name__ == '__main__': pass
Python
''' Created on 15.01.2011 @author: kupriyanov ''' class Font(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.name = 'test'
Python
import os from compiler.ast import TryExcept data = {'license: ': None, 'url: ': None, 'category: ': None, 'subsets: ': None, 'family: ': None, 'group: ': None, 'designer: ': '/designer/name', 'profile: ': '/designer/description', 'profiledescriptionlicense: ': None, 'profiledescriptionlicenseurl: ': None, 'originaldesigner: ': None, 'approved: ': None, 'visibility: ': None, 'description: ': None } known_subsets = ('latin', 'cyrillic', 'khmer', 'arabic', 'greek', 'hebrew', 'korean', 'vietnamese') def parceFontMetadata(path): try: f = open(path + '\\METADATA', 'r') # open -- file may get suffix added by low-level library except ZeroDivisionError: print "Attempted to divide by zero" lines = f.readlines() #profiledescriptionlicense: #profiledescriptionlicenseurl: #approved: #originaldesigner: # "font-family": "Allan", # "category": "normal", # "font-style": "normal", # "font-weight": "bold", # "format": "truetype", # "local-name": "Allan", # "local-file": "Allan", # "preview": "Allan", # "url": "http://themes.googleusercontent.com/font?kit=QNNVW1nta25A1TfGw7wquPesZW2xOQ-xsNqO47m55DA", # "md5": null, # "subsets": { # "cyrillic": true, # "greek": true, # "khmer": true, # "latin": true # }, # "designer": "Anton Koovit", # "license": { # "name": null, # "url": null # } #"designers": [ # { # "name": "Steve Matteson", # "description": "Steve Matteson is the Director of Type Design for Ascender Corporation and has created hundreds of fonts for use in various screen display environments and print publishing since 1987. A graduate of the Rochester Institute of Technology, Steve has an extensive background in typography, design and printing which he has applied to his development of high quality typefaces. His work can be found in User Interface designs (such as Google's Android platform, Windows Vista and Xbox 360); in publishing (such as Andy, Bertham, Endurance Pro and Pescadero Pro); and for corporate branding (such as Alcon Labs, Microsoft and Symantec). He resides in Louisville, CO with his wife, 2 kids and 2 Labrador Retrievers.", # "image": "http://themes.googleusercontent.com/image?id=0BwVBOzw_-hbMM2I5Yjk1MWMtYmVlNi00ZTJmLTkyNjItNjU3MDExMTUxMTdl&th=150&tw=100", # "site": "http://www.ascendercorp.com" # } fontadata = {} fontadata['font'] = {'font-family': None, 'category': None, 'font-style': 'normal', 'font-weight': 'normal', 'format': 'truetype', 'local-name': None, 'local-file': None, 'preview': None, 'url': None, 'md5': None, 'subsets': {}, 'designer': None } fontadata['font']['license'] = {'name': None, 'url': None } fontadata['designer'] = {'name': None, 'description': None, 'image': None, 'site': None} visibility = True approved = True PARSING_START = False CURRENT_PREFIX = None for line in lines[:]: ''' skip comments ''' prefix = '#' if line.startswith(prefix): CURRENT_PREFIX = None PARSING_START = False continue ''' check visivility ''' prefix = 'visibility: ' if line.startswith(prefix): if line.find('INTERNAL') > -1: visibility = False PARSING_START = False continue prefix = 'approved: ' if line.startswith(prefix): if stripType(prefix, line) != 'true': approved = False PARSING_START = False continue prefix = 'license: ' if line.startswith(prefix): license = stripType(prefix, line) if license == 'OFL': fontadata['font']['license']['name'] = 'SIL Open Font License, 1.1' fontadata['font']['license']['url'] = 'http://scripts.sil.org/OFL' else: fontadata['font']['license']['name'] = stripType(prefix, line) PARSING_START = False continue prefix = 'designer: ' if line.startswith(prefix): fontadata['designer']['name'] = stripType(prefix, line) fontadata['font']['designer'] = stripType(prefix, line) PARSING_START = False continue prefix = 'profile: ' if line.startswith(prefix): fontadata['designer']['description'] = stripType(prefix, line) continue prefix = 'description: ' if line.startswith(prefix): CURRENT_PREFIX = prefix description = stripType(prefix, line) fontadata['font']['description'] = stripLast(description) PARSING_START = True continue prefix = 'description.ru: ' if line.startswith(prefix): CURRENT_PREFIX = prefix PARSING_START = True continue prefix = 'family: ' if line.startswith(prefix): fontadata['font']['font-family'] = stripType(prefix, line) fontadata['font']['local-name'] = doLocalName(stripType(prefix, line)) fontadata['font']['local-file'] = fontadata['font']['local-name'] fontadata['font']['preview'] = stripType(prefix, line) PARSING_START = False continue prefix = 'font.' if line.startswith(prefix): font = stripType(prefix, line) if fontadata['font'].has_key('names'): fontadata['font']['names'] += ', ' fontadata['font']['names'] += font else: fontadata['font']['names'] = font PARSING_START = False continue prefix = 'category: ' if line.startswith(prefix): fontadata['font']['category'] = stripType(prefix, line) PARSING_START = False continue prefix = 'subsets: ' if line.startswith(prefix): fontadata['font']['subsets'] = parseSubsets(prefix, line) PARSING_START = False continue prefix = 'url: ' if line.startswith(prefix): fontadata['designer']['site'] = stripType(prefix, line) PARSING_START = False continue ''' check if this string is still description ''' prefix = 'description: ' if prefix == CURRENT_PREFIX and PARSING_START == True: line = stripLast(line) fontadata['font']['description'] += ' ' fontadata['font']['description'] += line continue #end for if (approved == False or visibility == False): err = fontadata['font']['local-name'],'\t','visible:',visibility,'\t','approved:',approved,'\t',path raise NameError(err) ''' prevent no names ''' if fontadata['font']['local-name'] == None: fontadata['font']['font-family'] = os.path.basename(path) fontadata['font']['local-name'] = fontadata['font']['font-family'] fontadata['font']['local-file'] = fontadata['font']['font-family'] fontadata['font']['preview'] = fontadata['font']['font-family'] return fontadata def parceDesignerMetadata(dirname, designer_data): designer_name = designer_data['name'] designer_name = designer_name.replace(' ', '_') designer_name = designer_name.lower() # try: f = open(dirname + 'designers\\' + designer_name + '\\BIO', 'r') # open -- file may get suffix added by low-level library # except ZeroDivisionError: # print "Attempted to divide by zero" lines = f.readlines() #name: Tart Workshop #portrait: http://themes.googleusercontent.com/ #url: http://www.tartworkshop.com #bio: <p>Lettering artist/illustrator Crystal Kl PARSING_START = False CURRENT_PREFIX = None for line in lines[:]: ''' skip comments ''' prefix = '#' if line.startswith(prefix): PARSING_START = False continue prefix = 'name: ' if line.startswith(prefix): value = stripType(prefix, line) designer_data['name'] = value PARSING_START = False continue prefix = 'portrait: ' if line.startswith(prefix): value = stripType(prefix, line) designer_data['image'] = value PARSING_START = False continue prefix = 'bio: ' if line.startswith(prefix): value = stripType(prefix, line) value = stripLast(value) designer_data['description'] = value CURRENT_PREFIX = prefix PARSING_START = True continue prefix = 'url: ' if line.startswith(prefix): value = stripType(prefix, line) designer_data['site'] = value continue ''' check if this string is still description ''' prefix = 'bio: ' if prefix == CURRENT_PREFIX and PARSING_START == True: value = stripLast(line) designer_data['description'] += ' ' designer_data['description'] += value continue return designer_data def doLocalName(line): return line.replace(' ', '') def stripType(key, string): string = string.rstrip() return string.lstrip(key) def stripLast(line): line = line.strip() if line.endswith('\\'): line = line.rstrip('\\') line = line.strip() #if line.rfind( '\\' ): #print 'Found bad char on:',line.rfind( '\\' ),' : >',line,'<' return line def parseSubsets(key, string): string = string.rstrip() string = string.lstrip(key) subsets = string.split(',') subset_list = [] ''' check if subset is known ''' for subset in subsets[:]: if '+' in subset: subset_sublist = subset.split('+') print subset_sublist subset = subset_sublist[0] if subset in known_subsets: subset_list.insert(len(subset_list),subset) #print subsets,'->',subset_list return subset_list
Python
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This is a simple utility for dumping out the header of a compressed file, and # is suitable for doing spot checks of compressed. files. However, this only # implements the "long" form of the table directory. import struct import sys def dump_woff2_header(header): header_values = struct.unpack('>IIIHHIHHIIIII', header[:44]) for i, key in enumerate([ 'signature', 'flavor', 'length', 'numTables', 'reserved', 'totalSfntSize', 'majorVersion', 'minorVersion', 'metaOffset', 'metaOrigLength', 'privOffset', 'privLength']): print key, header_values[i] numTables = header_values[3] for i in range(numTables): entry = struct.unpack('>IIIII', header[44+20*i:44+20*(i+1)]) print '%08x %d %d %d %d' % entry def main(): header = file(sys.argv[1]).read() dump_woff2_header(header) main()
Python
from googlevoice import Voice, util from os import path, remove from unittest import TestCase, main class VoiceTest(TestCase): voice = Voice() voice.login() outgoing = util.input('Outgoing number (blank to ignore call tests): ') forwarding = None if outgoing: forwarding = util.input('Forwarding number [optional]: ') or None if outgoing: def test_1call(self): self.voice.call(self.outgoing, self.forwarding) def test_sms(self): self.voice.send_sms(self.outgoing, 'i sms u') def test_2cancel(self): self.voice.cancel(self.outgoing, self.forwarding) def test_special(self): self.assert_(self.voice.special) def test_inbox(self): self.assert_(self.voice.inbox) def test_balance(self): self.assert_(self.voice.settings['credits']) def test_search(self): self.assert_(len(self.voice.search('joe'))) def test_disable_enable(self): self.voice.phones[0].disable() self.voice.phones[0].enable() def test_download(self): msg = list(self.voice.voicemail.messages)[0] fn = '%s.mp3' % msg.id if path.isfile(fn): remove(fn) self.voice.download(msg) self.assert_(path.isfile(fn)) def test_zlogout(self): self.voice.logout() self.assert_(self.voice.special is None) def test_config(self): from conf import config self.assert_(config.forwardingNumber) self.assert_(str(config.phoneType) in '1237') self.assertEqual(config.get('wtf'), None) if __name__ == '__main__': main()
Python
DEFAULT_CONFIG = """ [auth] # Google Account email address (one associated w/ your Voice account) email= # Raw password used or login password= [gvoice] # Number to place calls from (eg, your google voice number) forwardingNumber= # Default phoneType for your forwardingNumber as defined below # 1 - Home # 2 - Mobile # 3 - Work # 7 - Gizmo phoneType=2 """ DEBUG = False LOGIN = 'https://accounts.google.com/ServiceLogin?service=grandcentral' FEEDS = ('inbox', 'starred', 'all', 'spam', 'trash', 'voicemail', 'sms', 'recorded', 'placed', 'received', 'missed') BASE = 'https://www.google.com/voice/' LOGOUT = BASE + 'account/signout' INBOX = BASE + '#inbox' CALL = BASE + 'call/connect/' CANCEL = BASE + 'call/cancel/' DEFAULT_FORWARD = BASE + 'settings/editDefaultForwarding/' FORWARD = BASE + 'settings/editForwarding/' DELETE = BASE + 'inbox/deleteMessages/' MARK = BASE + 'inbox/mark/' STAR = BASE + 'inbox/star/' SMS = BASE + 'sms/send/' DOWNLOAD = BASE + 'media/send_voicemail/' BALANCE = BASE + 'settings/billingcredit/' XML_SEARCH = BASE + 'inbox/search/' XML_CONTACTS = BASE + 'contacts/' XML_RECENT = BASE + 'inbox/recent/' XML_INBOX = XML_RECENT + 'inbox/' XML_STARRED = XML_RECENT + 'starred/' XML_ALL = XML_RECENT + 'all/' XML_SPAM = XML_RECENT + 'spam/' XML_TRASH = XML_RECENT + 'trash/' XML_VOICEMAIL = XML_RECENT + 'voicemail/' XML_SMS = XML_RECENT + 'sms/' XML_RECORDED = XML_RECENT + 'recorded/' XML_PLACED = XML_RECENT + 'placed/' XML_RECEIVED = XML_RECENT + 'received/' XML_MISSED = XML_RECENT + 'missed/'
Python
import re from sys import stdout from xml.parsers.expat import ParserCreate from time import gmtime from datetime import datetime from pprint import pprint try: from urllib2 import build_opener,install_opener, \ HTTPCookieProcessor,Request,urlopen from urllib import urlencode,quote except ImportError: from urllib.request import build_opener,install_opener, \ HTTPCookieProcessor,Request,urlopen from urllib.parse import urlencode,quote try: from http.cookiejar import LWPCookieJar as CookieJar except ImportError: from cookielib import LWPCookieJar as CookieJar try: from json import loads except ImportError: from simplejson import loads try: input = raw_input except NameError: input = input sha1_re = re.compile(r'^[a-fA-F0-9]{40}$') def print_(*values, **kwargs): """ Implementation of Python3's print function Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. """ fo = kwargs.pop('file', stdout) fo.write(kwargs.pop('sep', ' ').join(map(str, values))) fo.write(kwargs.pop('end', '\n')) fo.flush() def is_sha1(s): """ Returns ``True`` if the string is a SHA1 hash """ return bool(sha1_re.match(s)) def validate_response(response): """ Validates that the JSON response is A-OK """ try: assert 'ok' in response and response['ok'] except AssertionError: raise ValidationError('There was a problem with GV: %s' % response) def load_and_validate(response): """ Loads JSON data from http response then validates """ validate_response(loads(response.read())) class ValidationError(Exception): """ Bombs when response code back from Voice 500s """ class LoginError(Exception): """ Occurs when login credentials are incorrect """ class ParsingError(Exception): """ Happens when XML feed parsing fails """ class JSONError(Exception): """ Failed JSON deserialization """ class DownloadError(Exception): """ Cannot download message, probably not in voicemail/recorded """ class ForwardingError(Exception): """ Forwarding number given was incorrect """ class AttrDict(dict): def __getattr__(self, attr): if attr in self: return self[attr] class Phone(AttrDict): """ Wrapper for phone objects used for phone specific methods Attributes are: * id: int * phoneNumber: i18n phone number * formattedNumber: humanized phone number string * we: data dict * wd: data dict * verified: bool * name: strign label * smsEnabled: bool * scheduleSet: bool * policyBitmask: int * weekdayTimes: list * dEPRECATEDDisabled: bool * weekdayAllDay: bool * telephonyVerified * weekendTimes: list * active: bool * weekendAllDay: bool * enabledForOthers: bool * type: int (1 - Home, 2 - Mobile, 3 - Work, 4 - Gizmo) """ def __init__(self, voice, data): self.voice = voice super(Phone, self).__init__(data) def enable(self,): """ Enables this phone for usage """ return self.__call_forwarding() def disable(self): """ Disables this phone """ return self.__call_forwarding('0') def __call_forwarding(self, enabled='1'): """ Enables or disables this phone """ self.voice.__validate_special_page('default_forward', {'enabled':enabled, 'phoneId': self.id}) def __str__(self): return self.phoneNumber def __repr__(self): return '<Phone %s>' % self.phoneNumber class Message(AttrDict): """ Wrapper for all call/sms message instances stored in Google Voice Attributes are: * id: SHA1 identifier * isTrash: bool * displayStartDateTime: datetime * star: bool * isSpam: bool * startTime: gmtime * labels: list * displayStartTime: time * children: str * note: str * isRead: bool * displayNumber: str * relativeStartTime: str * phoneNumber: str * type: int """ def __init__(self, folder, id, data): assert is_sha1(id), 'Message id not a SHA1 hash' self.folder = folder self.id = id super(AttrDict, self).__init__(data) self['startTime'] = gmtime(int(self['startTime'])/1000) self['displayStartDateTime'] = datetime.strptime( self['displayStartDateTime'], '%m/%d/%y %I:%M %p') self['displayStartTime'] = self['displayStartDateTime'].time() def delete(self, trash=1): """ Moves this message to the Trash. Use ``message.delete(0)`` to move it out of the Trash. """ self.folder.voice.__messages_post('delete', self.id, trash=trash) def star(self, star=1): """ Star this message. Use ``message.star(0)`` to unstar it. """ self.folder.voice.__messages_post('star', self.id, star=star) def mark(self, read=1): """ Mark this message as read. Use ``message.mark(0)`` to mark it as unread. """ self.folder.voice.__messages_post('mark', self.id, read=read) def download(self, adir=None): """ Download the message MP3 (if any). Saves files to ``adir`` (defaults to current directory). Message hashes can be found in ``self.voicemail().messages`` for example. Returns location of saved file. """ return self.folder.voice.download(self, adir) def __str__(self): return self.id def __repr__(self): return '<Message #%s (%s)>' % (self.id, self.phoneNumber) class Folder(AttrDict): """ Folder wrapper for feeds from Google Voice Attributes are: * totalSize: int (aka ``__len__``) * unreadCounts: dict * resultsPerPage: int * messages: list of Message instances """ def __init__(self, voice, name, data): self.voice = voice self.name = name super(AttrDict, self).__init__(data) def messages(self): """ Returns a list of all messages in this folder """ return [Message(self, *i) for i in self['messages'].items()] messages = property(messages) def __len__(self): return self['totalSize'] def __repr__(self): return '<Folder %s (%s)>' % (self.name, len(self)) class XMLParser(object): """ XML Parser helper that can dig json and html out of the feeds. The parser takes a ``Voice`` instance, page name, and function to grab data from. Calling the parser calls the data function once, sets up the ``json`` and ``html`` attributes and returns a ``Folder`` instance for the given page:: >>> o = XMLParser(voice, 'voicemail', lambda: 'some xml payload') >>> o() ... <Folder ...> >>> o.json ... 'some json payload' >>> o.data ... 'loaded json payload' >>> o.html ... 'some html payload' """ attr = None def start_element(self, name, attrs): if name in ('json','html'): self.attr = name def end_element(self, name): self.attr = None def char_data(self, data): if self.attr and data: setattr(self, self.attr, getattr(self, self.attr) + data) def __init__(self, voice, name, datafunc): self.json, self.html = '','' self.datafunc = datafunc self.voice = voice self.name = name def __call__(self): self.json, self.html = '','' parser = ParserCreate() parser.StartElementHandler = self.start_element parser.EndElementHandler = self.end_element parser.CharacterDataHandler = self.char_data try: data = self.datafunc() parser.Parse(data, 1) except: raise ParsingError return self.folder def folder(self): """ Returns associated ``Folder`` instance for given page (``self.name``) """ return Folder(self.voice, self.name, self.data) folder = property(folder) def data(self): """ Returns the parsed json information after calling the XMLParser """ try: return loads(self.json) except: raise JSONError data = property(data)
Python
from ConfigParser import ConfigParser, NoOptionError import os import settings class Config(ConfigParser): """ ``ConfigParser`` subclass that looks into your home folder for a file named ``.gvoice`` and parses configuration data from it. """ def __init__(self): self.fname = os.path.expanduser('~/.gvoice') if not os.path.exists(self.fname): try: f = open(self.fname, 'w') except IOError: return f.write(settings.DEFAULT_CONFIG) f.close() ConfigParser.__init__(self) try: self.read([self.fname]) except IOError: return def get(self, option, section='gvoice'): try: return ConfigParser.get(self, section, option).strip() or None except NoOptionError: return def set(self, option, value, section='gvoice'): return ConfigParser.set(self, section, option, value) def phoneType(self): try: return int(self.get('phoneType')) except TypeError: return def save(self): f = open(self.fname, 'w') self.write(f) f.close() phoneType = property(phoneType) forwardingNumber = property(lambda self: self.get('forwardingNumber')) email = property(lambda self: self.get('email','auth')) password = property(lambda self: self.get('password','auth')) secret = property(lambda self: self.get('secret')) config = Config()
Python
from conf import config from util import * import settings import os if settings.DEBUG: import logging logging.basicConfig() log = logging.getLogger('PyGoogleVoice') log.setLevel(logging.DEBUG) else: log = None class Voice(object): """ Main voice instance for interacting with the Google Voice service Handles login/logout and most of the baser HTTP methods """ def __init__(self): install_opener(build_opener(HTTPCookieProcessor(CookieJar()))) for name in settings.FEEDS: setattr(self, name, self.__get_xml_page(name)) ###################### # Some handy methods ###################### def special(self): """ Returns special identifier for your session (if logged in) """ if hasattr(self, '_special') and getattr(self, '_special'): return self._special try: try: regex = bytes("('_rnr_se':) '(.+)'", 'utf8') except TypeError: regex = bytes("('_rnr_se':) '(.+)'") except NameError: regex = r"('_rnr_se':) '(.+)'" try: sp = re.search(regex, urlopen(settings.INBOX).read()).group(2) except AttributeError: sp = None self._special = sp return sp special = property(special) def login(self, email=None, passwd=None): """ Login to the service using your Google Voice account Credentials will be propmpted for if not given as args or in the ``~/.gvoice`` config file """ if hasattr(self, '_special') and getattr(self, '_special'): return self if email is None: email = config.email if email is None: email = input('Email address: ') if passwd is None: passwd = config.password if passwd is None: from getpass import getpass passwd = getpass() content = self.__do_page('login').read() # holy hackjob galx = re.search(r"name=\"GALX\"\s+value=\"(.+)\"", content).group(1) self.__do_page('login', {'Email': email, 'Passwd': passwd, 'GALX': galx}) del email, passwd try: assert self.special except (AssertionError, AttributeError): raise LoginError return self def logout(self): """ Logs out an instance and makes sure it does not still have a session """ self.__do_page('logout') del self._special assert self.special == None return self def call(self, outgoingNumber, forwardingNumber=None, phoneType=None, subscriberNumber=None): """ Make a call to an ``outgoingNumber`` from your ``forwardingNumber`` (optional). If you pass in your ``forwardingNumber``, please also pass in the correct ``phoneType`` """ if forwardingNumber is None: forwardingNumber = config.forwardingNumber if phoneType is None: phoneType = config.phoneType self.__validate_special_page('call', { 'outgoingNumber': outgoingNumber, 'forwardingNumber': forwardingNumber, 'subscriberNumber': subscriberNumber or 'undefined', 'phoneType': phoneType, 'remember': '1' }) __call__ = call def cancel(self, outgoingNumber=None, forwardingNumber=None): """ Cancels a call matching outgoing and forwarding numbers (if given). Will raise an error if no matching call is being placed """ self.__validate_special_page('cancel', { 'outgoingNumber': outgoingNumber or 'undefined', 'forwardingNumber': forwardingNumber or 'undefined', 'cancelType': 'C2C', }) def phones(self): """ Returns a list of ``Phone`` instances attached to your account. """ return [Phone(self, data) for data in self.contacts['phones'].values()] phones = property(phones) def settings(self): """ Dict of current Google Voice settings """ return AttrDict(self.contacts['settings']) settings = property(settings) def send_sms(self, phoneNumber, text): """ Send an SMS message to a given ``phoneNumber`` with the given ``text`` message """ self.__validate_special_page('sms', {'phoneNumber': phoneNumber, 'text': text}) def search(self, query): """ Search your Google Voice Account history for calls, voicemails, and sms Returns ``Folder`` instance containting matching messages """ return self.__get_xml_page('search', data='?q=%s' % quote(query))() def download(self, msg, adir=None): """ Download a voicemail or recorded call MP3 matching the given ``msg`` which can either be a ``Message`` instance, or a SHA1 identifier. Saves files to ``adir`` (defaults to current directory). Message hashes can be found in ``self.voicemail().messages`` for example. Returns location of saved file. """ from os import path,getcwd if isinstance(msg, Message): msg = msg.id assert is_sha1(msg), 'Message id not a SHA1 hash' if adir is None: adir = getcwd() try: response = self.__do_page('download', msg) except: raise DownloadError fn = path.join(adir, '%s.mp3' % msg) fo = open(fn, 'wb') fo.write(response.read()) fo.close() return fn def contacts(self): """ Partial data of your Google Account Contacts related to your Voice account. For a more comprehensive suite of APIs, check out http://code.google.com/apis/contacts/docs/1.0/developers_guide_python.html """ if hasattr(self, '_contacts'): return self._contacts self._contacts = self.__get_xml_page('contacts')() return self._contacts contacts = property(contacts) ###################### # Helper methods ###################### def __do_page(self, page, data=None, headers={}): """ Loads a page out of the settings and pass it on to urllib Request """ page = page.upper() if isinstance(data, dict) or isinstance(data, tuple): data = urlencode(data) headers.update({'User-Agent': 'PyGoogleVoice/0.5'}) if log: log.debug('%s?%s - %s' % (getattr(settings, page)[22:], data or '', headers)) if page in ('DOWNLOAD','XML_SEARCH'): return urlopen(Request(getattr(settings, page) + data, None, headers)) if data: headers.update({'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'}) return urlopen(Request(getattr(settings, page), data, headers)) def __validate_special_page(self, page, data={}, **kwargs): """ Validates a given special page for an 'ok' response """ data.update(kwargs) load_and_validate(self.__do_special_page(page, data)) _Phone__validate_special_page = __validate_special_page def __do_special_page(self, page, data=None, headers={}): """ Add self.special to request data """ assert self.special, 'You must login before using this page' if isinstance(data, tuple): data += ('_rnr_se', self.special) elif isinstance(data, dict): data.update({'_rnr_se': self.special}) return self.__do_page(page, data, headers) _Phone__do_special_page = __do_special_page def __get_xml_page(self, page, data=None, headers={}): """ Return XMLParser instance generated from given page """ return XMLParser(self, page, lambda: self.__do_special_page('XML_%s' % page.upper(), data, headers).read()) def __messages_post(self, page, *msgs, **kwargs): """ Performs message operations, eg deleting,staring,moving """ data = kwargs.items() for msg in msgs: if isinstance(msg, Message): msg = msg.id assert is_sha1(msg), 'Message id not a SHA1 hash' data += (('messages',msg),) return self.__do_special_page(page, dict(data)) _Message__messages_post = __messages_post
Python
""" This project aims to bring the power of the Google Voice API to the Python language in a simple, easy-to-use manner. Currently it allows you to place calls, send sms, download voicemails/recorded messages, and search the various folders of your Google Voice Accounts. You can use the Python API or command line script to schedule calls, check for new received calls/sms, or even sync your recorded voicemails/calls. Works for Python 2 and Python 3 """ __author__ = 'Justin Quick and Joe McCall' __email__ = 'justquick@gmail.com, joe@mcc4ll.us', __copyright__ = 'Copyright 2009, Justin Quick and Joe McCall' __credits__ = ['Justin Quick','Joe McCall','Jacob Feisley','John Nagle'] __license__ = 'New BSD' __version__ = '0.5' from voice import Voice from util import Phone, Message, Folder
Python
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__) sys.exit(1) import settings if __name__ == "__main__": execute_manager(settings)
Python
from django.http import HttpResponse from django.http import HttpResponseBadRequest from django.http import HttpResponseForbidden from django.http import HttpResponseNotAllowed from django.contrib.auth.decorators import login_required from django.shortcuts import redirect from django.shortcuts import render_to_response from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.core.context_processors import csrf from alpha.models import PhoneNumber from alpha.models import UserProfile from alpha.models import Activity from alpha.models import Invite from alpha.models import MassInvite from alpha.models import Review from alpha.models import Feedback from alpha.models import Prospective @login_required def stream(request, page=0): response = {'is_stream': True, 'page': page} page = int(page) response['next_page'] = str(page + 1) response['prev_page'] = str(page - 1) if page > 0 else None if request.user.is_staff: start = int(page) * 20 end = (int(page) + 1) * 20 if 'username' in request.GET: username = request.GET['username'] response['username'] = username response['activities'] = Activity.objects.filter( user__username=username).order_by('-created')[start:end] else: response['activities'] = Activity.objects.all().order_by('-created')[start:end] return render_to_response('admin_stream.html', response) else: return HttpResponseForbidden() @login_required def invites(request): response = {'is_invite': True} if request.user.is_staff: if request.method == 'POST': if request.POST['command'] == 'new_invite': code = User.objects.make_random_password(length=5, allowed_chars='123456789') invite = Invite(code=code) invite.save() redirect('/a/superadmin/invites') elif request.POST['command'] == 'new_mass_invite': code = User.objects.make_random_password(length=5, allowed_chars='123456789') name = request.POST['invite_name'] or 'N/A' invite = MassInvite(code=code, name=name) invite.save() redirect('/a/superadmin/invites') elif request.POST['command'] == 'delete': invite = Invite.objects.get(pk=request.POST['invite']) invite.delete() elif request.POST['command'] == 'disable': invite = MassInvite.objects.get(pk=request.POST['invite']) invite.disabled = not invite.disabled invite.save() response['invites'] = Invite.objects.all().order_by('used', '-created') response['mass_invites'] = MassInvite.objects.all().order_by('-created') response.update(csrf(request)) return render_to_response('admin_invites.html', response) else: return HttpResponseForbidden() @login_required def reports(request): response = {'is_invite': True} if request.user.is_staff: response['reports'] = Feedback.objects.all().order_by('-created') response.update(csrf(request)) return render_to_response('admin_report.html', response) else: return HttpResponseForbidden() @login_required def prospectives(request): response = {'is_prosp': True} if request.user.is_staff: if request.method == 'POST': if request.POST['command'] == 'new_invite': prosp = Prospective.objects.get(pk=request.POST['prosp_id']) code = User.objects.make_random_password(length=5, allowed_chars='123456789') invite = Invite(code=code) invite.save() prosp.invite = invite prosp.save() response['prospectives'] = Prospective.objects.all().order_by('-created') response.update(csrf(request)) return render_to_response('admin_prospective.html', response) else: return HttpResponseForbidden() @login_required def reviews(request): response = {'is_review': True} if request.user.is_staff: response['reviews'] = Review.objects.all().order_by('-date') response.update(csrf(request)) return render_to_response('admin_reviews.html', response) else: return HttpResponseForbidden()
Python
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class PhoneNumber(models.Model): # Phone number, in format XXXXXXXXXX number = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) accessed = models.ManyToManyField(User, through='PhoneAccess') def __str__(self): # Prints phone number in format 555-555-5555 return '(%s) %s-%s' % (self.number[0:3], self.number[3:6], self.number[6:10]) class PhoneAccess(models.Model): user = models.ForeignKey(User) number = models.ForeignKey(PhoneNumber) accessed = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s accessed %s' % (self.user, self.number) class UserProfile(models.Model): # A link to the native Django user object user = models.OneToOneField(User) # PhoneNumber entry number = models.ForeignKey(PhoneNumber, blank=True, null=True) # Have we verified that this user owns the phone? (By sending a text) verified = models.BooleanField(default=False) confirmation_code = models.CharField(max_length=15, blank=True, null=True) # When this was created created = models.DateTimeField(auto_now_add=True) # Last time the user logged in last_login = models.DateTimeField(auto_now=True) def __str__(self): if self.number: return '%s - %s' % (str(self.user), self.number) else: return str(self.user) class Review(models.Model): """A single review, posted by a single user""" # The phone number this review refers to number = models.ForeignKey(PhoneNumber) # The user who posted this review user = models.ForeignKey(User) # Review content text = models.TextField() # Post date date = models.DateTimeField(auto_now_add=True) # Number of votes, cached votes = models.IntegerField(default=0) # Set of people who voted vote_ups = models.ManyToManyField(User, related_name='vote_ups') vote_downs = models.ManyToManyField(User, related_name='vote_downs') # Invalid if deleted valid = models.BooleanField(default=True) def __str__(self): text = (self.text[:50] + '...') if len(self.text) > 50 else self.text return '%s: %s' % (self.user, text) def number_display(self): return '(%s)' % self.number.number[0:3] def poster_number_display(self): return '(%s)' % self.user.get_profile().number.number[0:3] class Invite(models.Model): """An invite object. An admin can generate invites, and its used by alpha/beta testers to sign up""" code = models.CharField(max_length=20) used = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, blank=True, null=True) def use(self, user): self.user = user self.used = True self.save() def __str__(self): if self.used: return 'Used invite by %s' % self.user.username else: return 'Unused invite: %s' % self.code class MassInvite(models.Model): """An mass invite object. An admin can generate invites, and its used by alpha/beta testers to sign up. Mass invites are allowed to be used more than once.""" name = models.CharField(max_length=20) code = models.CharField(max_length=20) disabled = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) users = models.ManyToManyField(User) def use(self, user): self.users.add(user) self.save() def __str__(self): if self.used: return 'Used invite %s by %d users' % (self.code, len(self.users)) else: return 'Unused invite: %s' % self.code class Feedback(models.Model): """A piece of feedback from someone""" # Type of feedback type = models.CharField(max_length=20, default='Unspecified') # The user who wrote it user = models.ForeignKey(User) # Feedback content text = models.TextField() # URL that they were directed from url = models.CharField(max_length=50) # Creation date created = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s by %s' % (self.type, self.user) class Activity(models.Model): """Caches recent activities""" description = models.CharField(max_length=50) user = models.ForeignKey(User, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): if self.user.get_profile(): return '%s %s' % (self.user.get_profile().number, self.description) else: return '%s %s' % (self.user, self.description) class Prospective(models.Model): """Where we store information on prospective users""" name = models.CharField(max_length=50) email = models.EmailField() referrer = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) invite = models.OneToOneField(Invite, null=True, blank=True) class ProspectiveMessage(models.Model): """Email to send to prospectives""" subject = models.CharField(max_length=50) body = models.TextField() created = models.DateTimeField(auto_now_add=True) selected = models.BooleanField(default=False) # Create UserProfile automatically after User is created def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User)
Python
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
Python
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^/?$', 'fonr.alpha.views.profile', name='home'), url(r'^signup/?', 'fonr.alpha.views.signup', name='signup'), url(r'^([0-9]{10})/?', 'fonr.alpha.views.search'), url(r'^login/?$', 'fonr.alpha.views.loginpage'), url(r'^search/?$', 'fonr.alpha.views.search'), url(r'^search/([0-9]{10})/?$', 'fonr.alpha.views.search'), url(r'^review/([0-9]+)/?$', 'fonr.alpha.views.single_review'), url(r'^profile/?$', 'fonr.alpha.views.profile'), url(r'^vote/([0-9]+)/?$', 'fonr.alpha.views.vote'), url(r'^logout/?$', 'fonr.alpha.views.logout_page'), url(r'^verify/?$', 'fonr.alpha.views.verify'), url(r'^settings/?$', 'fonr.alpha.views.settings'), url(r'^report/?$', 'fonr.alpha.views.report'), url(r'^thankyou/?$', 'fonr.alpha.views.thankyou'), # Admin url('^superadmin/?$', 'fonr.alpha.views_admin.stream'), url('^superadmin/stream/?$', 'fonr.alpha.views_admin.stream'), url('^superadmin/stream/([0-9]+)/?$', 'fonr.alpha.views_admin.stream'), url('^superadmin/invites/?$', 'fonr.alpha.views_admin.invites'), url('^superadmin/reports/?$', 'fonr.alpha.views_admin.reports'), url('^superadmin/prospectives/?$', 'fonr.alpha.views_admin.prospectives'), url('^superadmin/reviews/?$', 'fonr.alpha.views_admin.reviews'), )
Python
# utils.py: Utility functions for fonr import re from fonr.googlevoice import Voice def check_phone_number(raw_number): """Number is a string the form of XXXXXXXXXX. Checks if its a valid US phone number""" # Fix number to match format r = re.compile('^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$') match = r.match(raw_number) if not match: return (False, 'Invalid phone number: Unrecognized format') number = ''.join(match.groups()) # Check if its 10 numbers match = re.match('([0-9]{10})', number) if not match: return (False, '%s is not 10 digits of numbers') # Check area code match = re.match('[2-9][0-8][0-9][0-9]{7}', number) if not match: return (False, 'Invalid area code %s' % number[0:3]) # Check exchange code match = re.match('[0-9]{3}[2-9][0-9]{2}[0-9]{4}', number) if not match: return (False, 'Invalid exchange code %s' % number[3:6]) return (True, number) # Use Google voice to send a text message def send_text(number, message): voice = Voice() voice.login() voice.send_sms(number, message)
Python
from django.contrib import admin from fonr.alpha.models import PhoneNumber from fonr.alpha.models import PhoneAccess from fonr.alpha.models import UserProfile from fonr.alpha.models import Review from fonr.alpha.models import Invite from fonr.alpha.models import Activity from fonr.alpha.models import Feedback from django.contrib.auth.models import User admin.site.register(PhoneNumber) admin.site.register(PhoneAccess) admin.site.register(UserProfile) admin.site.register(Review) admin.site.register(Invite) admin.site.register(Feedback) admin.site.register(Activity)
Python
from django.http import HttpResponse from django.http import HttpResponseBadRequest from django.http import HttpResponseForbidden from django.http import HttpResponseNotAllowed from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.contrib.auth.hashers import check_password from django.shortcuts import redirect from django.shortcuts import render_to_response from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.core.context_processors import csrf from django.views.decorators.csrf import ensure_csrf_cookie from django.core.exceptions import ObjectDoesNotExist from fonr.alpha.utils import check_phone_number from fonr.alpha.utils import send_text from alpha.models import PhoneNumber from alpha.models import UserProfile from alpha.models import Activity from alpha.models import Invite from alpha.models import MassInvite from alpha.models import Review from alpha.models import Feedback from alpha.models import Prospective from django.contrib.auth.models import AnonymousUser # Debug from fonr.settings import DEBUG import json def _log_activity(message, user=None): activity = Activity(description=message, user=user) activity.save() def index(request): """Index of the site, redirect to home if user is logged in, display sign in page otherwise""" if request.user.is_authenticated(): return redirect('home') else: response = {'request': request} response.update(csrf(request)) return render_to_response('index.html', response) @login_required def verify(request): """User gets redirected here if their account is not yet verified""" response = {'request': request} response.update(csrf(request)) return redirect('/') # TODO(Ryan): Add remove this when verification is done def thankyou(request): """A thank you page""" return render_to_response('thankyou.html', {}) def signup(request): """Sign up page. Create a new account, and redirect to verification.""" response = {'request': request} # CSRF token is used to prevent CSRF attacks, this token will be passed back in response.update(csrf(request)) # Just return an empty page if we receive a GET request if request.method == 'GET': return render_to_response('signup.html', response) # Try to create a new account elif request.method == 'POST': if 'prospective' in request.POST: # Add them to the prospectives list rather than sign up for a new acct try: prospective = Prospective(name = request.POST['prospective_name'], email = request.POST['prospective_email'], referrer = request.POST['prospective_referrer']) prospective.save() except Exception, e: response['error'] = str(e) return render_to_response('signup.html', response) else: return redirect('/a/thankyou') response['phone_number'] = request.POST['phone_number'] or '' # Check if the invite code exists and is valid if 'invite_code' not in request.POST: response['error'] = 'Invite code not given' return render_to_response('signup.html', response) elif Invite.objects.filter(code=request.POST['invite_code']): # Keep this in a variable, if user creation is successful then we mark it as used invites = Invite.objects.filter(code=request.POST['invite_code'], used=False) if not invites: response['error'] = 'Invite %s already used' % request.POST['invite_code'] return render_to_response('signup.html', response) else: invite = invites[0] elif MassInvite.objects.filter(code=request.POST['invite_code']): invites = MassInvite.objects.filter(code=request.POST['invite_code'], disabled=False) if not invites: response['error'] = 'Invite %s is disabled' % request.POST['invite_code'] return render_to_response('signup.html', response) else: invite = invites[0] else: response['error'] = 'Invalid invite code' return render_to_response('signup.html', response) # Clean up the phone number and check if its valid raw_number = request.POST['phone_number'] number_valid, number = check_phone_number(raw_number) if not number_valid: response['error'] = number return render_to_response('signup.html', response) # Number is valid, now check if the user exists already response['phone_number'] = number password = request.POST['password'] user = User.objects.filter(username=number) response['user'] = user if user: # User exists, return an error response['error'] = 'User %s already exists' % UserProfile.objects.get( user=user).number return render_to_response('signup.html', response) else: # User doesn't exist, make a new user, confirmation code confirmation_code = User.objects.make_random_password(length=6, allowed_chars='abcdefghjkmnpqrstuvwxyz23456789') user = User.objects.create_user(number, '%s@fonite.com', password) user.save() phone_number, created = PhoneNumber.objects.get_or_create(number=number) profile = UserProfile.objects.get(user=user) profile.confirmation_code = confirmation_code profile.number = phone_number # TODO(Ryan): Remove this after we get verification to work profile.valid = True profile.save() # Just for the invite period, we're not going to bother with number verification invite.use(user) # Used for logging _log_activity('Created an account with invite %s' % invite.code, user) # Sign the user in login_user = authenticate(username=number, password=password) login(request, login_user) return redirect('/a/verify') else: return HttpResponseBadRequest() def loginpage(request): """Authentication end point""" response = {'request': request} raw_number = request.POST['phone_number'] # Defaults to phone number password = request.POST['password'] number_valid, number = check_phone_number(raw_number) user = authenticate(username=number, password=password) if user is not None: if user.is_active: login(request, user) _log_activity('Logged in', user) return redirect('/') else: return render_to_response('disabled.html', {}) else: response.update({'phone_number': number}) response.update(csrf(request)) return render_to_response('login_failed.html', response) @login_required def home(request): """Home of the site, havn't really decided what goes here, maybe recent activity?""" response = {'is_home': True, 'request': request} return render_to_response('home.html', response) @login_required def search(request, query=None): """Returns info on a phone number if found, 'NOT FOUND' page otherwise""" response = {'query': query, 'request': request} response.update(csrf(request)) # Redirect request if its not in canotical form if not query: response['is_search'] = True if 'phone_number' in request.POST: raw_number = request.POST['phone_number'] number_valid, number = check_phone_number(raw_number) if number_valid: return redirect('/a/search/%s' % number) else: response['error'] = number return render_to_response('search.html', response) else: return render_to_response('search.html', response) # Check validity (Should be valid, but wouldn't hurt) number_valid, number = check_phone_number(query) if not number_valid: response['error'] = number return render_to_response('search.html', response) # Retrieve and return review phone_number, created = PhoneNumber.objects.get_or_create(number=number) if 'new_review' in request.POST: # Post a new review if requested review = Review( number=phone_number, text=request.POST['new_review'], user=request.user ) review.save() _log_activity('Posted a review for %s' % phone_number, request.user) else: _log_activity('Accessed %s' % phone_number, request.user) reviews = Review.objects.filter(number=phone_number, valid=True).order_by('-date') response['reviews'] = reviews response['phone_number'] = phone_number response['is_self'] = (request.user.username == phone_number.number) if response['is_self']: response['is_profile'] = True else: response['is_search'] = True response['user'] = request.user return render_to_response('review.html', response) def vote(request, review_id): """Vote up, vote down, or clear vote.""" response = {} if request.method != 'POST': return HttpResponseNotAllowed(['POST']) command = request.POST['command'] review = Review.objects.get(pk=review_id) user = request.user if command == 'up': if user in review.vote_ups.all(): response['success'] = 'false' response['message'] = 'Already voted' elif user in review.vote_downs.all(): response['success'] = 'true' review.vote_downs.remove(user) review.vote_ups.add(user) review.votes += 2 review.save() else: response['success'] = 'true' review.vote_ups.add(user) review.votes += 1 review.save() elif command == 'down': if user in review.vote_downs.all(): response['success'] = 'false' response['message'] = 'Already voted' elif user in review.vote_ups.all(): response['success'] = 'true' review.vote_ups.remove(user) review.vote_downs.add(user) review.votes -= 2 review.save() else: response['success'] = 'true' review.vote_downs.add(user) review.votes -= 1 review.save() elif command == 'clear': if user in review.vote_downs.all(): response['success'] = 'true' review.vote_downs.remove(user) review.votes += 1 review.save() elif user in review.vote_ups.all(): response['success'] = 'true' review.vote_ups.remove(user) review.votes -= 1 review.save() else: response['success'] = 'true' response['message'] = 'Nothing happened' else: response['message'] = 'No command given' response['votes'] = review.votes if response['success'] == 'true': reviewee = (review.number if review.number != request.user.get_profile().number else 'self') reviewer = review.user if review.user != request.user else 'self' _log_activity('Voted %s review of %s by %s' % (command, reviewee, reviewer), request.user) return HttpResponse(json.dumps(response)) @login_required @ensure_csrf_cookie def single_review(request, review_id): """Returns full text of a single review, allow voting""" response = {'request': request} review = Review.objects.get(pk=review_id) if request.method == 'POST': if request.POST['command'] == 'delete': if request.user == review.user: review.valid = False review.save() _log_activity('Deleted review of %s' % review.number, request.user) return redirect('/a/search/' + review.number.number) response['review'] = review response['phone_number'] = review.number response['is_self'] = (request.user.username == review.number.number) response['is_reviewer'] = (request.user == review.user) if response['is_self']: _log_activity('Views review of self', request.user) response['is_profile'] = True else: _log_activity('Views review of %s' % review.number, request.user) response['is_search'] = True response['user'] = request.user response.update(csrf(request)) return render_to_response('single_review.html', response) def logout_page(request): _log_activity('Logs out', request.user) logout(request) return redirect("/") def profile(request): """View and edit own page""" _log_activity('Views own profile', request.user) return search(request, request.user.username) def report(request): response = {'request': request} response.update(csrf(request)) if request.method == 'GET': response['redirect_url'] = request.GET['from'] return render_to_response('report.html', response) elif request.method == 'POST': feedback = Feedback(type=request.POST['type'], user=request.user, text=request.POST['text'], url=request.POST['from']) feedback.save() _log_activity('Writes report', request.user) return redirect(request.POST['from']) @login_required def settings(request): """Change user settings""" response = {'is_settings': True, 'request': request} response.update(csrf(request)) if request.method == 'POST': command = request.POST['command'] if command == 'change_password': if check_password(request.POST['old_password'], request.user.password): if request.POST['new_password'] == request.POST['confirm_password']: user = request.user user.set_password(request.POST['new_password']) user.save() _log_activity('Changes password', request.user) response['info_message'] = 'Password changed successfully' else: response['error_message'] = 'Passwords did not match' else: response['error_message'] = 'Old password incorrect' else: response['error_message'] = 'Invalid command %s' % command return render_to_response('settings.html', response)
Python
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__) sys.exit(1) import settings if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'fonr.alpha.views.index', name='home'), url(r'^a/', include('fonr.alpha.urls')), url(r'^accounts/login/?', 'fonr.alpha.views.index'), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) urlpatterns += staticfiles_urlpatterns()
Python
# Django settings for fonr project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Admin', 'kagelump@gmail.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'database.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'st^)(xhkm7ckk$=3n+h0v!a74ad&zgt+pnjc*o=4cr)jhezcau' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'fonr.urls' AUTH_PROFILE_MODULE = 'fonr.UserProfile' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', 'fonr.alpha', ) #SENDSMS_BACKEND = 'myapp.mysmsbackend.SmsBackend' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } supports_anonymous_user = True # Defines the model that stores the user's profile information AUTH_PROFILE_MODULE = 'alpha.UserProfile'
Python
import cherrypy import random import math import json import os.path import py.geobox as geobox from string import Template MAP_LEFT = 50 MAP_TOP = 50 MAP_RIGHT = 900 MAP_BOTTOM = 400
Python
class EntityManager(object): def __init__(self): self.ents = {} self.count = 0 self.deletes = [] def add_planet(self,type,sub,owner,x,y): self.count += 1 id = self.count p = [id,type,sub,owner,x,y] self.ents[id] = p return p def add_ship(self,id,type,sub,owner,x,y,strength): self.count += 1 id = self.count s = [id,type,sub,owner,x,y,strength] self.ents[id] = s return s def clean(self): while len(self.deletes) > 0: idx = self.deletes.pop() del self.ents[idx]
Python
import cherrypy import random import math import json import os.path import py.geobox as geobox from string import Template MAP_LEFT = 50 MAP_TOP = 50 MAP_RIGHT = 900 MAP_BOTTOM = 400 #test def get_distance2(x1,x2,y1,y2): return math.pow(x2-x1,2) + math.pow(y2-y1,2) class Server: item_counter = 0 player_counter = 0 players = {} ships = {} space_items = {} space_item_deletes = [] actions = [] turn_counter = 0 action_log = [] data_by_player = {} geoindex = geobox.geobox() @cherrypy.expose def create_new_player(self): Server.player_counter += 1 player = Server.player_counter Server.players[str(player)] = player Server.data_by_player[player] = {} Server.data_by_player[player]['view'] = {} x = random.randint(MAP_LEFT,MAP_RIGHT) y = random.randint(MAP_TOP,MAP_BOTTOM) a = {'type':'create','what':'base','player':player,'x':x,'y':y,'start':True} Server.actions.append(a) return json.dumps({'player_number':player}) def start_player(self): Server.player_counter += 1 player = Server.player_counter Server.data_by_player[player] = {} Server.data_by_player[player]['view'] = {} x = random.randint(MAP_LEFT,MAP_RIGHT) y = random.randint(MAP_TOP,MAP_BOTTOM) a = {'type':'create','what':'base','player':player,'x':x,'y':y,'start':True} Server.actions.append(a) return player @cherrypy.expose def get_game_info(self): return json.dumps({'turn':Server.turn_counter, 'space_items':Server.space_items, 'actions':Server.actions}) @cherrypy.expose def get_turn(self): return json.dumps({'turn':Server.turn_counter}) @cherrypy.expose def get_player_data(self,player_idx): #test return json.dumps(Server.data_by_player[player_idx]) @cherrypy.expose def get_player_view(self,player_number): return json.dumps({'turn': Server.turn_counter, 'actions':[], 'view':Server.data_by_player[int(player_number)]['view']}) @cherrypy.expose def get_player_view_loggedin(self): id = cherrypy.session.get('player_id') return json.dumps({'turn': Server.turn_counter, 'actions':[], 'player_id':id, 'view':Server.data_by_player[id]['view']}) @cherrypy.expose def get_geobox(self): return json.dumps(Server.geoindex.index) def space_item_filter(self,term,value): matched_items = [] for i in Server.space_items.values(): if i.has_key(term): if i[term] == value: matched_items.append(i) return matched_items @cherrypy.expose def get_action_log(self): html_log = '<br>'.join(Server.action_log) return html_log @cherrypy.expose def item_filter(self,term,value,valuetype='string'): if valuetype == 'int': value = int(value) matched_items = self.space_item_filter(term,value) return json.dumps(matched_items) @cherrypy.expose def get_all_space_items(self): return json.dumps(Server.space_items.values(),indent=4) def do_move(self,a): ship = Server.space_items[a['idx']] ship_speed2 = math.pow(ship['speed'],2) distance2 = get_distance2(ship['x'],a['x'],ship['y'],a['y']) if distance2 <= ship_speed2 and ship['ep'] >= 10: ship['x'] = a['x'] ship['y'] = a['y'] ship['ep'] -= 10 l = 'MOVE committed %s' % json.dumps(ship) Server.action_log.append(l) else: l = 'ERROR move not committed distance2 = %s speed2 = %s' % (distance2,ship_speed2) Server.action_log.append(l) def do_create(self,a): Server.item_counter += 1 idx = Server.item_counter t = {} if a['what'] == 'base' and a.has_key('start'): t = {'type':'base', 'player':a['player'], 'idx':idx, 'x':a['x'], 'y':a['y'], 'sp':1000, 'ore':100} Server.space_items[idx] = t return True base = a['base'] ore = Server.space_items[base] if a['what'] == 'ship' and ore > 10: t = {'idx':idx, 'type':'ship', 'x': a['x'], 'y': a['y'], 'sp':100, 'ep':100, 'speed':10, 'range':10, 'regen':10, 'player':a['player']} Server.space_items[base]['ore'] -= 10 Server.space_items[idx] = t elif a['what'] == 'base' and ore > 1000: t = {'type':'base', 'player':a['player'], 'idx':idx, 'x':a['x'], 'y':a['y'], 'sp':1000, 'ore':100} Server.space_items[base]['ore'] -= 1000 Server.space_items[idx] = t def do_attack(self,a): atk = Server.space_items[a['atk']] tgt = Server.space_items[a['tgt']] distance2 = get_distance2(atk['x'],tgt['x'],atk['y'],tgt['y']) atk_range2 = math.pow(atk['range'],2) if distance2 < atk_range2 and atk['ep'] >= 10: tgt['sp'] -= 10 atk['ep'] -= 10 l = 'ATTACK %s [ep:%s] attacks %s [sp:%s]' % (atk['idx'],atk['ep'],tgt['idx'],tgt['sp']) Server.action_log.append(l) if tgt['sp'] <= 0: Server.space_item_deletes.append(tgt['idx']) l = 'DESTROY %s killed %s' % (atk['idx'],tgt['idx']) Server.action_log.append(l) def do_mine(self,a): miner = Server.space_items[a['miner']] asteroid = Server.space_items[a['asteroid']] if asteroid['type'] == 'asteroid': distance2 = get_distance2(miner['x'],asteroid['x'],miner['y'],asteroid['y']) mine_range2 = math.pow(miner['range'],2) if distance2 <= mine_range2 and miner['ep'] >= 10: l = 'MINE asteroid %s' % a['asteroid'] Server.action_log.append(l) miner['ep'] -= 10 #change later to ore drop off Server.space_items[a['base']]['ore'] += 10 Server.space_item_deletes.append(a['asteroid']) else: l = 'too far to mine %s' % distance2 Server.action_log.append(l) def __init__(self): self.action_dict = {'move':self.do_move, 'attack':self.do_attack, 'mine':self.do_mine, 'create':self.do_create} self.make_asteroids(90) @cherrypy.expose def index(self): html = open(os.path.join(os.path.dirname(__file__), 'html/index.html'),"r") return html.read() @cherrypy.expose def stats(self): html = open(os.path.join(os.path.dirname(__file__), 'html/stats.html'),"r") return html.read() @cherrypy.expose def login(self): html = open(os.path.join(os.path.dirname(__file__), 'html/login.html'),"r") return html.read() @cherrypy.expose def do_login(self, username=None, password=None): if (username == password): if Server.players.has_key(username): cherrypy.session['player_id'] = Server.players['username'] cherrypy.session['player_name'] = username cherrypy.session['log'] = 'true' else: id = self.start_player() Server.players['username'] = id cherrypy.session['player_id'] = id cherrypy.session['player_name'] = username cherrypy.session['log'] = 'true' raise cherrypy.HTTPRedirect('player_page') else: raise cherrypy.HTTPRedirect('login') @cherrypy.expose def player_page(self): if cherrypy.session.get('log') == 'true': html = open(os.path.join(os.path.dirname(__file__), 'html/player.html'),"r").read() d = {'playername':cherrypy.session.get('player_name'), 'id':cherrypy.session.get('player_id')} temp = Template(html).substitute(d) return temp else: raise cherrypy.HTTPRedirect('login') @cherrypy.expose def test_json(self,stuff): a = json.loads(stuff) return json.dumps(a) def make_asteroids(self,amount): for i in range(0,amount): Server.item_counter += 1 idx = Server.item_counter a = {'type':'asteroid', 'x':random.randint(MAP_LEFT,MAP_RIGHT), 'y':random.randint(MAP_TOP,MAP_BOTTOM), 'idx':idx} Server.space_items[idx] = a @cherrypy.expose def submit_actions(self,actions=[]): acts = json.loads(actions) Server.actions.extend(acts) return 'got %s actions' % str(len(acts)) @cherrypy.expose def get_actions(self): return json.dumps(Server.actions) @cherrypy.expose def do_actions(self): self.clear_index() old_len = len(Server.actions) #calculate each action while len(Server.actions) > 0: a = Server.actions.pop() self.action_dict[a['type']](a) self.do_deletes() self.make_asteroids(random.randint(1,10)) #do the regen for each item and add each item to the indexes for i in Server.space_items.values(): if i.has_key('ep'): i['ep'] += i['regen'] self.add_item_to_index(i) #calculate the views for each player and cache them for p in Server.data_by_player.keys(): view = self.calc_player_view(p) Server.data_by_player[p]['view'] = view #after all accounting is done increment the turn counter Server.turn_counter += 1 return 'did them %s .... action list len is %s' % (old_len,len(Server.actions)) def do_deletes(self): while len(Server.space_item_deletes) > 0: idx = Server.space_item_deletes.pop() if Server.space_items.has_key(idx): del Server.space_items[idx] def add_item_to_index(self,item): t = item['type'] x = item['x'] y = item['y'] if item.has_key('player'): p = item['player'] Server.data_by_player[p].setdefault(t,[]).append(item) Server.geoindex.add_point(x,y,item) def calc_player_view(self,player_number): cells = [] items = {} for i in Server.data_by_player[player_number]['ship']: cells.append(Server.geoindex.get_cell(i['x'],i['y'])) for i in Server.data_by_player[player_number]['base']: cells.append(Server.geoindex.get_cell(i['x'],i['y'])) set_cells = set(cells) for c in set_cells: near_bys = Server.geoindex.get_near_by(cell=c) for n in near_bys: items[n['idx']] = n return items def clear_index(self): for p in Server.data_by_player.keys(): Server.data_by_player[p] = {} Server.data_by_player[p]['ship'] = [] Server.data_by_player[p]['base'] = [] Server.data_by_player[p]['view'] = [] Server.geoindex.clear() prodconf = os.path.join(os.path.dirname(__file__), 'prod.conf') current_dir = os.path.dirname(os.path.abspath(__file__)) if __name__ == '__main__': cherrypy.quickstart(Server(), config=prodconf)
Python
import json import urllib import sys import random import time import math ulr = "http://coder9.selfip.com:8080/" def get_distance2(x1,x2,y1,y2): return math.pow(x2-x1,2) + math.pow(y2-y1,2) def main(): actions = [] player_number = create_new_player()['player_number'] print 'I am player %s' % player_number turn = -1; while True: game_turn = get_turn()['turn'] if turn < game_turn: data = get_player_view(player_number) space_items = data['view'] think(player_number,space_items,actions) submit_actions(actions) actions = [] turn = game_turn else: print 'still the same turn %s' % turn time.sleep(2) def get_player_view(player_number): f = urllib.urlopen(ulr + "get_player_view/%s" % player_number) return json.loads(f.read()) def get_turn(): f = urllib.urlopen(ulr + "get_turn") return json.loads(f.read()) def create_new_player(): f = urllib.urlopen(ulr + "create_new_player") return json.loads(f.read()) def submit_actions(actions): print 'Submitting these actions' print "-" * 80 for i in actions: print str(i) acts = json.dumps(actions) params = urllib.urlencode({'actions':acts}) f = urllib.urlopen(ulr + "submit_actions", params) print f.read() print def make_ship(base_idx,player_idx,x,y): return {'type':'create','what':'ship','base':base_idx,'player':player_idx,'x':x,'y':y} def make_base(player_idx,x,y): return {'type':'create','what':'base','player':player_idx,'x':x,'y':y} def move_ship_to(x,y,ship,in_range_idx,base_idx): x1 = ship['x'] x2 = x y1 = ship['y'] y2 = y if get_distance2(x1,x2,y1,y2) < math.pow(ship['speed'],2): print 'i can make it to the location' return {'type':'mine','miner':ship['idx'],'asteroid':in_range_idx,'base':base_idx} else: diff_x = x2 - x1 diff_y = y2 - y1 atan2 = math.atan2(diff_y, diff_x) cos = math.cos(atan2) sin = math.sin(atan2) new_x = int(round(x1 + cos * (ship['speed'] - 1))) new_y = int(round(y1 + sin * (ship['speed'] - 1))) print 'distance I can move %s' % math.sqrt(get_distance2(x1,new_x,y1,new_y)) return {'type':'move','idx':ship['idx'],'x':new_x,'y':new_y} def attack(attacker,target): print 'attacking !!!! %s' % target return {'type':'attack','atk':attacker,'tgt':target} def think(player_idx,space_items,actions): bases = [i for i in space_items.values() if i['type'] == 'base' and i['player'] == player_idx] ships = [i for i in space_items.values() if i['type'] == 'ship' and i['player'] == player_idx] asteroids = [i for i in space_items.values() if i['type'] == 'asteroid'] enemy = [i for i in space_items.values() if i['type'] == 'ship' and i['player'] != player_idx] ebases = [i for i in space_items.values() if i['type'] == 'base' and i['player'] != player_idx] print 'thinking' # if len(bases) < 1: # x = random.randint(-200,200) # y = random.randint(-200,200) # a = make_base(player_idx,x,y) # actions.append(a) # return actions for b in bases: if b['ore'] > 10: print 'I have too much ore at base %s, ill make a ship' % b['idx'] x = b['x'] + random.randint(0,5) y = b['y'] + random.randint(0,5) actions.append(make_ship(b['idx'],player_idx,x,y)) for s in ships: #look for enemy base for eb in ebases: dis2 = get_distance2(s['x'],eb['x'],s['y'],eb['y']) range2 = math.pow(s['range'],2) if dis2 < range2: attack_action = attack(s['idx'],eb['idx']) actions.append(attack_action) break # look for enemy ship for e in enemy: dis2 = get_distance2(s['x'],e['x'],s['y'],e['y']) range2 = math.pow(s['range'],2) if dis2 < range2: attack_action = attack(s['idx'],e['idx']) actions.append(attack_action) break a = think_ship(s,asteroids,bases[0]) if a != None: actions.append(a) return actions def think_ship(ship,asteroids,base): #find closest asteroid closest = 99999999999999 closest_asteroid = {'idx':0} x1 = ship['x'] y1 = ship['y'] for a in asteroids: dis2 = get_distance2(x1,a['x'],y1,a['y']) if dis2 < closest: closest_asteroid = a closest = dis2 if closest_asteroid['idx'] != 0: return move_ship_to(closest_asteroid['x'], closest_asteroid['y'], ship, closest_asteroid['idx'], base['idx']) return None def think_base(base): pass if __name__ == '__main__': main()
Python
import json import urllib import pprint import random import time while True: f = urllib.urlopen("http://coder9.selfip.com:8080/do_actions") print f.read() time.sleep(10)
Python
import random from omega import geobox from omega import playermanager from omega import actionmanager from omega import entitymanager types = {0:'planet', 1:'ship'} subtypes = {0:'c', 1:'m', 2:'x', 3:'destroyer', 4:'cruiser', 5:'battle'} class Game(object): def __init__(self): self.turn = 0 self.size = {'n':300,'e':400,'s':300,'w':400} self.geo = geobox.GeoBox() self.pm = playermanager.PlayerManager() self.am = actionmanager.ActionManager() self.em = entitymanager.EntityManager() def new_player(self,name=None): self.pm. def make_planets(self,amount): for i in range(0,amount): x = random.randint(self.west,self.east) y = random.randint(self.south,self.north) self.ents_count += 1 id = self.ents_count # id,type,sub,owner,x,y planet = [id,0,1,0,x,y] self.ents[id] = planet self.planets.append(planet) def find_home(self): planet = [0,0,0,1,0,0]; while planet[3] != 0: planet = random_planet(self) return planet def random_planet(self): idx = random.randint(0,len(self.planets)) return self.planets[idx] def find_home(self): planet = [0,0,0,1,0,0]; while planet[3] != 0: planet = random_planet(self) return planet def make_planets(self,amount): for i in range(0,amount): x = random.randint(self.west,self.east) y = random.randint(self.south,self.north) self.ents_count += 1 id = self.ents_count # id,type,sub,owner,x,y planet = [id,0,1,0,x,y] self.ents[id] = planet self.planets.append(planet) def random_planet(self): idx = random.randint(0,len(self.planets)) return self.planets[idx]
Python
class PlayerManager(object): def __init__(self): self.players = {} self.count = 0 self.log = [] def add_player(self,planet,name=None,ore=10): self.count += 1 id = self.count player = {'id':id, 'name':name, 'ore':ore, 'planets':[], 'ships':[], 'view':[]} self.players[id] = player return player def clean(self): for p in self.player.keys(): self.players[p]['ships'] = [] self.players[p]['planets'] = [] self.players[p]['view'] = []
Python
import json class ActionManager(object): def __init__(self): self.actions = [] self.jsons = [] self.log = [] def add_json_actions(self,actions=[]): self.jsons.extend(actions) def convert_actions(self): self.actions = json.loads(self.json_actions)
Python
import random class GeoBox(object): def __init__(self): self.index = {} self.cellsize = 100; def clear(self): self.index = {} def get_cell(self,x,y): return x/self.cellsize,y/self.cellsize def add_point(self,x,y,item): key = self.get_cell(x,y) self.index.setdefault(str(key), []).append(item) def get_near_by(self,cell,cell_range=1,): near_by = [] c = [] for i in xrange(-cell_range,cell_range+1): c.append(i) for i in c: for j in c: kx = cell[0] - i ky = cell[1] - j key = str((kx,ky)) if self.index.has_key(key): near_by.extend(self.index[key]) return near_by def __str__(self): return str('\n'.join(['%s,%s' % (k,v) for k,v in self.index.items()])) if __name__ == "__main__": gb = geobox() for i in range(200): x = random.randint(0,1000) y = random.randint(0,1000) gb.add_point(x,y,i) print str(gb) print '-' * 40 print gb.get_near_by(300,300,1)
Python
import gc import time mylist = [] def make(): #this just fills in the list with some junk data print 'making them' for x in range(0,1000000): mylist.append(['aa','bb','cc','dd',2,3,4,5,6,7,8]) print 'made them' def gone(): #this is so I can watch the memory print 'are they gone?' time.sleep(2) def deletethem(): #did they get deleted? print 'deleting ref' del mylist[:] #print gc.collect() if __name__ == '__main__': print 'starting' while 1: make() deletethem() gone()
Python
# -*- coding: utf-8 -*- # Foma: a finite-state toolkit and library. # # Copyright © 2008-2015 Mans Hulden # # This file is part of foma. # # 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. # from sys import maxint from ctypes import * from ctypes.util import find_library fomalibpath = find_library('foma') foma = cdll.LoadLibrary(fomalibpath) class FSTstruct(Structure): _fields_ = [("name", c_char * 40), ("arity", c_int), ("arccount", c_int), ("statecount", c_int), ("linecount", c_int), ("finalcount", c_int), ("pathcount", c_longlong), ("is_deterministic", c_int), ("is_pruned", c_int), ("is_minimized", c_int), ("is_epsilon_free", c_int), ("is_loop_free", c_int), ("is_completed", c_int), ("arcs_sorted_in", c_int), ("arcs_sorted_out", c_int), ("fsm_state", c_void_p), ("sigma", c_void_p), ("medlookup", c_void_p)] foma_fsm_parse_regex = foma.fsm_parse_regex foma_fsm_parse_regex.restype = POINTER(FSTstruct) foma_apply_init = foma.apply_init foma_apply_init.restype = c_void_p foma_apply_clear = foma.apply_clear foma_apply_words = foma.apply_words foma_apply_words.restype = c_char_p foma_apply_lower_words = foma.apply_lower_words foma_apply_lower_words.restype = c_char_p foma_apply_upper_words = foma.apply_upper_words foma_apply_upper_words.restype = c_char_p foma_apply_down = foma.apply_down foma_apply_down.restype = c_char_p foma_apply_up = foma.apply_up foma_apply_up.restype = c_char_p foma_apply_set_space_symbol = foma.apply_set_space_symbol foma_fsm_count = foma.fsm_count foma_fsm_topsort = foma.fsm_topsort foma_fsm_topsort.restype = POINTER(FSTstruct) foma_fsm_minimize = foma.fsm_minimize foma_fsm_minimize.restype = POINTER(FSTstruct) foma_fsm_union = foma.fsm_union foma_fsm_union.restype = POINTER(FSTstruct) foma_fsm_intersect = foma.fsm_intersect foma_fsm_intersect.restype = POINTER(FSTstruct) foma_fsm_minus = foma.fsm_minus foma_fsm_minus.restype = POINTER(FSTstruct) foma_fsm_compose = foma.fsm_compose foma_fsm_compose.restype = POINTER(FSTstruct) foma_fsm_concat = foma.fsm_concat foma_fsm_concat.restype = POINTER(FSTstruct) foma_fsm_copy = foma.fsm_copy foma_fsm_copy.restype = POINTER(FSTstruct) foma_fsm_complement = foma.fsm_complement foma_fsm_complement.restype = POINTER(FSTstruct) foma_fsm_lower = foma.fsm_lower foma_fsm_lower.restype = POINTER(FSTstruct) foma_fsm_upper = foma.fsm_upper foma_fsm_upper.restype = POINTER(FSTstruct) foma_fsm_minimize = foma.fsm_minimize foma_fsm_minimize.restype = POINTER(FSTstruct) foma_fsm_destroy = foma.fsm_destroy foma_fsm_equivalent = foma.fsm_equivalent foma_fsm_equivalent.restype = c_int foma_fsm_isempty = foma.fsm_isempty foma_fsm_isempty.restype = c_int foma_fsm_flatten = foma.fsm_flatten foma_fsm_flatten.restype = POINTER(FSTstruct) foma_apply_set_space_symbol = foma.apply_set_space_symbol foma_fsm_read_binary_file = foma.fsm_read_binary_file foma_fsm_read_binary_file.restype = POINTER(FSTstruct) """Define functions.""" foma_add_defined = foma.add_defined foma_add_defined.restype = c_int foma_add_defined_function = foma.add_defined_function foma_add_defined_function.restype = c_int defined_networks_init = foma.defined_networks_init defined_networks_init.restype = c_void_p defined_functions_init = foma.defined_functions_init defined_functions_init.restype = c_void_p """Trie functions.""" fsm_trie_init = foma.fsm_trie_init fsm_trie_init.restype = c_void_p fsm_trie_add_word = foma.fsm_trie_add_word fsm_trie_done = foma.fsm_trie_done fsm_trie_done.restype = POINTER(FSTstruct) class FSTnetworkdefinitions(object): def __init__(self): self.defhandle = defined_networks_init(None) class FSTfunctiondefinitions(object): def __init__(self): self.deffhandle = defined_functions_init(None) class FST(object): networkdefinitions = FSTnetworkdefinitions() functiondefinitions = FSTfunctiondefinitions() @classmethod def define(cls, definition, name): """Defines an FSM constant; can be supplied regex or existing FSM.""" name = cls.encode(name) if isinstance(definition, FST): retval = foma.add_defined(c_void_p(cls.networkdefinitions.defhandle), foma_fsm_copy(definition.fsthandle), c_char_p(name)) elif isinstance(definition, basestring): regex = cls.encode(definition) retval = foma.add_defined(c_void_p(cls.networkdefinitions.defhandle), foma_fsm_parse_regex(c_char_p(regex), c_void_p(cls.networkdefinitions.defhandle), c_void_p(cls.functiondefinitions.deffhandle)), c_char_p(name)) else: raise ValueError("Expected str, unicode, or FSM") @classmethod def definef(cls, prototype, definition): """Defines an FSM function.""" # Prototype is a 2-tuple (name, (arg1name, ..., argname)) # Definition is regex using prototype variables name = cls.encode(prototype[0] + '(') if isinstance(definition, basestring): numargs = len(prototype[1]) for i in xrange(numargs): definition = definition.replace(prototype[1][i], "@ARGUMENT0%i@" % (i+1)) regex = cls.encode(definition + ';') retval = foma.add_defined_function(c_void_p(cls.functiondefinitions.deffhandle), c_char_p(name), c_char_p(regex), c_int(numargs)) else: raise ValueError("Expected regex as definition") @classmethod def wordlist(cls, wordlist, minimize = True): """Create FSM directly from wordlist. Returns a trie-shaped deterministic automaton if not minimized.""" th = fsm_trie_init() for w in wordlist: thisword = cls.encode(w) fsm_trie_add_word(c_void_p(th), c_char_p(thisword)) fsm = cls() fsm.fsthandle = fsm_trie_done(c_void_p(th)) if minimize: fsm.fsthandle = foma_fsm_minimize(fsm.fsthandle) return fsm @classmethod def load(cls, filename): """Load binary FSM from file.""" fsm = cls() fsm.fsthandle = foma_fsm_read_binary_file(c_char_p(filename)) if not fsm.fsthandle: raise ValueError("File error.") return fsm @staticmethod def encode(string): """Makes sure str and unicode are converted.""" if isinstance(string, unicode): return string.encode('utf8') elif isinstance(string, str): return string else: return str(string) def __init__(self, regex = False): if regex: self.regex = self.encode(regex) self.fsthandle = foma_fsm_parse_regex(c_char_p(self.regex), c_void_p(self.networkdefinitions.defhandle), c_void_p(self.functiondefinitions.deffhandle)) if not self.fsthandle: raise ValueError("Syntax error in regex") else: self.fsthandle = None self.getitemapplyer = None def __getitem__(self, key): if not self.fsthandle: raise KeyError('FST not defined') if not self.getitemapplyer: self.getitemapplyer = foma_apply_init(self.fsthandle) result = [] output = foma_apply_down(c_void_p(self.getitemapplyer), c_char_p(self.encode(key))) while True: if output == None: return result else: result.append(output) output = foma_apply_down(c_void_p(self.getitemapplyer), None) def __del__(self): if self.fsthandle: foma_fsm_destroy(self.fsthandle) def __str__(self): if not self.fsthandle: raise ValueError('FSM not defined') foma_fsm_count(self.fsthandle) s = 'Name: %s\n' % self.fsthandle.contents.name s += 'States: %i\n' % self.fsthandle.contents.statecount s += 'Transitions: %i\n' % self.fsthandle.contents.arccount s += 'Final states: %i\n' % self.fsthandle.contents.finalcount s += 'Deterministic: %i\n' % self.fsthandle.contents.is_deterministic s += 'Minimized: %i\n' % self.fsthandle.contents.is_minimized s += 'Arity: %i\n' % self.fsthandle.contents.arity return s def __len__(self): if self.fsthandle: if self.fsthandle.contents.pathcount == -3: # UNKNOWN self.fsthandle = foma_fsm_topsort(self.fsthandle) if self.fsthandle.contents.pathcount == -1: # CYCLIC raise ValueError("FSM is cyclic") if self.fsthandle.contents.pathcount == -2: # OVERFLOW return maxint return self.fsthandle.contents.pathcount else: raise ValueError("FSM not defined") def __add__(self, other): return self.concat(other) def __sub__(self, other): return self.minus(other) def __le__(self, other): if self.fsthandle and other.fsthandle: return bool(c_int(foma_fsm_isempty(foma_fsm_minimize(foma_fsm_minus(foma_fsm_copy(self.fsthandle),foma_fsm_copy(other.fsthandle)))))) else: raise ValueError('Undefined FST') def __lt__(self, other): if self.fsthandle and other.fsthandle: return (not self.__eq__(other)) and bool(c_int(foma_fsm_isempty(foma_fsm_minimize(foma_fsm_minus(foma_fsm_copy(self.fsthandle),foma_fsm_copy(other.fsthandle)))))) else: raise ValueError('Undefined FST') def __or__(self, other): return self.union(other) def __and__(self, other): return self.intersect(other) def __eq__(self, other): if self.fsthandle and other.fsthandle: return bool(c_int(foma_fsm_equivalent(foma_fsm_copy(self.fsthandle), foma_fsm_copy(other.fsthandle)))) else: raise ValueError('Undefined FST') def __ne__(self, other): return not(self.__eq__(other)) def __contains__(self, word): af = self.apply_down(word) try: i = af.next() return True except StopIteration: return False def __call__(self, other): if isinstance(other, basestring): return FST("{" + other + "}").compose(self) else: return other.compose(self) def __invert__(self): new = FST() new.fsthandle = self._fomacallunary(foma_fsm_complement) return new def __iter__(self): return self._apply(foma_apply_upper_words, word = None, tokenize = False) def _apply(self, applyf, word = None, tokenize = False): if not self.fsthandle: raise ValueError('FST not defined') applyerhandle = foma_apply_init(self.fsthandle) if tokenize: toksym = '\x07' foma_apply_set_space_symbol(c_void_p(applyerhandle), c_char_p(toksym)) if word: output = applyf(c_void_p(applyerhandle), c_char_p(self.encode(word))) else: output = applyf(c_void_p(applyerhandle)) while True: if output == None: foma_apply_clear(c_void_p(applyerhandle)) return else: if tokenize: yield output[:-1].split('\x07') else: yield output if word: output = applyf(c_void_p(applyerhandle), None) else: output = applyf(c_void_p(applyerhandle)) def words(self, tokenize = False): return self._apply(foma_apply_words, word = None, tokenize = tokenize) def lowerwords(self, tokenize = False): return self._apply(foma_apply_lower_words, word = None, tokenize = tokenize) def upperwords(self, tokenize = False): return self._apply(foma_apply_upper_words, word = None, tokenize = tokenize) def apply_down(self, word, tokenize = False): return self._apply(foma_apply_down, word = word, tokenize = tokenize) def apply_up(self, word, tokenize = False): if self.fsthandle: return self._apply(foma_apply_up, word = word, tokenize = tokenize) else: raise ValueError('Undefined FST') def _fomacallunary(self, func, minimize = True): if self.fsthandle: handle = func(foma_fsm_copy(self.fsthandle)) if minimize: handle = foma_fsm_minimize(handle) return handle else: raise ValueError('Undefined FST') def _fomacallbinary(self, other, func, minimize = True): if self.fsthandle and other.fsthandle: handle = func(foma_fsm_copy(self.fsthandle), foma_fsm_copy(other.fsthandle)) if minimize: handle = foma_fsm_minimize(handle) return handle else: raise ValueError('Undefined FST') def union(self, other, minimize = True): new = FST() new.fsthandle = self._fomacallbinary(other, foma_fsm_union, minimize) return new def intersect(self, other, minimize = True): new = FST() new.fsthandle = self._fomacallbinary(other, foma_fsm_intersect, minimize) return new def minus(self, other, minimize = True): new = FST() new.fsthandle = self._fomacallbinary(other, foma_fsm_minus, minimize) return new def concat(self, other, minimize = True): new = FST() new.fsthandle = self._fomacallbinary(other, foma_fsm_concat, minimize) return new def compose(self, other, minimize = True): new = FST() new.fsthandle = self._fomacallbinary(other, foma_fsm_compose, minimize) return new def lower(self, minimize = True): new = FST() new.fsthandle = self._fomacallunary(foma_fsm_lower, minimize) return new def upper(self, minimize = True): new = FST() new.fsthandle = self._fomacallunary(foma_fsm_upper, minimize) return new def flatten(self): new = FST() eps_sym = FST('□') new.fsthandle = foma_fsm_flatten(foma_fsm_copy(self.fsthandle), foma_fsm_copy(eps_sym.fsthandle)) return new class MTFSM(FST): def __init__(self, regex = False, numtapes = 2): if isinstance(regex, str) or isinstance(regex, unicode): FST.__init__(self, regex) eps_sym = FST('□') self.fsthandle = foma_fsm_flatten(foma_fsm_copy(self.fsthandle), foma_fsm_copy(eps_sym.fsthandle)) self.numtapes = numtapes elif isinstance(regex, FST): self.fsthandle = foma_fsm_copy(regex.fsthandle) self.regex = None self.numtapes = numtapes else: self.fsthandle = None self.regex = None def __str__(self): if not self.fsthandle: raise ValueError('FSM not defined') foma_fsm_count(self.fsthandle) s = 'Name: %s\n' % self.fsthandle.contents.name s += 'States: %i\n' % self.fsthandle.contents.statecount s += 'Transitions: %i\n' % self.fsthandle.contents.arccount s += 'Final states: %i\n' % self.fsthandle.contents.finalcount s += 'Deterministic: %i\n' % self.fsthandle.contents.is_deterministic s += 'Minimized: %i\n' % self.fsthandle.contents.is_minimized s += 'Numtapes: %i\n' % self.numtapes return s def parse(self, word): #[word/□ .o. [0:?^(numtapes-1) ?]*].l & Grammar ; m = self.numtapes regx = (u'[{' + word + u'}/□ .o. [0:?^' + str(m-1) + u' ?]*].l') reg = FST(regx) gr = FST() gr.fsthandle = foma_fsm_copy(self.fsthandle) res = MTFSM(reg.intersect(gr), numtapes = m) return res def join(self, other): """Joins two multitape FSMs by composition. E.g. [ a d ] [ c □ □ ] [ a d □ ] A = [ b e ] B = [ d f g ], and A.join(B) = [ b e □ ] [ c □ ] [ e f g ] [ c □ □ ] [ d f g ] [ e f g ] """ m = self.numtapes n = other.numtapes pada = FST('[0:□^' + str(m) +' [0:?^' + str(n-1) + ' - 0:□^' + str(n-1) + '] | ?^' + str(m) + ' 0:?^' + str(n-1) + ']*') padb = FST('[[0:?^' + str(m-1) + ' - 0:□^' + str(m-1) + ' ] 0:□^' + str(n) + '| 0:?^' + str(m-1) + ' ?^' + str(n) + ']*') extenda = self.compose(pada).lower() extendb = other.compose(padb).lower() flt = FST('~[?^' + str(m+n-1) +'* [□^' + str(m) + ' ?^' + str(n-1) + ' [?^' + str(m-1) + ' □^' + str(n) + ' |[?^' + str(m-1) +' - □^' + str(m-1) + ' ] □ [?^' + str(n-1) + ' - □^' + str(n-1) + ' ]] | ?^' + str(m-1) + ' □^' + str(n) + ' [□^' + str(m) + ' ?^' + str(n-1) + ' |[?^' + str(m-1) + ' - □^' + str(m-1) + ' ] □ [?^' + str(n-1) + ' - □^' + str(n-1) + ' ]]] ?*]') res = extenda & extendb & flt result = MTFSM(res, m + n - 1) return result def _apply(self, applyf, word = None): if not self.fsthandle: raise ValueError('FST not defined') applyerhandle = foma_apply_init(self.fsthandle) output = applyf(c_void_p(applyerhandle)) while True: if output == None: foma_apply_clear(c_void_p(applyerhandle)) return else: yield output if word: output = applyf(c_void_p(applyerhandle), None) else: output = applyf(c_void_p(applyerhandle)) def __iter__(self): return self._mtwords() def __add__(self, other): return self.join(other) def _fmt(self, word): cols = word colchunks = [map(lambda z: len(z), word[x:x+self.numtapes]) for x in xrange(0, len(word), self.numtapes)] col_widths = [max(x) for x in colchunks] format = ' '.join(['%%-%ds' % width for width in col_widths]) # string to rows rows = [[word[y] for y in xrange(x, len(word), self.numtapes)] for x in xrange(self.numtapes)] s = '' for row in rows: #s += format % tuple(row) + '\n' s += ''.join(row) + '\n' return s def _mtwords(self): applyf = foma_apply_upper_words if not self.fsthandle: raise ValueError('FST not defined') applyerhandle = foma_apply_init(self.fsthandle) toksym = '\x07' foma_apply_set_space_symbol(c_void_p(applyerhandle), c_char_p(toksym)) output = applyf(c_void_p(applyerhandle)) while True: if output == None: foma_apply_clear(c_void_p(applyerhandle)) return else: yield self._fmt(output[:-1].split('\x07')) output = applyf(c_void_p(applyerhandle))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Главный скрипт PageHandler: Обраточик страниц, перехватывающий все адреса сайта. """ import logging from engine import settings from engine import styles from engine import pagegen from engine import formhandler from engine import rpc from engine import features from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app logging.getLogger().setLevel(logging.INFO) # включаем логгирование событий class PageHandler(webapp.RequestHandler): """Создает объект класса-обработчика страниц Args: webapp.ReauestHandler: обработчик запросов """ def get(self, category): """По методу GET забирает страницу и раздел сайта, задает заголовок портала из настроек и вызывает генератор страниц с параметрами страницы, раздела и параметров шаблона. Args: self: класс обработчика category: запрошенный раздел страницы """ if not category: # если раздел не задан - считаем раздел корневым category = settings.ROOT page_template_values = { # задаем изначальные параметры шаблона страницы 'portal_title': settings.SITETITLE } pagegen.generatePage(self, category, page_template_values) # генерируем страницу application = webapp.WSGIApplication([ ('/styles/(.*)', styles.StylesHandler), ('/formhandler(.*)', formhandler.FormHandler), ('/rpc/(.*)', rpc.RPCHandler) ] + features.features + [('/(.*)', PageHandler)] , debug = settings.DEBUG) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009 Alexey Malashin # # Licensed under GNU License # # 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. """fooCMS package Система управления содержанием на основе Google App Engine для использования с языком python. """ __author__ = 'frozzzen@gmail.com (Alexey Malashin)' __date__ = '28 January 2009' __version__ = '$Revision: 00001 $' __credits__ = 'for all' __all__ = ['main']
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Главный скрипт PageHandler: Обраточик страниц, перехватывающий все адреса сайта. """ import logging from engine import settings from engine import styles from engine import pagegen from engine import formhandler from engine import rpc from engine import features from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app logging.getLogger().setLevel(logging.INFO) # включаем логгирование событий class PageHandler(webapp.RequestHandler): """Создает объект класса-обработчика страниц Args: webapp.ReauestHandler: обработчик запросов """ def get(self, category): """По методу GET забирает страницу и раздел сайта, задает заголовок портала из настроек и вызывает генератор страниц с параметрами страницы, раздела и параметров шаблона. Args: self: класс обработчика category: запрошенный раздел страницы """ if not category: # если раздел не задан - считаем раздел корневым category = settings.ROOT page_template_values = { # задаем изначальные параметры шаблона страницы 'portal_title': settings.SITETITLE } pagegen.generatePage(self, category, page_template_values) # генерируем страницу application = webapp.WSGIApplication([ ('/styles/(.*)', styles.StylesHandler), ('/formhandler(.*)', formhandler.FormHandler), ('/rpc/(.*)', rpc.RPCHandler) ] + features.features + [('/(.*)', PageHandler)] , debug = settings.DEBUG) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """Настройки портала """ # виртуальная директория, где установлена CMS ROOT = '/' # заголовок сайта SITETITLE = 'fooCMS' # название сайта SITECAPTION = 'fooCMS<br><span style="font-size: 60%;">Content Management Sytem for Google App Engine</span>' # ключевые слова тэга meta keywords KEYWORDS = 'CMS, GAE, foo, fooCMS, portal, python' # кодировка используемая в портале (deprecated), 'a' = ascii, 'u' = UTF-8 ENCODING = 'u' # режим отладки DEBUG = True # время кэширования страниц и стилей, по умолчанию = 43200 сек (12 часов) PAGECACHE = 259200 # 72h # время кэширования других объектов из БД DATACACHE = 3600 # код проверки для удаленного вызова процедур RPCODE = 'YOUR-RPC-CODE-HERE' # путь к блокам (относительно папки ./engine) blocksPath = '../blocks/' # путь к шаблонам (относительно папки ./engine) templatesPath = '../templates/' # путь к стилям (относительно папки ./engine) stylesPath = '../styles/'
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ RPC """ import logging from engine import settings from engine.data import news from engine.data import cites from engine.data import pages from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # enable info logging by the app logging.getLogger().setLevel(logging.INFO) class RPCHandler(webapp.RequestHandler): """Класс страницы удаленного вызова процедур """ def get(self, category): """Забираем по методу GET страницу Args: self: класс страницы category: раздел """ result = 'invalid category' self.response.out.write(result) def post(self, category): """Забираем по методу POST страницу Args: self: класс страницы category: раздел """ result = 'invalid category' # результат по-умолчанию if self.request.get('RPCCODE') == settings.RPCODE: # проверяем код RPC if category == 'pages/add': # добавляем страницу page = {'url' : self.request.get('pageURL'), 'title' : self.request.get('pageTitle'), 'description' : self.request.get('pageDescription'), 'content' : self.request.get('pageContent')} result = pages.AddPage(page) elif category == 'pages/get': # получаем страницу url = self.request.get('url') page = pages.GetPages(url) result = page.URL + ':item_end:' + page.Title + ':item_end:' + page.Description + ':item_end:' + page.Content + ':item_end:' elif category == 'news/add': # добавляем новости result = news.AddNews(self.request.get('news')) elif category == 'cites/add': # добавляем цитаты result = cites.AddCite(self.request.get('citeText'), self.request.get('citeAuthor')) else: result = 'Wrong RPC code!' self.response.out.write(result) # выводим результат
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы с цитатами """ import random import logging from engine import settings from google.appengine.ext import db from datetime import datetime class Cite(db.Model): """Класс - цитата """ Text = db.StringProperty(verbose_name = 'Цитата', multiline = True, required = True) Author = db.StringProperty(verbose_name = 'Автор', multiline = False) # Poster = db.UserProperty(required=True) def AddCite(text, author): """Добавить цитату Args: text: текст цитаты author: автор цитаты """ c = Cite(Text = text, Author = author) return c.put() def GetCites(single = True): """Получить цитаты из базы Args: single: получить только одну цитату, взятую случайным образом """ q = Cite.all().order('-Author') # создаем запрос if not q.get(): # если в запросе пусто q = None logging.warning('GetCites: no cites exists!') else: if single and q.get(): random.seed() q = q.fetch(1, random.randint(0, q.count() - 1)) q = q[0] #q = q.get() return q def DelCites(cite): """Удаление цитаты Args: cite: ключи для выборки из базы данных """ results = Cite.get(cite) for result in results: result.delete()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы с новостями """ import logging from engine import settings from google.appengine.ext import db from datetime import datetime #from google.appengine.api import memcache class News(db.Model): """Класс - новость """ Text = db.StringProperty(verbose_name = 'Сообщение', multiline=True, required = True) Date = db.DateTimeProperty(verbose_name = 'Время/Дата', auto_now = True) # Poster = db.UserProperty(required=True) def AddNews(text): """Добвить новость Args: text: текст новости Returns: ключ новости """ n = News(Text = text) return n.put() def GetNews(single = True): """Получить новости из базы Args: single: получить только одну новость (последнюю) Returns: запрос новости """ q = News.all().order('-Date') if not q.get(): q = None logging.warning('GetNews: no news exists!') else: if single: q = q.get() return q def DelNews(news): """Удаление новостей Args: news: ключи для выборки из базы данных """ results = News.get(news) for result in results: result.delete()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы с цитатами """ import random import logging from engine import settings from google.appengine.ext import db from datetime import datetime class Cite(db.Model): """Класс - цитата """ Text = db.StringProperty(verbose_name = 'Цитата', multiline = True, required = True) Author = db.StringProperty(verbose_name = 'Автор', multiline = False) # Poster = db.UserProperty(required=True) def AddCite(text, author): """Добавить цитату Args: text: текст цитаты author: автор цитаты """ c = Cite(Text = text, Author = author) return c.put() def GetCites(single = True): """Получить цитаты из базы Args: single: получить только одну цитату, взятую случайным образом """ q = Cite.all().order('-Author') # создаем запрос if not q.get(): # если в запросе пусто q = None logging.warning('GetCites: no cites exists!') else: if single and q.get(): random.seed() q = q.fetch(1, random.randint(0, q.count() - 1)) q = q[0] #q = q.get() return q def DelCites(cite): """Удаление цитаты Args: cite: ключи для выборки из базы данных """ results = Cite.get(cite) for result in results: result.delete()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы с сообщениями обратной связи """ from engine import settings from google.appengine.ext import db from datetime import datetime class UserMessage(db.Model): """Класс БД сообщений пользователя """ Author = db.StringProperty(verbose_name = "Автор сообщения", required=True) Mail = db.EmailProperty(verbose_name = "Почта для ответа", required=True) Message = db.StringProperty(verbose_name = "Сообщение", multiline=True, required=True) Date = db.DateTimeProperty(verbose_name = "Дата/Время создания", auto_now_add=True) def AddMsg(usermsg): """Добавить сообщение Args: usermsg: сообщение """ m = UserMessage( Author = usermsg['author'], Mail = usermsg['mail'], Message = unicode(usermsg['message']) ) return m.put() def GetMsgs(): """Получить все сообщения из базы в порядке сортировки по дате """ m = UserMessage.all().order('-Date') return m def DelMsg(msgs): """Удаление сообщений Args: msgs: ключи для выборки из базы данных """ results = UserMessage.get(msgs) for result in results: result.delete()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Модуль работы с данными """ __author__ = 'frozzzen@gmail.com (Alexey Malashin)' __all__ = ['cites', 'feedback', 'news', 'pages'] def DropAllDB(): """Удалить все базы данных """ db.Delete(Model.all())
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы со страницами """ from engine import settings from google.appengine.ext import db from google.appengine.api import memcache class Page(db.Model): """Класс БД страница """ URL = db.StringProperty(verbose_name = "Адрес страницы", required=True) Title = db.StringProperty(verbose_name = "Заголовок страницы") Description = db.StringProperty(verbose_name = "Описание страницы") Content = db.TextProperty(verbose_name = "Содержание страницы", required=True) Date = db.DateTimeProperty(verbose_name = "Дата/Время создания", auto_now_add=True) # Author = db.UserProperty(verbose_name = "Автор") def AddPage(page): """Добавить страницу Args: page: dict страницы """ p = GetPages(page['url']) # пытаемся узнать, есть ли уже такая страница в базе if not p: # если нет, создаем новую p = Page( URL = page['url'], Title = unicode(page['title']), Description = unicode(page['description']), Content = unicode(page['content']) ) else: # иначе обновляем данные p.URL = page['url'] p.Title = unicode(page['title']) p.Description = unicode(page['description']) p.Content = unicode(page['content']) memcache.delete('page_' + p.URL) # удаляем из кэша старую страницу #memcache.replace("page_" + p.URL, p, settings.PAGECACHE) # обновляем кэш return p.put() def GetPages(url = ''): """Получить страницы из базы Args: url: получить страницу по полю URL из базы. если пусто - получить все страницы из базы """ if url: p = memcache.get('page_' + url) # пытаемся получить страницу из кэша if p is None: # если ее там не оказалось p = Page.all().filter('URL', url).get() # получаем страницу из базы memcache.add('page_' + url, p, settings.PAGECACHE) # кладем страницу в кэш else: p = Page.all().order('URL') return p def DelPage(page): """Удаление страницы Args: page: ключи для выборки из базы данных """ results = Page.get(page) for result in results: memcache.delete('page_' + result.URL) # удаляем страницу из кэша result.delete() # удаляем страницу из базы def DropPages(): """Удалить таблицу страниц """ db.Delete(Pages.all()) #db.Delete(Model.all())
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы с новостями """ import logging from engine import settings from google.appengine.ext import db from datetime import datetime #from google.appengine.api import memcache class News(db.Model): """Класс - новость """ Text = db.StringProperty(verbose_name = 'Сообщение', multiline=True, required = True) Date = db.DateTimeProperty(verbose_name = 'Время/Дата', auto_now = True) # Poster = db.UserProperty(required=True) def AddNews(text): """Добвить новость Args: text: текст новости Returns: ключ новости """ n = News(Text = text) return n.put() def GetNews(single = True): """Получить новости из базы Args: single: получить только одну новость (последнюю) Returns: запрос новости """ q = News.all().order('-Date') if not q.get(): q = None logging.warning('GetNews: no news exists!') else: if single: q = q.get() return q def DelNews(news): """Удаление новостей Args: news: ключи для выборки из базы данных """ results = News.get(news) for result in results: result.delete()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы со страницами """ from engine import settings from google.appengine.ext import db from google.appengine.api import memcache class Page(db.Model): """Класс БД страница """ URL = db.StringProperty(verbose_name = "Адрес страницы", required=True) Title = db.StringProperty(verbose_name = "Заголовок страницы") Description = db.StringProperty(verbose_name = "Описание страницы") Content = db.TextProperty(verbose_name = "Содержание страницы", required=True) Date = db.DateTimeProperty(verbose_name = "Дата/Время создания", auto_now_add=True) # Author = db.UserProperty(verbose_name = "Автор") def AddPage(page): """Добавить страницу Args: page: dict страницы """ p = GetPages(page['url']) # пытаемся узнать, есть ли уже такая страница в базе if not p: # если нет, создаем новую p = Page( URL = page['url'], Title = unicode(page['title']), Description = unicode(page['description']), Content = unicode(page['content']) ) else: # иначе обновляем данные p.URL = page['url'] p.Title = unicode(page['title']) p.Description = unicode(page['description']) p.Content = unicode(page['content']) memcache.delete('page_' + p.URL) # удаляем из кэша старую страницу #memcache.replace("page_" + p.URL, p, settings.PAGECACHE) # обновляем кэш return p.put() def GetPages(url = ''): """Получить страницы из базы Args: url: получить страницу по полю URL из базы. если пусто - получить все страницы из базы """ if url: p = memcache.get('page_' + url) # пытаемся получить страницу из кэша if p is None: # если ее там не оказалось p = Page.all().filter('URL', url).get() # получаем страницу из базы memcache.add('page_' + url, p, settings.PAGECACHE) # кладем страницу в кэш else: p = Page.all().order('URL') return p def DelPage(page): """Удаление страницы Args: page: ключи для выборки из базы данных """ results = Page.get(page) for result in results: memcache.delete('page_' + result.URL) # удаляем страницу из кэша result.delete() # удаляем страницу из базы def DropPages(): """Удалить таблицу страниц """ db.Delete(Pages.all()) #db.Delete(Model.all())
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Функции работы с сообщениями обратной связи """ from engine import settings from google.appengine.ext import db from datetime import datetime class UserMessage(db.Model): """Класс БД сообщений пользователя """ Author = db.StringProperty(verbose_name = "Автор сообщения", required=True) Mail = db.EmailProperty(verbose_name = "Почта для ответа", required=True) Message = db.StringProperty(verbose_name = "Сообщение", multiline=True, required=True) Date = db.DateTimeProperty(verbose_name = "Дата/Время создания", auto_now_add=True) def AddMsg(usermsg): """Добавить сообщение Args: usermsg: сообщение """ m = UserMessage( Author = usermsg['author'], Mail = usermsg['mail'], Message = unicode(usermsg['message']) ) return m.put() def GetMsgs(): """Получить все сообщения из базы в порядке сортировки по дате """ m = UserMessage.all().order('-Date') return m def DelMsg(msgs): """Удаление сообщений Args: msgs: ключи для выборки из базы данных """ results = UserMessage.get(msgs) for result in results: result.delete()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Модуль работы с данными """ __author__ = 'frozzzen@gmail.com (Alexey Malashin)' __all__ = ['cites', 'feedback', 'news', 'pages'] def DropAllDB(): """Удалить все базы данных """ db.Delete(Model.all())
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Обработчик форм """ import logging from engine import settings from engine.data import feedback from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # enable info logging by the app logging.getLogger().setLevel(logging.INFO) class FormHandler(webapp.RequestHandler): def post(self, category): if category == '/about': # форма о нас form = { 'author': self.request.get('author'), 'mail': self.request.get('mail'), 'message': self.request.get('message') } feedback.AddMsg(form) self.redirect(category)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Обработчик форм """ import logging from engine import settings from engine.data import feedback from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # enable info logging by the app logging.getLogger().setLevel(logging.INFO) class FormHandler(webapp.RequestHandler): def post(self, category): if category == '/about': # форма о нас form = { 'author': self.request.get('author'), 'mail': self.request.get('mail'), 'message': self.request.get('message') } feedback.AddMsg(form) self.redirect(category)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Резервное копирование """ import logging import os import StringIO import tarfile import gzip #import zlib from engine import settings from engine.data import feedback from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def tarPath(root, name, tfile): """Архивируем путь в tar Args: root: a directory; name: entry in root tfile: tarfile object. """ info = tarfile.TarInfo() if root: path = root + '/' + name else: path = name if os.path.isdir(path): entries = os.listdir(path) for entry in entries: fullPath = path + '/' + entry if os.path.isdir(fullPath): info.size = 0 info.name = fullPath info.type = tarfile.DIRTYPE tfile.addfile(info) tarPath('', fullPath, tfile) else: # is file f = file(fullPath,'rb') info.type = tarfile.REGTYPE info.size = os.path.getsize(fullPath); info.name = fullPath info.mtime = os.path.getmtime(fullPath); tfile.addfile(info, f) def gztarfile(path): """Архивируем и сжимаем все файлы и директории по указанному пути. """ tarbuf = StringIO.StringIO() tar = tarfile.TarFile(mode = 'w', fileobj = tarbuf) #tar.add(path) tarPath('', path, tar) tar.close() zbuf = StringIO.StringIO() zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9) zfile.write(tarbuf.getvalue()) zfile.close() return zbuf.getvalue() class BackupHandler(webapp.RequestHandler): def get(self): rootpath = '.' logging.info('Backup started.') dir = os.path.dirname(__file__) filename = 'backup' # + datenow self.redirect(settings.ROOT + 'admin/backup') self.response.set_status(200) self.response.headers['Content-Type'] = 'application/octet-stream' self.response.headers.add_header('Content-Type', 'application/x-compressed') self.response.headers['Content-Disposition'] = 'attachment;filename=' + filename self.response.out.write(gztarfile(rootpath))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """Генератор страниц """ import os import logging import datetime from engine import settings from engine import styles from engine.data import news from engine.data import cites from engine.data import pages from google.appengine.api import users from google.appengine.ext.webapp import template def getFileContent(filePath): """Получить содержимое файла Args: filePath: путь к файлу относительно текущего каталога """ fileContent = os.path.exists(os.path.join(os.path.dirname(__file__), filePath)) if fileContent: # проверяем - существует ли файл fileContent = os.path.join(os.path.dirname(__file__), filePath) try: # если файл существует - пытаемся его открыть и прочитать f = open(fileContent, 'r') fileContent = f.read() except: fileContent = 'foe' # file open error logging.error('getFileContent: open file <%s> error!' % filePath) else: fileContent = 'fnf' # file not found logging.warning('getFileContent: file <%s> not found' % filePath) return fileContent def writeHeaders(self, status = 200, expires = 7): """Запись заголовков страницы Args: self: класс страницы status: код ответа (по-умолчанию - 200 OK) expires: время устаревания (по-умолчанию - 7 дней) """ expires = datetime.datetime.utcnow() + datetime.timedelta(expires) self.response.set_status(status) self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.headers.add_header('Content-Language', 'ru') self.response.headers.add_header('Expires', expires.strftime("%d %b %Y %H:%M:%S GMT")) #self.error(status) def getMenu(IsAdmin=False): """Загрузка меню Args: IsAdmin: загружаем меню администрирования или нет (по-умолчанию - нет). """ if not IsAdmin: # определяем какое меню загружать type = 'pages' elif IsAdmin: type = 'admin' # пытаемся загрузить меню из файла menu = getFileContent(settings.blocksPath + '_menu_' + type + '_' + settings.ENCODING + '.blk') if (menu == 'fnf') or (menu == 'foe'): # если не получилось загрузить меню menu = '<h1 style="color: red;">Меню не найдено!</h1>' logging.warning('getMenu: menu IsAdmin=%s not opened!' % IsAdmin) return menu def getContent(blockContent): """Получаем содержание запрошенной страницы. Args: blockContent: запрошенный раздел сайта """ status = 200 # статус ответа по-умолчанию OK if blockContent == 'news': # если запросили раздел новостей content = news.GetNews(False) # получаем ВСЕ новости из базы if content == None: content = 'nonews' # устанавливаем тэг отсутствия новостей, если их нет logging.warning('getContent: no news exists for page <%s>' % blockContent) elif blockContent.startswith('/admin'): # если запросили раздел администрирования - считываем раздел из файла content = getFileContent(settings.blocksPath + blockContent + '_' + settings.ENCODING + '.blk') if content == 'fnf': # ошибка - файл не найден content = '<h1 style="color: red;">Раздел не найден</h1>' status = 404 elif content == 'foe': # ошибка - проблема со считыванием файла content = '<h1 style="color: red;">Ошибка загрузки раздела</h1>' status = 500 else: # если запросили любой другой раздел if blockContent == 'main': blockContent = '' # для главной страницы - блок пустой content = pages.GetPages(settings.ROOT + blockContent) # получаем раздел из базы if not content: # если не загрузилось содержимое страницы #content = errorLoadBlock(404, 'content') content = pages.GetPages('404')# устанавливаем ошибку - страница не найдена status = 404 logging.warning('getContent: page <%s> not found!' % blockContent) if content == None: # если ни одна страница не загрузилась - сайт не настроен (в базе пусто) content = '<h1 style="color: red;">Сайт в разработке</h1><br>На сайте отсутсвуют страницы.<br>\ Пожалуйста, зайдите в раздел администрирования и добавьте страницы.' logging.error('getContent: pages don`t exist in DB (page requested: %s)' % blockContent) status = 500 return content, status # возвращаем результат и статус страницы def getUser(user = None): """Загрузка блока пользователя Args: user: текущий пользователь """ if user: user_block = ("Welcome, <a href=\"mailto:%s\">%s</a>! (<a href=\"%s\">sign out</a>)" % (user.email(), user.nickname(), users.create_logout_url("/"))) if users.is_current_user_admin(): user_block = ("%s<br><a href=\"/admin/\">Adminko</a>" % user_block) else: user_block = ("<a href=\"%s\"> Sign in or register</a>." % users.create_login_url("/")) return user_block def generateEmbed(templateFile, data): """Генератор встраиваемого кода для фишек Args: template: шаблон (относительно пути, где лежат шаблоны data: данные """ tpl_file = os.path.join(os.path.dirname(__file__), settings.templatesPath + templateFile + '.tpl') if os.path.exists(tpl_file): embed_out = template.render(tpl_file, { 'entrys': data }) else: embed_out = 'error' sel.response.out.write(embed_out) def generatePage(self, pagereq, template_values): """Генератор страниц Args: self: класс pagereq: запрошенная страница (раздел) относительно корня template_values: параметры шаблона страницы """ # *** определяем, какой шаблон использовать *** if pagereq == settings.ROOT: # главная страница tpl_file = 'page_main' pagereq = 'main' elif pagereq.startswith('/admin'): # админка tpl_file = 'page_admin' elif os.path.exists( os.path.join(os.path.dirname(__file__), # страница settings.templatesPath + 'page_' + pagereq + '_' + settings.ENCODING + '.tpl') ): tpl_file = 'page_' + pagereq elif os.path.exists( os.path.join(os.path.dirname(__file__), # модуль settings.templatesPath + 'feature_' + pagereq + '_' + settings.ENCODING + '.tpl') ): tpl_file = 'feature_' + pagereq else: # любая другая страница tpl_file = 'page_simple' page = getContent(pagereq) # получаем содержание страницы и статус template_values.update( # обновляем значения параметров шаблона #portal_title = settings.SITETITLE, # ...заголовок сайта portal_caption = settings.SITECAPTION, # ...название сайта portal_keywords = settings.KEYWORDS, # ...ключевые слова сайта (тэг meta keywords) page_menu = getMenu(pagereq.startswith('/admin')), # ...меню (админки или обычное) page = page[0], # ...содержание страницы page_user = getUser(users.get_current_user()) ) # ...блок пользователя template_values.update(page_styles = styles.getStyles(pagereq)) # получаем стили страницы if pagereq == 'main': # параметры главной страницы n = news.GetNews() # загружаем новости c = cites.GetCites() # загружаем цитаты if not n: n = '<h1 style="color: red;">Ошибка загрузки новостей</h1>' logging.warning('generatePage: error loading news on page <%s>' % pagereq) else: n = n.Text # если новость получена, забираем ее текст if not c: c = '<h1 style="color: red;">Ошибка загрузки цитат</h1>' logging.warning('generatePage: error loading cites on page <%s>' % pagereq) # выставляем параметры шаблона для новостей и цитат template_values.update( page_news = n, page_cite = c ) # генерируем шаблон path_template = os.path.join( os.path.dirname(__file__), settings.templatesPath + tpl_file + '_' + settings.ENCODING + '.tpl') page_out = template.render(path_template, template_values) writeHeaders(self, page[1]) # прописываем заголовки self.response.out.write(page_out) # выводим страницу
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Инициализация """ __author__ = 'frozzzen@gmail.com (Alexey Malashin)' __date__ = '28 January 2009' __version__ = '$Revision: 00001 $' __credits__ = 'for all' __all__ = ['pagegen', 'settings', 'styles', 'formhandler', 'backup']
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ RPC """ import logging from engine import settings from engine.data import news from engine.data import cites from engine.data import pages from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # enable info logging by the app logging.getLogger().setLevel(logging.INFO) class RPCHandler(webapp.RequestHandler): """Класс страницы удаленного вызова процедур """ def get(self, category): """Забираем по методу GET страницу Args: self: класс страницы category: раздел """ result = 'invalid category' self.response.out.write(result) def post(self, category): """Забираем по методу POST страницу Args: self: класс страницы category: раздел """ result = 'invalid category' # результат по-умолчанию if self.request.get('RPCCODE') == settings.RPCODE: # проверяем код RPC if category == 'pages/add': # добавляем страницу page = {'url' : self.request.get('pageURL'), 'title' : self.request.get('pageTitle'), 'description' : self.request.get('pageDescription'), 'content' : self.request.get('pageContent')} result = pages.AddPage(page) elif category == 'pages/get': # получаем страницу url = self.request.get('url') page = pages.GetPages(url) result = page.URL + ':item_end:' + page.Title + ':item_end:' + page.Description + ':item_end:' + page.Content + ':item_end:' elif category == 'news/add': # добавляем новости result = news.AddNews(self.request.get('news')) elif category == 'cites/add': # добавляем цитаты result = cites.AddCite(self.request.get('citeText'), self.request.get('citeAuthor')) else: result = 'Wrong RPC code!' self.response.out.write(result) # выводим результат
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Обработчик стилей """ import logging from os import path from engine import settings from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import memcache # enable info logging by the app logging.getLogger().setLevel(logging.INFO) class StylesHandler(webapp.RequestHandler): """Класс страницы стилей """ def get(self, style = 'none'): """По методу GET забираем адрес стиля Args: self: класс страницы style: стиль который запросили (по-умолчанию none.css) """ style_content = memcache.get('style_' + style) # пытаемся получить стиль из кэша if (style_content is None): # or settings.DEBUG: # если его там не нашлось style_path = path.join(path.dirname(__file__), settings.stylesPath, style + '.css') if not path.exists(style_path): style_path = path.join(path.dirname(__file__), settings.stylesPath, 'none.css') try: style_content = open(style_path).read() # считываем стиль из файла except: style_content = 'error' memcache.add('style_' + style, style_content, settings.PAGECACHE) # кладем стиль в кэш self.response.headers['Content-Type'] = 'text/css; charset=utf-8' # self.response.headers.add_header('Expires', 'Mon, 01 Dec 1994 16:00:00 GMT') self.response.out.write(style_content) def getStyles(page): """Получить стили для запрошенной страницы Args: page: URL страницы """ lst = page.split('/') # разделяем путь к стилю по категориям s = [] # итоговые стили страницы for item in lst: # проверяем каждый стиль, существует ли файл стиля if path.exists(path.join(path.dirname(__file__), settings.stylesPath, item + '.css')): s += [item] return s
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """Генератор страниц """ import os import logging import datetime from engine import settings from engine import styles from engine.data import news from engine.data import cites from engine.data import pages from google.appengine.api import users from google.appengine.ext.webapp import template def getFileContent(filePath): """Получить содержимое файла Args: filePath: путь к файлу относительно текущего каталога """ fileContent = os.path.exists(os.path.join(os.path.dirname(__file__), filePath)) if fileContent: # проверяем - существует ли файл fileContent = os.path.join(os.path.dirname(__file__), filePath) try: # если файл существует - пытаемся его открыть и прочитать f = open(fileContent, 'r') fileContent = f.read() except: fileContent = 'foe' # file open error logging.error('getFileContent: open file <%s> error!' % filePath) else: fileContent = 'fnf' # file not found logging.warning('getFileContent: file <%s> not found' % filePath) return fileContent def writeHeaders(self, status = 200, expires = 7): """Запись заголовков страницы Args: self: класс страницы status: код ответа (по-умолчанию - 200 OK) expires: время устаревания (по-умолчанию - 7 дней) """ expires = datetime.datetime.utcnow() + datetime.timedelta(expires) self.response.set_status(status) self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.headers.add_header('Content-Language', 'ru') self.response.headers.add_header('Expires', expires.strftime("%d %b %Y %H:%M:%S GMT")) #self.error(status) def getMenu(IsAdmin=False): """Загрузка меню Args: IsAdmin: загружаем меню администрирования или нет (по-умолчанию - нет). """ if not IsAdmin: # определяем какое меню загружать type = 'pages' elif IsAdmin: type = 'admin' # пытаемся загрузить меню из файла menu = getFileContent(settings.blocksPath + '_menu_' + type + '_' + settings.ENCODING + '.blk') if (menu == 'fnf') or (menu == 'foe'): # если не получилось загрузить меню menu = '<h1 style="color: red;">Меню не найдено!</h1>' logging.warning('getMenu: menu IsAdmin=%s not opened!' % IsAdmin) return menu def getContent(blockContent): """Получаем содержание запрошенной страницы. Args: blockContent: запрошенный раздел сайта """ status = 200 # статус ответа по-умолчанию OK if blockContent == 'news': # если запросили раздел новостей content = news.GetNews(False) # получаем ВСЕ новости из базы if content == None: content = 'nonews' # устанавливаем тэг отсутствия новостей, если их нет logging.warning('getContent: no news exists for page <%s>' % blockContent) elif blockContent.startswith('/admin'): # если запросили раздел администрирования - считываем раздел из файла content = getFileContent(settings.blocksPath + blockContent + '_' + settings.ENCODING + '.blk') if content == 'fnf': # ошибка - файл не найден content = '<h1 style="color: red;">Раздел не найден</h1>' status = 404 elif content == 'foe': # ошибка - проблема со считыванием файла content = '<h1 style="color: red;">Ошибка загрузки раздела</h1>' status = 500 else: # если запросили любой другой раздел if blockContent == 'main': blockContent = '' # для главной страницы - блок пустой content = pages.GetPages(settings.ROOT + blockContent) # получаем раздел из базы if not content: # если не загрузилось содержимое страницы #content = errorLoadBlock(404, 'content') content = pages.GetPages('404')# устанавливаем ошибку - страница не найдена status = 404 logging.warning('getContent: page <%s> not found!' % blockContent) if content == None: # если ни одна страница не загрузилась - сайт не настроен (в базе пусто) content = '<h1 style="color: red;">Сайт в разработке</h1><br>На сайте отсутсвуют страницы.<br>\ Пожалуйста, зайдите в раздел администрирования и добавьте страницы.' logging.error('getContent: pages don`t exist in DB (page requested: %s)' % blockContent) status = 500 return content, status # возвращаем результат и статус страницы def getUser(user = None): """Загрузка блока пользователя Args: user: текущий пользователь """ if user: user_block = ("Welcome, <a href=\"mailto:%s\">%s</a>! (<a href=\"%s\">sign out</a>)" % (user.email(), user.nickname(), users.create_logout_url("/"))) if users.is_current_user_admin(): user_block = ("%s<br><a href=\"/admin/\">Adminko</a>" % user_block) else: user_block = ("<a href=\"%s\"> Sign in or register</a>." % users.create_login_url("/")) return user_block def generateEmbed(templateFile, data): """Генератор встраиваемого кода для фишек Args: template: шаблон (относительно пути, где лежат шаблоны data: данные """ tpl_file = os.path.join(os.path.dirname(__file__), settings.templatesPath + templateFile + '.tpl') if os.path.exists(tpl_file): embed_out = template.render(tpl_file, { 'entrys': data }) else: embed_out = 'error' sel.response.out.write(embed_out) def generatePage(self, pagereq, template_values): """Генератор страниц Args: self: класс pagereq: запрошенная страница (раздел) относительно корня template_values: параметры шаблона страницы """ # *** определяем, какой шаблон использовать *** if pagereq == settings.ROOT: # главная страница tpl_file = 'page_main' pagereq = 'main' elif pagereq.startswith('/admin'): # админка tpl_file = 'page_admin' elif os.path.exists( os.path.join(os.path.dirname(__file__), # страница settings.templatesPath + 'page_' + pagereq + '_' + settings.ENCODING + '.tpl') ): tpl_file = 'page_' + pagereq elif os.path.exists( os.path.join(os.path.dirname(__file__), # модуль settings.templatesPath + 'feature_' + pagereq + '_' + settings.ENCODING + '.tpl') ): tpl_file = 'feature_' + pagereq else: # любая другая страница tpl_file = 'page_simple' page = getContent(pagereq) # получаем содержание страницы и статус template_values.update( # обновляем значения параметров шаблона #portal_title = settings.SITETITLE, # ...заголовок сайта portal_caption = settings.SITECAPTION, # ...название сайта portal_keywords = settings.KEYWORDS, # ...ключевые слова сайта (тэг meta keywords) page_menu = getMenu(pagereq.startswith('/admin')), # ...меню (админки или обычное) page = page[0], # ...содержание страницы page_user = getUser(users.get_current_user()) ) # ...блок пользователя template_values.update(page_styles = styles.getStyles(pagereq)) # получаем стили страницы if pagereq == 'main': # параметры главной страницы n = news.GetNews() # загружаем новости c = cites.GetCites() # загружаем цитаты if not n: n = '<h1 style="color: red;">Ошибка загрузки новостей</h1>' logging.warning('generatePage: error loading news on page <%s>' % pagereq) else: n = n.Text # если новость получена, забираем ее текст if not c: c = '<h1 style="color: red;">Ошибка загрузки цитат</h1>' logging.warning('generatePage: error loading cites on page <%s>' % pagereq) # выставляем параметры шаблона для новостей и цитат template_values.update( page_news = n, page_cite = c ) # генерируем шаблон path_template = os.path.join( os.path.dirname(__file__), settings.templatesPath + tpl_file + '_' + settings.ENCODING + '.tpl') page_out = template.render(path_template, template_values) writeHeaders(self, page[1]) # прописываем заголовки self.response.out.write(page_out) # выводим страницу
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Инициализация """ __author__ = 'frozzzen@gmail.com (Alexey Malashin)' __date__ = '28 January 2009' __version__ = '$Revision: 00001 $' __credits__ = 'for all' __all__ = ['pagegen', 'settings', 'styles', 'formhandler', 'backup']
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Обработчик стилей """ import logging from os import path from engine import settings from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import memcache # enable info logging by the app logging.getLogger().setLevel(logging.INFO) class StylesHandler(webapp.RequestHandler): """Класс страницы стилей """ def get(self, style = 'none'): """По методу GET забираем адрес стиля Args: self: класс страницы style: стиль который запросили (по-умолчанию none.css) """ style_content = memcache.get('style_' + style) # пытаемся получить стиль из кэша if (style_content is None): # or settings.DEBUG: # если его там не нашлось style_path = path.join(path.dirname(__file__), settings.stylesPath, style + '.css') if not path.exists(style_path): style_path = path.join(path.dirname(__file__), settings.stylesPath, 'none.css') try: style_content = open(style_path).read() # считываем стиль из файла except: style_content = 'error' memcache.add('style_' + style, style_content, settings.PAGECACHE) # кладем стиль в кэш self.response.headers['Content-Type'] = 'text/css; charset=utf-8' # self.response.headers.add_header('Expires', 'Mon, 01 Dec 1994 16:00:00 GMT') self.response.out.write(style_content) def getStyles(page): """Получить стили для запрошенной страницы Args: page: URL страницы """ lst = page.split('/') # разделяем путь к стилю по категориям s = [] # итоговые стили страницы for item in lst: # проверяем каждый стиль, существует ли файл стиля if path.exists(path.join(path.dirname(__file__), settings.stylesPath, item + '.css')): s += [item] return s
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Резервное копирование """ import logging import os import StringIO import tarfile import gzip #import zlib from engine import settings from engine.data import feedback from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def tarPath(root, name, tfile): """Архивируем путь в tar Args: root: a directory; name: entry in root tfile: tarfile object. """ info = tarfile.TarInfo() if root: path = root + '/' + name else: path = name if os.path.isdir(path): entries = os.listdir(path) for entry in entries: fullPath = path + '/' + entry if os.path.isdir(fullPath): info.size = 0 info.name = fullPath info.type = tarfile.DIRTYPE tfile.addfile(info) tarPath('', fullPath, tfile) else: # is file f = file(fullPath,'rb') info.type = tarfile.REGTYPE info.size = os.path.getsize(fullPath); info.name = fullPath info.mtime = os.path.getmtime(fullPath); tfile.addfile(info, f) def gztarfile(path): """Архивируем и сжимаем все файлы и директории по указанному пути. """ tarbuf = StringIO.StringIO() tar = tarfile.TarFile(mode = 'w', fileobj = tarbuf) #tar.add(path) tarPath('', path, tar) tar.close() zbuf = StringIO.StringIO() zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9) zfile.write(tarbuf.getvalue()) zfile.close() return zbuf.getvalue() class BackupHandler(webapp.RequestHandler): def get(self): rootpath = '.' logging.info('Backup started.') dir = os.path.dirname(__file__) filename = 'backup' # + datenow self.redirect(settings.ROOT + 'admin/backup') self.response.set_status(200) self.response.headers['Content-Type'] = 'application/octet-stream' self.response.headers.add_header('Content-Type', 'application/x-compressed') self.response.headers['Content-Disposition'] = 'attachment;filename=' + filename self.response.out.write(gztarfile(rootpath))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Видеогалерея, основанная на youtube """ import logging import gdata.geo import config #from gdata import media from gdata.alt import appengine from gdata import youtube from gdata.youtube import service #from gdata import urlfetch from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from engine import settings from engine import pagegen # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def getVideos(playlistid = 'none', videoid = 'none'): """Получить видеоальбом. Args: playlistid: идентификатор плейлиста в youtube videosid: идентификатор плейлиста (список видео) videoid: идентификатор видеофайла Returns: данные альбома или фотографии """ try: gd_client = gdata.youtube.service.YouTubeService() gd_client.email = config.GD_mail # username gd_client.password = config.GD_password # password gd_client.source = config.GD_clientid # YOUTUBE_CLIENT_ID; YOUTUBE_TEST_CLIENT_ID = 'ytapi-pythonclientlibrary_servicetest' gd_client.developer_key = config.GD_devkey # developer_key gd_client.client_id = config.GD_clientid # YOUTUBE_CLIENT_ID; YOUTUBE_TEST_CLIENT_ID = 'ytapi-pythonclientlibrary_servicetest' gd_client.debug = settings.DEBUG gdata.alt.appengine.run_on_appengine(gd_client) gd_client.ProgrammaticLogin() if playlistid == 'none' and videoid == 'none': # если ничего не задано data = gd_client.GetYouTubePlaylistFeed(username = config.GD_youtube) # получаем список плейлистов пользователя elif playlistid != 'none': # если задан ид плейлиста data = gd_client.GetYouTubePlaylistVideoFeed(playlist_id = playlistid) # получаем список роликов в нем elif videoid != 'none': # или получаем данные конкретного видео data = gd_client.GetYouTubeVideoEntry(video_id = videoid) except Exception, error: # если произошла ошибка... data = { 'error': 'Sorry, dude, service can`t load videos, please, come back later...' } logging.error( 'getVideos: Error = %s; playlsitid = %s; videoid = %s' % (error, playlistid, videoid) ) return data class VideoHandler(webapp.RequestHandler): """Класс-обработчик видеогалереи """ def get(self): """Получить по методу GET галерею Args: self: класс-страница """ playlistid = self.request.get('playlistid', default_value = 'none') # получаем id плейлиста videoid = self.request.get('videoid', default_value = 'none') # получаем id видеоролика page_template_values = { 'portal_title': 'Видеогаларея ' + settings.SITETITLE, 'page_description': 'наше видео' } data = getVideos(playlistid, videoid) # получаем данные if type(data) == dict: # если тип = dict значт возникла ошибка... action = 'error' entrys = data elif playlistid == 'none' and videoid == 'none': # если никакой из параметров не задан action = 'playlists' entrys = [] for e in data.entry: # строим список с dict-элементами, содержащими параметры плейлиста id = e.id.text.split('/') id = id[len(id) - 1] entrys += [{ 'id': id, 'title': e.title.text, 'description': e.description.text, 'content': e.content.text, 'updated': e.updated.text, 'published': e.published.text }] page_template_values.update( logo = data.logo.text ) # логотипчик elif playlistid != 'none': # если задан ид плейлиста action = 'playlist' entrys = [] for e in data.entry: # строим список с dict-элементами, содержащими видеоролики в плейлисте id = e.link[0].href.split('/') id = id[len(id) - 1].split('=')[1] entrys += [{ 'id': id, 'title': e.title.text, 'thumb': e.media.thumbnail[0].url, 'description': e.description.text, 'content': e.content.text, 'updated': e.updated.text, }] #'published': e.published.text }] page_template_values.update( logo = data.logo.text, total = data.total_results.text ) # логотипчик и количество роликов elif videoid != 'none': # выбран конкретный ролик action = 'video' #player = 'yt' # для плеера с youtube player = 'my' # для своего плеера entrys = { 'geo': data.geo, # строим dict с характеристиками видеоролика 'title': data.title.text, 'summary': data.summary, 'description': data.media.description.text, 'player': data.media.player.url, 'duration': data.media.duration.seconds, 'video': data.GetSwfUrl() } page_template_values.update( playersource = player ) # задаем вид плеера (наш или ютубовский) page_template_values.update( action = action, entrys = entrys ) # задаем действие и содержание if action != 'error': page_template_values.update( author = data.author[0].name.text, # параметры шаблона, общие для плейлистов, списков видео и роликов title = data.title.text, updated = data.updated.text ) pagegen.generatePage(self, 'video', page_template_values) # выводим страницу
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Галерея, основанная на picasaweb """ import logging import gdata.geo import config #from gdata import media from gdata.alt import appengine from gdata.photos import service from google.appengine.ext import webapp from engine import settings from engine import pagegen # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def getGallery(id = '0'): """Получить фотоальбом. Args: id: идентификатор фотоальбома пользователя в picasaweb Returns: данные альбома или фотографии """ try: gd_client = gdata.photos.service.PhotosService() gd_client.email = config.GD_mail gd_client.password = config.GD_password gd_client.source = config.GD_picasa gd_client.debug = settings.DEBUG gdata.alt.appengine.run_on_appengine(gd_client) gd_client.ProgrammaticLogin() if id == 'albums': albums = gd_client.GetUserFeed(user = config.GD_picasa) data = albums.entry else: photos = gd_client.GetFeed('/data/feed/api/user/%s/albumid/%s?kind=photo' % (config.GD_picasa, str(id))) data = photos.entry except Exception, error: data = { 'error': 'Sorry, dude, service can`t load photoalbums, please, come back later...' } logging.error('getGallery: Error = %s; id = %s' % (error, id) ) return data class GalleryHandler(webapp.RequestHandler): """Класс - обработчик галереи """ def get(self): """Получить по методу GET галерею Args: self: класс-страница """ id = self.request.get('id', default_value = 'albums') # получаем id альбома #embed = self.request.get('embed', default_value = 'no') # получить html код для встраивания в страницу? page_template_values = { 'portal_title': 'Фотогалерея ' + settings.SITETITLE, 'page_description': 'наши фотоальбомы', } data = getGallery(id) # получаем данные альбома if type(data) == dict: # если тип == dict значт произошла ошибка и ее положили в entry.error action = 'error' elif id == 'albums': action = 'albums' else: action = 'photos' page_template_values.update(action = action, entrys = data) pagegen.generatePage(self, 'gallery', page_template_values)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Фишки, которые можно прикрутить к сайту """ import gallery import video import files import docs #import stub __author__ = 'frozzzen@gmail.com (Alexey Malashin)' # __all__ = ['gallery', 'video', 'files'] features = [ ('/gallery', gallery.GalleryHandler), # фотогалерея ('/video', video.VideoHandler), # видеогалерея ('/docs', docs.DocsHandler), #('/files', files.FilesHandler), # файловый архив #('/stub', stub.StubHandler) ]
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Галерея, основанная на picasaweb """ import logging import config import gdata.docs.service import gdata.docs from gdata.alt import appengine from google.appengine.ext import webapp from engine import settings from engine import pagegen # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def getDoc(id = 'none', dtype = 'all'): """ Args: id: dtype: Returns: """ try: gd_client = gdata.docs.service.DocsService() gd_client.email = config.GD_mail gd_client.password = config.GD_password gd_client.source = 'fooCMS-portal-2' gd_client.debug = settings.DEBUG gdata.alt.appengine.run_on_appengine(gd_client) gd_client.ProgrammaticLogin() if dtype == 'all': data = gd_client.GetDocumentListFeed() elif (dtype != 'all') and (id == 'none'): query = gdata.docs.service.DocumentQuery(categories = [dtype]) data = gd_client.Query(query.ToUri()) elif id != 'none': data = 'doc loaded here' except Exception, error: data = { 'error': 'Sorry, dude, service can`t load docs, please, come back later...' } logging.error('getDoc: Error = %s; id = %s' % (error, id) ) return data class DocsHandler(webapp.RequestHandler): """ """ def get(self): """ Args: self: """ doc_id = self.request.get('id', default_value = 'none') doc_type = self.request.get('type', default_value = 'all') page_template_values = { 'portal_title': 'Документы ' + settings.SITETITLE, 'page_description': 'документы для изучения', } data = getDoc(doc_id, doc_type) if type(data) == dict: action = 'error' entrys = data else: action = doc_type entrys = [] for e in data.entry: id = e.id.text.split('/') id = id[len(id) - 1].split('%3A') dtype = id[0] id = id[1] entrys += [{ 'id': id, 'title': e.title.text, #.encode('UTF-8'), 'type': dtype, #'link': 'http://%s.google.com/%s?%s=' % (id)# e.GetAlternateLink().href }] page_template_values.update(action = action, entrys = entrys) pagegen.generatePage(self, 'docs', page_template_values)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Файловая хранилка на основе openomy """ from google.appengine.ext import webapp class FilesHandler(webapp.RequestHandler): def get(self): pass
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Галерея, основанная на picasaweb """ import logging import gdata.geo import config #from gdata import media from gdata.alt import appengine from gdata.photos import service from google.appengine.ext import webapp from engine import settings from engine import pagegen # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def getGallery(id = '0'): """Получить фотоальбом. Args: id: идентификатор фотоальбома пользователя в picasaweb Returns: данные альбома или фотографии """ try: gd_client = gdata.photos.service.PhotosService() gd_client.email = config.GD_mail gd_client.password = config.GD_password gd_client.source = config.GD_picasa gd_client.debug = settings.DEBUG gdata.alt.appengine.run_on_appengine(gd_client) gd_client.ProgrammaticLogin() if id == 'albums': albums = gd_client.GetUserFeed(user = config.GD_picasa) data = albums.entry else: photos = gd_client.GetFeed('/data/feed/api/user/%s/albumid/%s?kind=photo' % (config.GD_picasa, str(id))) data = photos.entry except Exception, error: data = { 'error': 'Sorry, dude, service can`t load photoalbums, please, come back later...' } logging.error('getGallery: Error = %s; id = %s' % (error, id) ) return data class GalleryHandler(webapp.RequestHandler): """Класс - обработчик галереи """ def get(self): """Получить по методу GET галерею Args: self: класс-страница """ id = self.request.get('id', default_value = 'albums') # получаем id альбома #embed = self.request.get('embed', default_value = 'no') # получить html код для встраивания в страницу? page_template_values = { 'portal_title': 'Фотогалерея ' + settings.SITETITLE, 'page_description': 'наши фотоальбомы', } data = getGallery(id) # получаем данные альбома if type(data) == dict: # если тип == dict значт произошла ошибка и ее положили в entry.error action = 'error' elif id == 'albums': action = 'albums' else: action = 'photos' page_template_values.update(action = action, entrys = data) pagegen.generatePage(self, 'gallery', page_template_values)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Файловая хранилка на основе openomy """ from google.appengine.ext import webapp class FilesHandler(webapp.RequestHandler): def get(self): pass
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Фишки, которые можно прикрутить к сайту """ import gallery import video import files import docs #import stub __author__ = 'frozzzen@gmail.com (Alexey Malashin)' # __all__ = ['gallery', 'video', 'files'] features = [ ('/gallery', gallery.GalleryHandler), # фотогалерея ('/video', video.VideoHandler), # видеогалерея ('/docs', docs.DocsHandler), #('/files', files.FilesHandler), # файловый архив #('/stub', stub.StubHandler) ]
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Галерея, основанная на picasaweb """ import logging import config import gdata.docs.service import gdata.docs from gdata.alt import appengine from google.appengine.ext import webapp from engine import settings from engine import pagegen # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def getDoc(id = 'none', dtype = 'all'): """ Args: id: dtype: Returns: """ try: gd_client = gdata.docs.service.DocsService() gd_client.email = config.GD_mail gd_client.password = config.GD_password gd_client.source = 'fooCMS-portal-2' gd_client.debug = settings.DEBUG gdata.alt.appengine.run_on_appengine(gd_client) gd_client.ProgrammaticLogin() if dtype == 'all': data = gd_client.GetDocumentListFeed() elif (dtype != 'all') and (id == 'none'): query = gdata.docs.service.DocumentQuery(categories = [dtype]) data = gd_client.Query(query.ToUri()) elif id != 'none': data = 'doc loaded here' except Exception, error: data = { 'error': 'Sorry, dude, service can`t load docs, please, come back later...' } logging.error('getDoc: Error = %s; id = %s' % (error, id) ) return data class DocsHandler(webapp.RequestHandler): """ """ def get(self): """ Args: self: """ doc_id = self.request.get('id', default_value = 'none') doc_type = self.request.get('type', default_value = 'all') page_template_values = { 'portal_title': 'Документы ' + settings.SITETITLE, 'page_description': 'документы для изучения', } data = getDoc(doc_id, doc_type) if type(data) == dict: action = 'error' entrys = data else: action = doc_type entrys = [] for e in data.entry: id = e.id.text.split('/') id = id[len(id) - 1].split('%3A') dtype = id[0] id = id[1] entrys += [{ 'id': id, 'title': e.title.text, #.encode('UTF-8'), 'type': dtype, #'link': 'http://%s.google.com/%s?%s=' % (id)# e.GetAlternateLink().href }] page_template_values.update(action = action, entrys = entrys) pagegen.generatePage(self, 'docs', page_template_values)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Параметры фич """ # аккаунт для доступа к google data GD_mail = 'YOUR-M@IL-HERE' # пароль для доступа к google data GD_password = 'YOUR-PASSW0RD-H3RE' # пользователь в веб-альбомах picasa GD_picasa = 'YOUR-GALLERY-USER-HERE' # пользователь в youtube GD_youtube = 'YOUR-YOUTUBE-USER-HERE' # developer key для youtube GD_devkey = 'youtubedeveloperkeyhere' # client id для youtube GD_clientid = 'youtubeclientidhere'
Python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Видеогалерея, основанная на youtube """ import logging import gdata.geo import config #from gdata import media from gdata.alt import appengine from gdata import youtube from gdata.youtube import service #from gdata import urlfetch from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from engine import settings from engine import pagegen # enable info logging by the app logging.getLogger().setLevel(logging.INFO) def getVideos(playlistid = 'none', videoid = 'none'): """Получить видеоальбом. Args: playlistid: идентификатор плейлиста в youtube videosid: идентификатор плейлиста (список видео) videoid: идентификатор видеофайла Returns: данные альбома или фотографии """ try: gd_client = gdata.youtube.service.YouTubeService() gd_client.email = config.GD_mail # username gd_client.password = config.GD_password # password gd_client.source = config.GD_clientid # YOUTUBE_CLIENT_ID; YOUTUBE_TEST_CLIENT_ID = 'ytapi-pythonclientlibrary_servicetest' gd_client.developer_key = config.GD_devkey # developer_key gd_client.client_id = config.GD_clientid # YOUTUBE_CLIENT_ID; YOUTUBE_TEST_CLIENT_ID = 'ytapi-pythonclientlibrary_servicetest' gd_client.debug = settings.DEBUG gdata.alt.appengine.run_on_appengine(gd_client) gd_client.ProgrammaticLogin() if playlistid == 'none' and videoid == 'none': # если ничего не задано data = gd_client.GetYouTubePlaylistFeed(username = config.GD_youtube) # получаем список плейлистов пользователя elif playlistid != 'none': # если задан ид плейлиста data = gd_client.GetYouTubePlaylistVideoFeed(playlist_id = playlistid) # получаем список роликов в нем elif videoid != 'none': # или получаем данные конкретного видео data = gd_client.GetYouTubeVideoEntry(video_id = videoid) except Exception, error: # если произошла ошибка... data = { 'error': 'Sorry, dude, service can`t load videos, please, come back later...' } logging.error( 'getVideos: Error = %s; playlsitid = %s; videoid = %s' % (error, playlistid, videoid) ) return data class VideoHandler(webapp.RequestHandler): """Класс-обработчик видеогалереи """ def get(self): """Получить по методу GET галерею Args: self: класс-страница """ playlistid = self.request.get('playlistid', default_value = 'none') # получаем id плейлиста videoid = self.request.get('videoid', default_value = 'none') # получаем id видеоролика page_template_values = { 'portal_title': 'Видеогаларея ' + settings.SITETITLE, 'page_description': 'наше видео' } data = getVideos(playlistid, videoid) # получаем данные if type(data) == dict: # если тип = dict значт возникла ошибка... action = 'error' entrys = data elif playlistid == 'none' and videoid == 'none': # если никакой из параметров не задан action = 'playlists' entrys = [] for e in data.entry: # строим список с dict-элементами, содержащими параметры плейлиста id = e.id.text.split('/') id = id[len(id) - 1] entrys += [{ 'id': id, 'title': e.title.text, 'description': e.description.text, 'content': e.content.text, 'updated': e.updated.text, 'published': e.published.text }] page_template_values.update( logo = data.logo.text ) # логотипчик elif playlistid != 'none': # если задан ид плейлиста action = 'playlist' entrys = [] for e in data.entry: # строим список с dict-элементами, содержащими видеоролики в плейлисте id = e.link[0].href.split('/') id = id[len(id) - 1].split('=')[1] entrys += [{ 'id': id, 'title': e.title.text, 'thumb': e.media.thumbnail[0].url, 'description': e.description.text, 'content': e.content.text, 'updated': e.updated.text, }] #'published': e.published.text }] page_template_values.update( logo = data.logo.text, total = data.total_results.text ) # логотипчик и количество роликов elif videoid != 'none': # выбран конкретный ролик action = 'video' #player = 'yt' # для плеера с youtube player = 'my' # для своего плеера entrys = { 'geo': data.geo, # строим dict с характеристиками видеоролика 'title': data.title.text, 'summary': data.summary, 'description': data.media.description.text, 'player': data.media.player.url, 'duration': data.media.duration.seconds, 'video': data.GetSwfUrl() } page_template_values.update( playersource = player ) # задаем вид плеера (наш или ютубовский) page_template_values.update( action = action, entrys = entrys ) # задаем действие и содержание if action != 'error': page_template_values.update( author = data.author[0].name.text, # параметры шаблона, общие для плейлистов, списков видео и роликов title = data.title.text, updated = data.updated.text ) pagegen.generatePage(self, 'video', page_template_values) # выводим страницу
Python
#!/usr/bin/python # # Copyright (C) 2007, 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. import cgi import math import random import re import time import types import urllib import atom.http_interface import atom.token_store import atom.url import gdata.oauth as oauth import gdata.oauth.rsa as oauth_rsa import gdata.tlslite.utils.keyfactory as keyfactory import gdata.tlslite.utils.cryptomath as cryptomath __author__ = 'api.jscudder (Jeff Scudder)' PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth=' AUTHSUB_AUTH_LABEL = 'AuthSub token=' """This module provides functions and objects used with Google authentication. Details on Google authorization mechanisms used with the Google Data APIs can be found here: http://code.google.com/apis/gdata/auth.html http://code.google.com/apis/accounts/ The essential functions are the following. Related to ClientLogin: generate_client_login_request_body: Constructs the body of an HTTP request to obtain a ClientLogin token for a specific service. extract_client_login_token: Creates a ClientLoginToken with the token from a success response to a ClientLogin request. get_captcha_challenge: If the server responded to the ClientLogin request with a CAPTCHA challenge, this method extracts the CAPTCHA URL and identifying CAPTCHA token. Related to AuthSub: generate_auth_sub_url: Constructs a full URL for a AuthSub request. The user's browser must be sent to this Google Accounts URL and redirected back to the app to obtain the AuthSub token. extract_auth_sub_token_from_url: Once the user's browser has been redirected back to the web app, use this function to create an AuthSubToken with the correct authorization token and scope. token_from_http_body: Extracts the AuthSubToken value string from the server's response to an AuthSub session token upgrade request. """ def generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): """Creates the body of the autentication request See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request for more details. Args: email: str password: str service: str source: str account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid values are 'GOOGLE' and 'HOSTED' captcha_token: str (optional) captcha_response: str (optional) Returns: The HTTP body to send in a request for a client login token. """ # Create a POST body containing the user's credentials. request_fields = {'Email': email, 'Passwd': password, 'accountType': account_type, 'service': service, 'source': source} if captcha_token and captcha_response: # Send the captcha token and response as part of the POST body if the # user is responding to a captch challenge. request_fields['logintoken'] = captcha_token request_fields['logincaptcha'] = captcha_response return urllib.urlencode(request_fields) GenerateClientLoginRequestBody = generate_client_login_request_body def GenerateClientLoginAuthToken(http_body): """Returns the token value to use in Authorization headers. Reads the token from the server's response to a Client Login request and creates header value to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The value half of an Authorization header. """ token = get_client_login_token(http_body) if token: return 'GoogleLogin auth=%s' % token return None def get_client_login_token(http_body): """Returns the token value for a ClientLoginToken. Reads the token from the server's response to a Client Login request and creates the token value string to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The token value string for a ClientLoginToken. """ for response_line in http_body.splitlines(): if response_line.startswith('Auth='): # Strip off the leading Auth= and return the Authorization value. return response_line[5:] return None def extract_client_login_token(http_body, scopes): """Parses the server's response and returns a ClientLoginToken. Args: http_body: str The body of the server's HTTP response to a Client Login request. It is assumed that the login request was successful. scopes: list containing atom.url.Urls or strs. The scopes list contains all of the partial URLs under which the client login token is valid. For example, if scopes contains ['http://example.com/foo'] then the client login token would be valid for http://example.com/foo/bar/baz Returns: A ClientLoginToken which is valid for the specified scopes. """ token_string = get_client_login_token(http_body) token = ClientLoginToken(scopes=scopes) token.set_token_string(token_string) return token def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str This function returns a full URL for viewing the challenge image which is built from the server's response. This base_url is used as the beginning of the URL because the server only provides the end of the URL. For example the server provides 'Captcha?ctoken=Hi...N' and the URL for the image is 'http://www.google.com/accounts/Captcha?ctoken=Hi...N' Returns: A dictionary containing the information needed to repond to the CAPTCHA challenge, the image URL and the ID token of the challenge. The dictionary is in the form: {'token': string identifying the CAPTCHA image, 'url': string containing the URL of the image} Returns None if there was no CAPTCHA challenge in the response. """ contains_captcha_challenge = False captcha_parameters = {} for response_line in http_body.splitlines(): if response_line.startswith('Error=CaptchaRequired'): contains_captcha_challenge = True elif response_line.startswith('CaptchaToken='): # Strip off the leading CaptchaToken= captcha_parameters['token'] = response_line[13:] elif response_line.startswith('CaptchaUrl='): captcha_parameters['url'] = '%s%s' % (captcha_base_url, response_line[11:]) if contains_captcha_challenge: return captcha_parameters else: return None GetCaptchaChallenge = get_captcha_challenge def GenerateOAuthRequestTokenUrl( oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): """Generate a URL at which a request for OAuth request token is to be sent. Args: oauth_input_params: OAuthInputParams OAuth input parameters. scopes: list of strings The URLs of the services to be accessed. request_token_url: string The beginning of the request token URL. This is normally 'https://www.google.com/accounts/OAuthGetRequestToken' or '/accounts/OAuthGetRequestToken' extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} Returns: atom.url.Url OAuth request token URL. """ scopes_string = ' '.join([str(scope) for scope in scopes]) parameters = {'scope': scopes_string} if extra_parameters: parameters.update(extra_parameters) oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), http_url=request_token_url, parameters=parameters) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), None) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAuthorizationUrl( request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken OAuth request token. authorization_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthAuthorizeToken' or '/accounts/OAuthAuthorizeToken' callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. Returns: atom.url.Url OAuth authorization URL. """ scopes = request_token.scopes if isinstance(scopes, list): scopes = ' '.join(scopes) if include_scopes_in_callback and callback_url: if callback_url.find('?') > -1: callback_url += '&' else: callback_url += '?' callback_url += urllib.urlencode({scopes_param_prefix:scopes}) oauth_token = oauth.OAuthToken(request_token.key, request_token.secret) oauth_request = oauth.OAuthRequest.from_token_and_callback( token=oauth_token, callback=callback_url, http_url=authorization_url, parameters=extra_params) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAccessTokenUrl( authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0'): """Generates URL at which user will login to authorize the request token. Args: authorized_request_token: gdata.auth.OAuthToken OAuth authorized request token. oauth_input_params: OAuthInputParams OAuth input parameters. access_token_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthGetAccessToken' or '/accounts/OAuthGetAccessToken' oauth_version: str (default='1.0') oauth_version parameter. Returns: atom.url.Url OAuth access token URL. """ oauth_token = oauth.OAuthToken(authorized_request_token.key, authorized_request_token.secret) oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), token=oauth_token, http_url=access_token_url, parameters={'oauth_version': oauth_version}) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), oauth_token) return atom.url.parse_url(oauth_request.to_url()) def GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/AuthForWebApps.html Args: request_url: str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' next: string The URL user will be sent to after logging in. scope: string The URL of the service to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. domain: str (optional) The Google Apps domain for this account. If this is not a Google Apps account, use 'default' which is the default value. """ # Translate True/False values for parameters into numeric values acceoted # by the AuthSub service. if secure: secure = 1 else: secure = 0 if session: session = 1 else: session = 0 request_params = urllib.urlencode({'next': next, 'scope': scope, 'secure': secure, 'session': session, 'hd': domain}) if request_url.find('?') == -1: return '%s?%s' % (request_url, request_params) else: # The request URL already contained url parameters so we should add # the parameters using the & seperator return '%s&%s' % (request_url, request_params) def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): """Constructs a URL string for requesting a multiscope AuthSub token. The generated token will contain a URL parameter to pass along the requested scopes to the next URL. When the Google Accounts page redirects the broswser to the 'next' URL, it appends the single use AuthSub token value to the URL as a URL parameter with the key 'token'. However, the information about which scopes were requested is not included by Google Accounts. This method adds the scopes to the next URL before making the request so that the redirect will be sent to a page, and both the token value and the list of scopes can be extracted from the request URL. Args: next: atom.url.URL or string The URL user will be sent to after authorizing this web application to access their data. scopes: list containint strings The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. request_url: atom.url.Url or str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' domain: The domain which the account is part of. This is used for Google Apps accounts, the default value is 'default' which means that the requested account is a Google Account (@gmail.com for example) scopes_param_prefix: str (optional) The requested scopes are added as a URL parameter to the next URL so that the page at the 'next' URL can extract the token value and the valid scopes from the URL. The key for the URL parameter defaults to 'auth_sub_scopes' Returns: An atom.url.Url which the user's browser should be directed to in order to authorize this application to access their information. """ if isinstance(next, (str, unicode)): next = atom.url.parse_url(next) scopes_string = ' '.join([str(scope) for scope in scopes]) next.params[scopes_param_prefix] = scopes_string if isinstance(request_url, (str, unicode)): request_url = atom.url.parse_url(request_url) request_url.params['next'] = str(next) request_url.params['scope'] = scopes_string if session: request_url.params['session'] = 1 else: request_url.params['session'] = 0 if secure: request_url.params['secure'] = 1 else: request_url.params['secure'] = 0 request_url.params['hd'] = domain return request_url def AuthSubTokenFromUrl(url): """Extracts the AuthSub token from the URL. Used after the AuthSub redirect has sent the user to the 'next' page and appended the token to the URL. This function returns the value to be used in the Authorization header. Args: url: str The URL of the current page which contains the AuthSub token as a URL parameter. """ token = TokenFromUrl(url) if token: return 'AuthSub token=%s' % token return None def TokenFromUrl(url): """Extracts the AuthSub token from the URL. Returns the raw token value. Args: url: str The URL or the query portion of the URL string (after the ?) of the current page which contains the AuthSub token as a URL parameter. """ if url.find('?') > -1: query_params = url.split('?')[1] else: query_params = url for pair in query_params.split('&'): if pair.startswith('token='): return pair[6:] return None def extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): """Creates an AuthSubToken and sets the token value and scopes from the URL. After the Google Accounts AuthSub pages redirect the user's broswer back to the web application (using the 'next' URL from the request) the web app must extract the token from the current page's URL. The token is provided as a URL parameter named 'token' and if generate_auth_sub_url was used to create the request, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An AuthSubToken with the token value from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the AuthSubToken defaults to being valid for no scopes. If there was no 'token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_value = url.params['token'] if rsa_key: token = SecureAuthSubToken(rsa_key, scopes=scopes) else: token = AuthSubToken(scopes=scopes) token.set_token_string(token_value) return token def AuthSubTokenFromHttpBody(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The header value to use for Authorization which contains the AuthSub token. """ token_value = token_from_http_body(http_body) if token_value: return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value) return None def token_from_http_body(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The raw token value to use in an AuthSubToken object. """ for response_line in http_body.splitlines(): if response_line.startswith('Token='): # Strip off Token= and return the token value string. return response_line[6:] return None TokenFromHttpBody = token_from_http_body def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): """Creates an OAuthToken and sets token key and scopes (if present) from URL. After the Google Accounts OAuth pages redirect the user's broswer back to the web application (using the 'callback' URL from the request) the web app can extract the token from the current page's URL. The token is same as the request token, but it is either authorized (if user grants access) or unauthorized (if user denies access). The token is provided as a URL parameter named 'oauth_token' and if it was chosen to use GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An OAuthToken with the token key from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the OAuthToken defaults to being valid for no scopes. If there was no 'oauth_token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'oauth_token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_key = url.params['oauth_token'] token = OAuthToken(key=token_key, scopes=scopes) return token def OAuthTokenFromHttpBody(http_body): """Parses the HTTP response body and returns an OAuth token. The returned OAuth token will just have key and secret parameters set. It won't have any knowledge about the scopes or oauth_input_params. It is your responsibility to make it aware of the remaining parameters. Returns: OAuthToken OAuth token. """ token = oauth.OAuthToken.from_string(http_body) oauth_token = OAuthToken(key=token.key, secret=token.secret) return oauth_token class OAuthSignatureMethod(object): """Holds valid OAuth signature methods. RSA_SHA1: Class to build signature according to RSA-SHA1 algorithm. HMAC_SHA1: Class to build signature according to HMAC-SHA1 algorithm. """ HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1 class RSA_SHA1(oauth_rsa.OAuthSignatureMethod_RSA_SHA1): """Provides implementation for abstract methods to return RSA certs.""" def __init__(self, private_key, public_cert): self.private_key = private_key self.public_cert = public_cert def _fetch_public_cert(self, unused_oauth_request): return self.public_cert def _fetch_private_cert(self, unused_oauth_request): return self.private_key class OAuthInputParams(object): """Stores OAuth input parameters. This class is a store for OAuth input parameters viz. consumer key and secret, signature method and RSA key. """ def __init__(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None): """Initializes object with parameters required for using OAuth mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. """ if signature_method == OAuthSignatureMethod.RSA_SHA1: self._signature_method = signature_method(rsa_key, None) else: self._signature_method = signature_method() self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) def GetSignatureMethod(self): """Gets the OAuth signature method. Returns: object of supertype <oauth.oauth.OAuthSignatureMethod> """ return self._signature_method def GetConsumer(self): """Gets the OAuth consumer. Returns: object of type <oauth.oauth.Consumer> """ return self._consumer class ClientLoginToken(atom.http_interface.GenericToken): """Stores the Authorization header in auth_header and adds to requests. This token will add it's Authorization header to an HTTP request as it is made. Ths token class is simple but some Token classes must calculate portions of the Authorization header based on the request being made, which is why the token is responsible for making requests via an http_client parameter. Args: auth_header: str The value for the Authorization header. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, auth_header=None, scopes=None): self.auth_header = auth_header self.scopes = scopes or [] def __str__(self): return self.auth_header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if headers is None: headers = {'Authorization':self.auth_header} else: headers['Authorization'] = self.auth_header return http_client.request(operation, url, data=data, headers=headers) def get_token_string(self): """Removes PROGRAMMATIC_AUTH_LABEL to give just the token value.""" return self.auth_header[len(PROGRAMMATIC_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string) def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class AuthSubToken(ClientLoginToken): def get_token_string(self): """Removes AUTHSUB_AUTH_LABEL to give just the token value.""" return self.auth_header[len(AUTHSUB_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (AUTHSUB_AUTH_LABEL, token_string) class OAuthToken(atom.http_interface.GenericToken): """Stores the token key, token secret and scopes for which token is valid. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the OAuth signature to be added to the authorization header is dependent on the request parameters. Attributes: key: str The value for the OAuth token i.e. token key. secret: str The value for the OAuth token secret. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' oauth_input_params: OAuthInputParams OAuth input parameters. """ def __init__(self, key=None, secret=None, scopes=None, oauth_input_params=None): self.key = key self.secret = secret self.scopes = scopes or [] self.oauth_input_params = oauth_input_params def __str__(self): return self.get_token_string() def get_token_string(self): """Returns the token string. The token string returned is of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. Returns: A token string of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. If self.secret is absent, it just returns oauth_token=[0]. If self.key is absent, it just returns oauth_token_secret=[1]. If both are absent, it returns None. """ if self.key and self.secret: return urllib.urlencode({'oauth_token': self.key, 'oauth_token_secret': self.secret}) elif self.key: return 'oauth_token=%s' % self.key elif self.secret: return 'oauth_token_secret=%s' % self.secret else: return None def set_token_string(self, token_string): """Sets the token key and secret from the token string. Args: token_string: str Token string of form oauth_token=[0]&oauth_token_secret=[1]. If oauth_token is not present, self.key will be None. If oauth_token_secret is not present, self.secret will be None. """ token_params = cgi.parse_qs(token_string, keep_blank_values=False) if 'oauth_token' in token_params: self.key = token_params['oauth_token'][0] if 'oauth_token_secret' in token_params: self.secret = token_params['oauth_token_secret'][0] def GetAuthHeader(self, http_method, http_url, realm=''): """Get the authentication header. Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. realm: string (default='') realm parameter to be included in the authorization header. Returns: dict Header to be sent with every subsequent request after authentication. """ if isinstance(http_url, types.StringTypes): http_url = atom.url.parse_url(http_url) header = None token = None if self.key or self.secret: token = oauth.OAuthToken(self.key, self.secret) oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.oauth_input_params.GetConsumer(), token=token, http_url=str(http_url), http_method=http_method, parameters=http_url.params) oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(), self.oauth_input_params.GetConsumer(), token) header = oauth_request.to_header(realm=realm) header['Authorization'] = header['Authorization'].replace('+', '%2B') return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers) def valid_for_scope(self, url): if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class SecureAuthSubToken(AuthSubToken): """Stores the rsa private key, token, and scopes for the secure AuthSub token. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the secure AuthSub signature to be added to the authorization header is dependent on the request parameters. Attributes: rsa_key: string The RSA private key in PEM format that the token will use to sign requests token_string: string (optional) The value for the AuthSub token. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, rsa_key, token_string=None, scopes=None): self.rsa_key = keyfactory.parsePEMKey(rsa_key) self.token_string = token_string or '' self.scopes = scopes or [] def __str__(self): return self.get_token_string() def get_token_string(self): return str(self.token_string) def set_token_string(self, token_string): self.token_string = token_string def GetAuthHeader(self, http_method, http_url): """Generates the Authorization header. The form of the secure AuthSub Authorization header is Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig" and data represents a string in the form data = http_method http_url timestamp nonce Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. Returns: dict Header to be sent with every subsequent request after authentication. """ timestamp = int(math.floor(time.time())) nonce = '%lu' % random.randrange(1, 2**64) data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce) sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data)) header = {'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' % (AUTHSUB_AUTH_LABEL, self.token_string, data, sig)} return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers)
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.exif, implementing the exif namespace in gdata # # $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions copyright 2007 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. """This module maps elements from the {EXIF} namespace[1] to GData objects. These elements describe image data, using exif attributes[2]. Picasa Web Albums uses the exif namespace to represent Exif data encoded in a photo [3]. Picasa Web Albums uses the following exif elements: exif:distance exif:exposure exif:flash exif:focallength exif:fstop exif:imageUniqueID exif:iso exif:make exif:model exif:tags exif:time [1]: http://schemas.google.com/photos/exif/2007. [2]: http://en.wikipedia.org/wiki/Exif [3]: http://code.google.com/apis/picasaweb/reference.html#exif_reference """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007' class ExifBaseElement(atom.AtomBase): """Base class for elements in the EXIF_NAMESPACE (%s). To add new elements, you only need to add the element tag name to self._tag """ % EXIF_NAMESPACE _tag = '' _namespace = EXIF_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Distance(ExifBaseElement): "(float) The distance to the subject, e.g. 0.0" _tag = 'distance' def DistanceFromString(xml_string): return atom.CreateClassFromXMLString(Distance, xml_string) class Exposure(ExifBaseElement): "(float) The exposure time used, e.g. 0.025 or 8.0E4" _tag = 'exposure' def ExposureFromString(xml_string): return atom.CreateClassFromXMLString(Exposure, xml_string) class Flash(ExifBaseElement): """(string) Boolean value indicating whether the flash was used. The .text attribute will either be `true' or `false' As a convenience, this object's .bool method will return what you want, so you can say: flash_used = bool(Flash) """ _tag = 'flash' def __bool__(self): if self.text.lower() in ('true','false'): return self.text.lower() == 'true' def FlashFromString(xml_string): return atom.CreateClassFromXMLString(Flash, xml_string) class Focallength(ExifBaseElement): "(float) The focal length used, e.g. 23.7" _tag = 'focallength' def FocallengthFromString(xml_string): return atom.CreateClassFromXMLString(Focallength, xml_string) class Fstop(ExifBaseElement): "(float) The fstop value used, e.g. 5.0" _tag = 'fstop' def FstopFromString(xml_string): return atom.CreateClassFromXMLString(Fstop, xml_string) class ImageUniqueID(ExifBaseElement): "(string) The unique image ID for the photo. Generated by Google Photo servers" _tag = 'imageUniqueID' def ImageUniqueIDFromString(xml_string): return atom.CreateClassFromXMLString(ImageUniqueID, xml_string) class Iso(ExifBaseElement): "(int) The iso equivalent value used, e.g. 200" _tag = 'iso' def IsoFromString(xml_string): return atom.CreateClassFromXMLString(Iso, xml_string) class Make(ExifBaseElement): "(string) The make of the camera used, e.g. Fictitious Camera Company" _tag = 'make' def MakeFromString(xml_string): return atom.CreateClassFromXMLString(Make, xml_string) class Model(ExifBaseElement): "(string) The model of the camera used,e.g AMAZING-100D" _tag = 'model' def ModelFromString(xml_string): return atom.CreateClassFromXMLString(Model, xml_string) class Time(ExifBaseElement): """(int) The date/time the photo was taken, e.g. 1180294337000. Represented as the number of milliseconds since January 1st, 1970. The value of this element will always be identical to the value of the <gphoto:timestamp>. Look at this object's .isoformat() for a human friendly datetime string: photo_epoch = Time.text # 1180294337000 photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z' Alternatively: photo_datetime = Time.datetime() # (requires python >= 2.3) """ _tag = 'time' def isoformat(self): """(string) Return the timestamp as a ISO 8601 formatted string, e.g. '2007-05-27T19:32:17.000Z' """ import time epoch = float(self.text)/1000 return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch)) def datetime(self): """(datetime.datetime) Return the timestamp as a datetime.datetime object Requires python 2.3 """ import datetime epoch = float(self.text)/1000 return datetime.datetime.fromtimestamp(epoch) def TimeFromString(xml_string): return atom.CreateClassFromXMLString(Time, xml_string) class Tags(ExifBaseElement): """The container for all exif elements. The <exif:tags> element can appear as a child of a photo entry. """ _tag = 'tags' _children = atom.AtomBase._children.copy() _children['{%s}fstop' % EXIF_NAMESPACE] = ('fstop', Fstop) _children['{%s}make' % EXIF_NAMESPACE] = ('make', Make) _children['{%s}model' % EXIF_NAMESPACE] = ('model', Model) _children['{%s}distance' % EXIF_NAMESPACE] = ('distance', Distance) _children['{%s}exposure' % EXIF_NAMESPACE] = ('exposure', Exposure) _children['{%s}flash' % EXIF_NAMESPACE] = ('flash', Flash) _children['{%s}focallength' % EXIF_NAMESPACE] = ('focallength', Focallength) _children['{%s}iso' % EXIF_NAMESPACE] = ('iso', Iso) _children['{%s}time' % EXIF_NAMESPACE] = ('time', Time) _children['{%s}imageUniqueID' % EXIF_NAMESPACE] = ('imageUniqueID', ImageUniqueID) def __init__(self, extension_elements=None, extension_attributes=None, text=None): ExifBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.fstop=None self.make=None self.model=None self.distance=None self.exposure=None self.flash=None self.focallength=None self.iso=None self.time=None self.imageUniqueID=None def TagsFromString(xml_string): return atom.CreateClassFromXMLString(Tags, xml_string)
Python
#!/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)
Python
#!/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. """YouTubeService extends GDataService to streamline YouTube operations. YouTubeService: Provides methods to perform CRUD operations on YouTube feeds. Extends GDataService. """ __author__ = ('api.stephaniel@gmail.com (Stephanie Liu), ' 'api.jhartmann@gmail.com (Jochen Hartmann)') try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import os import atom import gdata import gdata.service import gdata.youtube YOUTUBE_SERVER = 'gdata.youtube.com' YOUTUBE_SERVICE = 'youtube' 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_URI = 'http://uploads.gdata.youtube.com/feeds/api/users' YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken' YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos' YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users' YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists' YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds' YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated') YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_viewed') YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'recently_featured') YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'watch_on_mobile') YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_favorites') YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_recent') YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_discussed') YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_linked') YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_responded') YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas' YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA, 'complaint-reasons.cat') YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA, 'subscriptiontypes.cat') YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS', 'RIGHTS', 'SPAM') YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected') YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family') UNKOWN_ERROR = 1000 YOUTUBE_BAD_REQUEST = 400 YOUTUBE_CONFLICT = 409 YOUTUBE_INTERNAL_SERVER_ERROR = 500 YOUTUBE_INVALID_ARGUMENT = 601 YOUTUBE_INVALID_CONTENT_TYPE = 602 YOUTUBE_NOT_A_VIDEO = 603 YOUTUBE_INVALID_KIND = 604 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 YouTubeService(gdata.service.GDataService): """Client for the YouTube service. Performs all documented Google Data YouTube API functions, such as inserting, updating and deleting videos, comments, playlist, subscriptions etc. YouTube Service requires authentication for any write, update or delete actions. Attributes: email: An optional string identifying the user. Required only for authenticated actions. password: An optional string identifying the user's password. source: An optional string identifying the name of your application. server: An optional address of the YouTube API server. gdata.youtube.com is provided as the default value. additional_headers: An optional dictionary containing additional headers to be passed along with each request. Use to store developer key. client_id: An optional string identifying your application, required for authenticated requests, along with a developer key. developer_key: An optional string value. Register your application at http://code.google.com/apis/youtube/dashboard to obtain a (free) key. """ def __init__(self, email=None, password=None, source=None, server=YOUTUBE_SERVER, additional_headers=None, client_id=None, developer_key=None, **kwargs): """Creates a client for the YouTube service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'gdata.youtube.com'. client_id: string (optional) Identifies your application, required for authenticated requests, along with a developer key. developer_key: string (optional) Register your application at http://code.google.com/apis/youtube/dashboard to obtain a (free) key. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ self.additional_headers = {} if client_id is not None and developer_key is not None: self.additional_headers = {'X-Gdata-Client': client_id, 'X-GData-Key': 'key=%s' % developer_key} elif developer_key and not client_id: raise YouTubeError('You must also specify the clientId') gdata.service.GDataService.__init__( self, email=email, password=password, service=YOUTUBE_SERVICE, source=source, server=server, additional_headers=additional_headers, **kwargs) self.auth_service_url = YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL def GetYouTubeVideoFeed(self, uri): """Retrieve a YouTubeVideoFeed. Args: uri: A string representing the URI of the feed that is to be retrieved. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString) def GetYouTubeVideoEntry(self, uri=None, video_id=None): """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 GetYouTubeVideoEntry() method') elif video_id and not uri: uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id) return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def GetYouTubeContactFeed(self, uri=None, username='default'): """Retrieve a YouTubeContactFeed. Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the contact feed that is to be retrieved. username: An optional string representing the username. Defaults to the currently authenticated user. Returns: A YouTubeContactFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeContactFeed() method. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts') return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString) def GetYouTubeContactEntry(self, uri): """Retrieve a YouTubeContactEntry. Args: uri: A string representing the URI of the contact entry that is to be retrieved. Returns: A YouTubeContactEntry if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString) def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None): """Retrieve a YouTubeVideoCommentFeed. Either a uri or a video_id must be provided. Args: uri: An optional string representing the URI of the comment feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the comment feed. Returns: A YouTubeVideoCommentFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoCommentFeed() 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 GetYouTubeVideoCommentFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments') return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString) def GetYouTubeVideoCommentEntry(self, uri): """Retrieve a YouTubeVideoCommentEntry. Args: uri: A string representing the URI of the comment entry that is to be retrieved. Returns: A YouTubeCommentEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString) def GetYouTubeUserFeed(self, uri=None, username=None): """Retrieve a YouTubeUserFeed. Either a uri or a username must be provided. 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(uri, converter=gdata.youtube.YouTubeUserFeedFromString) def GetYouTubeUserEntry(self, uri=None, username=None): """Retrieve a YouTubeUserEntry. Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the user entry that is to be retrieved. username: An optional string representing the username. Returns: A YouTubeUserEntry if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeUserEntry() method. """ if uri is None and username is None: raise YouTubeError('You must provide at least a uri or a username ' 'to the GetYouTubeUserEntry() method') elif username and not uri: uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username) return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString) def GetYouTubePlaylistFeed(self, uri=None, username='default'): """Retrieve a YouTubePlaylistFeed (a feed of playlists for a user). Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the playlist feed that is to be retrieved. username: An optional string representing the username. Defaults to the currently authenticated user. Returns: A YouTubePlaylistFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubePlaylistFeed() method. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists') return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString) def GetYouTubePlaylistEntry(self, uri): """Retrieve a YouTubePlaylistEntry. Args: uri: A string representing the URI of the playlist feed that is to be retrieved. Returns: A YouTubePlaylistEntry if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None): """Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist). Either a uri or a playlist_id must be provided. Args: uri: An optional string representing the URI of the playlist video feed that is to be retrieved. playlist_id: An optional string representing the Id of the playlist whose playlist video feed is to be retrieved. Returns: A YouTubePlaylistVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a playlist_id to the GetYouTubePlaylistVideoFeed() method. """ if uri is None and playlist_id is None: raise YouTubeError('You must provide at least a uri or a playlist_id ' 'to the GetYouTubePlaylistVideoFeed() method') elif playlist_id and not uri: uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id) return self.Get( uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString) def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None): """Retrieve a YouTubeVideoResponseFeed. Either a uri or a playlist_id must be provided. Args: uri: An optional string representing the URI of the video response feed that is to be retrieved. video_id: An optional string representing the ID of the video whose response feed is to be retrieved. Returns: A YouTubeVideoResponseFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoResponseFeed() 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 GetYouTubeVideoResponseFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses') return self.Get( uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString) def GetYouTubeVideoResponseEntry(self, uri): """Retrieve a YouTubeVideoResponseEntry. Args: uri: A string representing the URI of the video response entry that is to be retrieved. Returns: A YouTubeVideoResponseEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString) def GetYouTubeSubscriptionFeed(self, uri=None, username='default'): """Retrieve a YouTubeSubscriptionFeed. Either the uri of the feed or a username must be provided. Args: uri: An optional string representing the URI of the feed that is to be retrieved. username: An optional string representing the username whose subscription feed is to be retrieved. Defaults to the currently authenticted user. Returns: A YouTubeVideoSubscriptionFeed if successfully retrieved. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions') return self.Get( uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString) def GetYouTubeSubscriptionEntry(self, uri): """Retrieve a YouTubeSubscriptionEntry. Args: uri: A string representing the URI of the entry that is to be retrieved. Returns: A YouTubeVideoSubscriptionEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None): """Retrieve a YouTubeRelatedVideoFeed. Either a uri for the feed or a video_id is required. Args: uri: An optional string representing the URI of the feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the related video feed. Returns: A YouTubeRelatedVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeRelatedVideoFeed() 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 GetYouTubeRelatedVideoFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related') return self.Get( uri, converter=gdata.youtube.YouTubeVideoFeedFromString) def GetTopRatedVideoFeed(self): """Retrieve the 'top_rated' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI) def GetMostViewedVideoFeed(self): """Retrieve the 'most_viewed' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI) def GetRecentlyFeaturedVideoFeed(self): """Retrieve the 'recently_featured' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI) def GetWatchOnMobileVideoFeed(self): """Retrieve the 'watch_on_mobile' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI) def GetTopFavoritesVideoFeed(self): """Retrieve the 'top_favorites' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI) def GetMostRecentVideoFeed(self): """Retrieve the 'most_recent' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI) def GetMostDiscussedVideoFeed(self): """Retrieve the 'most_discussed' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI) def GetMostLinkedVideoFeed(self): """Retrieve the 'most_linked' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI) def GetMostRespondedVideoFeed(self): """Retrieve the 'most_responded' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI) def GetUserFavoritesFeed(self, username='default'): """Retrieve the favorites feed for a given user. Args: username: An optional string representing the username whose favorites feed is to be retrieved. Defaults to the currently authenticated user. Returns: A YouTubeVideoFeed if successfully retrieved. """ favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.GetYouTubeVideoFeed(favorites_feed_uri) def InsertVideoEntry(self, video_entry, filename_or_handle, youtube_username='default', content_type='video/quicktime'): """Upload a new video to YouTube using the direct upload mechanism. Needs authentication. Args: video_entry: The YouTubeVideoEntry to upload. filename_or_handle: A file-like object or file name where the video will be read from. youtube_username: An optional string representing the username into whose account this video is to be uploaded to. Defaults to the currently authenticated user. content_type: An optional string representing internet media type (a.k.a. mime type) of the media object. Currently the YouTube API supports these types: o video/mpeg o video/quicktime o video/x-msvideo o video/mp4 o video/x-flv Returns: The newly created YouTubeVideoEntry if successful. Raises: AssertionError: video_entry must be a gdata.youtube.VideoEntry instance. YouTubeError: An error occurred trying to read the video file provided. gdata.service.RequestError: An error occurred trying to upload the video to the API server. """ # We need to perform a series of checks on the video_entry and on the # file that we plan to upload, such as checking whether we have a valid # video_entry and that the file is the correct type and readable, prior # to performing the actual POST request. try: assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) except AssertionError: raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':'`video_entry` must be a gdata.youtube.VideoEntry instance', 'reason':'Found %s, not VideoEntry' % type(video_entry) }) majtype, mintype = content_type.split('/') try: assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % ['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]}) if (isinstance(filename_or_handle, (str, unicode)) and os.path.exists(filename_or_handle)): mediasource = gdata.MediaSource() mediasource.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'): import StringIO if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'video' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body': '`filename_or_handle` must be a path name or a file-like object', 'reason': ('Found %s, not path name or object ' 'with a .read() method' % type(filename_or_handle))}) upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username, 'uploads') self.additional_headers['Slug'] = mediasource.file_name # Using a nested try statement to retain Python 2.4 compatibility try: try: return self.Post(video_entry, uri=upload_uri, media_source=mediasource, converter=gdata.youtube.YouTubeVideoEntryFromString) except gdata.service.RequestError, e: raise YouTubeError(e.args[0]) finally: del(self.additional_headers['Slug']) def CheckUploadStatus(self, video_entry=None, video_id=None): """Check upload status on a recently uploaded video entry. Needs authentication. Either video_entry or video_id must be provided. Args: video_entry: An optional YouTubeVideoEntry whose upload status to check video_id: An optional string representing the ID of the uploaded video whose status is to be checked. Returns: A tuple containing (video_upload_state, detailed_message) or None if no status information is found. Raises: YouTubeError: You must provide at least a video_entry or a video_id to the CheckUploadStatus() method. """ if video_entry is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the CheckUploadStatus() method') elif video_id and not video_entry: video_entry = self.GetYouTubeVideoEntry(video_id=video_id) control = video_entry.control if control is not None: draft = control.draft if draft is not None: if draft.text == 'yes': yt_state = control.extension_elements[0] if yt_state is not None: state_value = yt_state.attributes['name'] message = '' if yt_state.text is not None: message = yt_state.text return (state_value, message) def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI): """Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry. Needs authentication. Args: video_entry: The YouTubeVideoEntry to upload (meta-data only). uri: An optional string representing the URI from where to fetch the token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI. Returns: A tuple containing the URL to which to post your video file, along with the youtube token that must be included with your upload in the form of: (post_url, youtube_token). """ try: response = self.Post(video_entry, uri) except gdata.service.RequestError, e: raise YouTubeError(e.args[0]) tree = ElementTree.fromstring(response) for child in tree: if child.tag == 'url': post_url = child.text elif child.tag == 'token': youtube_token = child.text return (post_url, youtube_token) def UpdateVideoEntry(self, video_entry): """Updates a video entry's meta-data. Needs authentication. Args: video_entry: The YouTubeVideoEntry to update, containing updated meta-data. Returns: An updated YouTubeVideoEntry on success or None. """ for link in video_entry.link: if link.rel == 'edit': edit_uri = link.href return self.Put(video_entry, uri=edit_uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def DeleteVideoEntry(self, video_entry): """Deletes a video entry. Needs authentication. Args: video_entry: The YouTubeVideoEntry to be deleted. Returns: True if entry was deleted successfully. """ for link in video_entry.link: if link.rel == 'edit': edit_uri = link.href return self.Delete(edit_uri) def AddRating(self, rating_value, video_entry): """Add a rating to a video entry. Needs authentication. Args: rating_value: The integer value for the rating (between 1 and 5). video_entry: The YouTubeVideoEntry to be rated. Returns: True if the rating was added successfully. Raises: YouTubeError: rating_value must be between 1 and 5 in AddRating(). """ if rating_value < 1 or rating_value > 5: raise YouTubeError('rating_value must be between 1 and 5 in AddRating()') entry = gdata.GDataEntry() rating = gdata.youtube.Rating(min='1', max='5') rating.extension_attributes['name'] = 'value' rating.extension_attributes['value'] = str(rating_value) entry.extension_elements.append(rating) for link in video_entry.link: if link.rel == YOUTUBE_RATING_LINK_REL: rating_uri = link.href return self.Post(entry, uri=rating_uri) def AddComment(self, comment_text, video_entry): """Add a comment to a video entry. Needs authentication. Note that each comment that is posted must contain the video entry that it is to be posted to. Args: comment_text: A string representing the text of the comment. video_entry: The YouTubeVideoEntry to be commented on. Returns: True if the comment was added successfully. """ content = atom.Content(text=comment_text) comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content) comment_post_uri = video_entry.comments.feed_link[0].href return self.Post(comment_entry, uri=comment_post_uri) def AddVideoResponse(self, video_id_to_respond_to, video_response): """Add a video response. Needs authentication. Args: video_id_to_respond_to: A string representing the ID of the video to be responded to. video_response: YouTubeVideoEntry to be posted as a response. Returns: True if video response was posted successfully. """ post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to, 'responses') return self.Post(video_response, uri=post_uri) def DeleteVideoResponse(self, video_id, response_video_id): """Delete a video response. Needs authentication. Args: video_id: A string representing the ID of video that contains the response. response_video_id: A string representing the ID of the video that was posted as a response. Returns: True if video response was deleted succcessfully. """ delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses', response_video_id) return self.Delete(delete_uri) def AddComplaint(self, complaint_text, complaint_term, video_id): """Add a complaint for a particular video entry. Needs authentication. Args: complaint_text: A string representing the complaint text. complaint_term: A string representing the complaint category term. video_id: A string representing the ID of YouTubeVideoEntry to complain about. Returns: True if posted successfully. Raises: YouTubeError: Your complaint_term is not valid. """ if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS: raise YouTubeError('Your complaint_term is not valid') content = atom.Content(text=complaint_text) category = atom.Category(term=complaint_term, scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME) complaint_entry = gdata.GDataEntry(content=content, category=[category]) post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints') return self.Post(complaint_entry, post_uri) def AddVideoEntryToFavorites(self, video_entry, username='default'): """Add a video entry to a users favorite feed. Needs authentication. Args: video_entry: The YouTubeVideoEntry to add. username: An optional string representing the username to whose favorite feed you wish to add the entry. Defaults to the currently authenticated user. Returns: The posted YouTubeVideoEntry if successfully posted. """ post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.Post(video_entry, post_uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def DeleteVideoEntryFromFavorites(self, video_id, username='default'): """Delete a video entry from the users favorite feed. Needs authentication. Args: video_id: A string representing the ID of the video that is to be removed username: An optional string representing the username of the user's favorite feed. Defaults to the currently authenticated user. Returns: True if entry was successfully deleted. """ edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites', video_id) return self.Delete(edit_link) def AddPlaylist(self, playlist_title, playlist_description, playlist_private=None): """Add a new playlist to the currently authenticated users account. Needs authentication. Args: playlist_title: A string representing the title for the new playlist. playlist_description: A string representing the description of the playlist. playlist_private: An optional boolean, set to True if the playlist is to be private. Returns: The YouTubePlaylistEntry if successfully posted. """ playlist_entry = gdata.youtube.YouTubePlaylistEntry( title=atom.Title(text=playlist_title), description=gdata.youtube.Description(text=playlist_description)) if playlist_private: playlist_entry.private = gdata.youtube.Private() playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default', 'playlists') return self.Post(playlist_entry, playlist_post_uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def UpdatePlaylist(self, playlist_id, new_playlist_title, new_playlist_description, playlist_private=None, username='default'): """Update a playlist with new meta-data. Needs authentication. Args: playlist_id: A string representing the ID of the playlist to be updated. new_playlist_title: A string representing a new title for the playlist. new_playlist_description: A string representing a new description for the playlist. playlist_private: An optional boolean, set to True if the playlist is to be private. username: An optional string representing the username whose playlist is to be updated. Defaults to the currently authenticated user. Returns: A YouTubePlaylistEntry if the update was successful. """ updated_playlist = gdata.youtube.YouTubePlaylistEntry( title=atom.Title(text=new_playlist_title), description=gdata.youtube.Description(text=new_playlist_description)) if playlist_private: updated_playlist.private = gdata.youtube.Private() playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username, playlist_id) return self.Put(updated_playlist, playlist_put_uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def DeletePlaylist(self, playlist_uri): """Delete a playlist from the currently authenticated users playlists. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist that is to be deleted. Returns: True if successfully deleted. """ return self.Delete(playlist_uri) def AddPlaylistVideoEntryToPlaylist( self, playlist_uri, video_id, custom_video_title=None, custom_video_description=None): """Add a video entry to a playlist, optionally providing a custom title and description. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist to which this video entry is to be added. video_id: A string representing the ID of the video entry to add. custom_video_title: An optional string representing a custom title for the video (only shown on the playlist). custom_video_description: An optional string representing a custom description for the video (only shown on the playlist). Returns: A YouTubePlaylistVideoEntry if successfully posted. """ playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry( atom_id=atom.Id(text=video_id)) if custom_video_title: playlist_video_entry.title = atom.Title(text=custom_video_title) if custom_video_description: playlist_video_entry.description = gdata.youtube.Description( text=custom_video_description) return self.Post(playlist_video_entry, playlist_uri, converter=gdata.youtube.YouTubePlaylistVideoEntryFromString) def UpdatePlaylistVideoEntryMetaData( self, playlist_uri, playlist_entry_id, new_video_title, new_video_description, new_video_position): """Update the meta data for a YouTubePlaylistVideoEntry. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist that contains the entry to be updated. playlist_entry_id: A string representing the ID of the entry to be updated. new_video_title: A string representing the new title for the video entry. new_video_description: A string representing the new description for the video entry. new_video_position: An integer representing the new position on the playlist for the video. Returns: A YouTubePlaylistVideoEntry if the update was successful. """ playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry( title=atom.Title(text=new_video_title), description=gdata.youtube.Description(text=new_video_description), position=gdata.youtube.Position(text=str(new_video_position))) playlist_put_uri = playlist_uri + '/' + playlist_entry_id return self.Put(playlist_video_entry, playlist_put_uri, converter=gdata.youtube.YouTubePlaylistVideoEntryFromString) def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id): """Delete a playlist video entry from a playlist. Needs authentication. Args: playlist_uri: A URI representing the playlist from which the playlist video entry is to be removed from. playlist_video_entry_id: A string representing id of the playlist video entry that is to be removed. Returns: True if entry was successfully deleted. """ delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id) return self.Delete(delete_uri) def AddSubscriptionToChannel(self, username_to_subscribe_to, my_username = 'default'): """Add a new channel subscription to the currently authenticated users account. Needs authentication. Args: username_to_subscribe_to: A string representing the username of the channel to which we want to subscribe to. my_username: An optional string representing the name of the user which we want to subscribe. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successfully posted. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='channel') subscription_username = gdata.youtube.Username( text=username_to_subscribe_to) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, username=subscription_username) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def AddSubscriptionToFavorites(self, username, my_username = 'default'): """Add a new subscription to a users favorites to the currently authenticated user's account. Needs authentication Args: username: A string representing the username of the user's favorite feed to subscribe to. my_username: An optional string representing the username of the user that is to be subscribed. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successful. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='favorites') subscription_username = gdata.youtube.Username(text=username) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, username=subscription_username) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def AddSubscriptionToQuery(self, query, my_username = 'default'): """Add a new subscription to a specific keyword query to the currently authenticated user's account. Needs authentication Args: query: A string representing the keyword query to subscribe to. my_username: An optional string representing the username of the user that is to be subscribed. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successful. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='query') subscription_query_string = gdata.youtube.QueryString(text=query) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, query_string=subscription_query_string) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def DeleteSubscription(self, subscription_uri): """Delete a subscription from the currently authenticated user's account. Needs authentication. Args: subscription_uri: A string representing the URI of the subscription that is to be deleted. Returns: True if deleted successfully. """ return self.Delete(subscription_uri) def AddContact(self, contact_username, my_username='default'): """Add a new contact to the currently authenticated user's contact feed. Needs authentication. Args: contact_username: A string representing the username of the contact that you wish to add. my_username: An optional string representing the username to whose contact the new contact is to be added. Returns: A YouTubeContactEntry if added successfully. """ contact_category = atom.Category( scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat', term = 'Friends') contact_username = gdata.youtube.Username(text=contact_username) contact_entry = gdata.youtube.YouTubeContactEntry( category=contact_category, username=contact_username) contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts') return self.Post(contact_entry, contact_post_uri, converter=gdata.youtube.YouTubeContactEntryFromString) def UpdateContact(self, contact_username, new_contact_status, new_contact_category, my_username='default'): """Update a contact, providing a new status and a new category. Needs authentication. Args: contact_username: A string representing the username of the contact that is to be updated. new_contact_status: A string representing the new status of the contact. This can either be set to 'accepted' or 'rejected'. new_contact_category: A string representing the new category for the contact, either 'Friends' or 'Family'. my_username: An optional string representing the username of the user whose contact feed we are modifying. Defaults to the currently authenticated user. Returns: A YouTubeContactEntry if updated succesfully. Raises: YouTubeError: New contact status must be within the accepted values. Or new contact category must be within the accepted categories. """ if new_contact_status not in YOUTUBE_CONTACT_STATUS: raise YouTubeError('New contact status must be one of %s' % (' '.join(YOUTUBE_CONTACT_STATUS))) if new_contact_category not in YOUTUBE_CONTACT_CATEGORY: raise YouTubeError('New contact category must be one of %s' % (' '.join(YOUTUBE_CONTACT_CATEGORY))) contact_category = atom.Category( scheme='http://gdata.youtube.com/schemas/2007/contact.cat', term=new_contact_category) contact_status = gdata.youtube.Status(text=new_contact_status) contact_entry = gdata.youtube.YouTubeContactEntry( category=contact_category, status=contact_status) contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts', contact_username) return self.Put(contact_entry, contact_put_uri, converter=gdata.youtube.YouTubeContactEntryFromString) def DeleteContact(self, contact_username, my_username='default'): """Delete a contact from a users contact feed. Needs authentication. Args: contact_username: A string representing the username of the contact that is to be deleted. my_username: An optional string representing the username of the user's contact feed from which to delete the contact. Defaults to the currently authenticated user. Returns: True if the contact was deleted successfully """ contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts', contact_username) return self.Delete(contact_edit_uri) def _GetDeveloperKey(self): """Getter for Developer Key property. Returns: If the developer key has been set, a string representing the developer key is returned or None. """ if 'X-GData-Key' in self.additional_headers: return self.additional_headers['X-GData-Key'][4:] else: return None def _SetDeveloperKey(self, developer_key): """Setter for Developer Key property. Sets the developer key in the 'X-GData-Key' header. The actual value that is set is 'key=' plus the developer_key that was passed. """ self.additional_headers['X-GData-Key'] = 'key=' + developer_key developer_key = property(_GetDeveloperKey, _SetDeveloperKey, doc="""The Developer Key property""") def _GetClientId(self): """Getter for Client Id property. Returns: If the client_id has been set, a string representing it is returned or None. """ if 'X-Gdata-Client' in self.additional_headers: return self.additional_headers['X-Gdata-Client'] else: return None def _SetClientId(self, client_id): """Setter for Client Id property. Sets the 'X-Gdata-Client' header. """ self.additional_headers['X-Gdata-Client'] = client_id client_id = property(_GetClientId, _SetClientId, doc="""The ClientId property""") def Query(self, uri): """Performs a query and returns a resulting feed or entry. Args: uri: A string representing the URI of the feed that is to be queried. Returns: On success, a tuple in the form: (boolean succeeded=True, ElementTree._Element result) On failure, a tuple in the form: (boolean succeeded=False, {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response}) """ result = self.Get(uri) return result def YouTubeQuery(self, query): """Performs a YouTube specific query and returns a resulting feed or entry. Args: query: A Query object or one if its sub-classes (YouTubeVideoQuery, YouTubeUserQuery or YouTubePlaylistQuery). Returns: Depending on the type of Query object submitted returns either a YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the Query object provided was not YouTube-related, a tuple is returned. On success the tuple will be in this form: (boolean succeeded=True, ElementTree._Element result) On failure, the tuple will be in this form: (boolean succeeded=False, {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server response}) """ result = self.Query(query.ToUri()) if isinstance(query, YouTubeVideoQuery): return gdata.youtube.YouTubeVideoFeedFromString(result.ToString()) elif isinstance(query, YouTubeUserQuery): return gdata.youtube.YouTubeUserFeedFromString(result.ToString()) elif isinstance(query, YouTubePlaylistQuery): return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString()) else: return result class YouTubeVideoQuery(gdata.service.Query): """Subclasses gdata.service.Query to represent a YouTube Data API query. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. Please refer to the API documentation for details. Attributes: vq: The vq parameter, which is only supported for video feeds, specifies a search query term. Refer to API documentation for further details. orderby: The orderby parameter, which is only supported for video feeds, specifies the value that will be used to sort videos in the search result set. Valid values for this parameter are relevance, published, viewCount and rating. time: The time parameter, which is only available for the top_rated, top_favorites, most_viewed, most_discussed, most_linked and most_responded standard feeds, restricts the search to videos uploaded within the specified time. Valid values for this parameter are today (1 day), this_week (7 days), this_month (1 month) and all_time. The default value for this parameter is all_time. format: The format parameter specifies that videos must be available in a particular video format. Refer to the API documentation for details. racy: The racy parameter allows a search result set to include restricted content as well as standard content. Valid values for this parameter are include and exclude. By default, restricted content is excluded. lr: The lr parameter restricts the search to videos that have a title, description or keywords in a specific language. Valid values for the lr parameter are ISO 639-1 two-letter language codes. restriction: The restriction parameter identifies the IP address that should be used to filter videos that can only be played in specific countries. location: A string of geo coordinates. Note that this is not used when the search is performed but rather to filter the returned videos for ones that match to the location entered. """ def __init__(self, video_id=None, feed_type=None, text_query=None, params=None, categories=None): if feed_type in YOUTUBE_STANDARDFEEDS: feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type) elif feed_type is 'responses' or feed_type is 'comments' and video_id: feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id, feed_type) else: feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER) gdata.service.Query.__init__(self, feed, text_query=text_query, params=params, categories=categories) def _GetVideoQuery(self): if 'vq' in self: return self['vq'] else: return None def _SetVideoQuery(self, val): self['vq'] = val vq = property(_GetVideoQuery, _SetVideoQuery, doc="""The video query (vq) query parameter""") def _GetOrderBy(self): if 'orderby' in self: return self['orderby'] else: return None def _SetOrderBy(self, val): if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS: if val.startswith('relevance_lang_') is False: raise YouTubeError('OrderBy must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS)) self['orderby'] = val orderby = property(_GetOrderBy, _SetOrderBy, doc="""The orderby query parameter""") def _GetTime(self): if 'time' in self: return self['time'] else: return None def _SetTime(self, val): if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS: raise YouTubeError('Time must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS)) self['time'] = val time = property(_GetTime, _SetTime, doc="""The time query parameter""") def _GetFormat(self): if 'format' in self: return self['format'] else: return None def _SetFormat(self, val): if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS: raise YouTubeError('Format must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS)) self['format'] = val format = property(_GetFormat, _SetFormat, doc="""The format query parameter""") def _GetRacy(self): if 'racy' in self: return self['racy'] else: return None def _SetRacy(self, val): if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS: raise YouTubeError('Racy must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS)) self['racy'] = val racy = property(_GetRacy, _SetRacy, doc="""The racy query parameter""") def _GetLanguageRestriction(self): if 'lr' in self: return self['lr'] else: return None def _SetLanguageRestriction(self, val): self['lr'] = val lr = property(_GetLanguageRestriction, _SetLanguageRestriction, doc="""The lr (language restriction) query parameter""") def _GetIPRestriction(self): if 'restriction' in self: return self['restriction'] else: return None def _SetIPRestriction(self, val): self['restriction'] = val restriction = property(_GetIPRestriction, _SetIPRestriction, doc="""The restriction query parameter""") def _GetLocation(self): if 'location' in self: return self['location'] else: return None def _SetLocation(self, val): self['location'] = val location = property(_GetLocation, _SetLocation, doc="""The location query parameter""") class YouTubeUserQuery(YouTubeVideoQuery): """Subclasses YouTubeVideoQuery to perform user-specific queries. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. """ def __init__(self, username=None, feed_type=None, subscription_id=None, text_query=None, params=None, categories=None): uploads_favorites_playlists = ('uploads', 'favorites', 'playlists') if feed_type is 'subscriptions' and subscription_id and username: feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username, feed_type, subscription_id) elif feed_type is 'subscriptions' and not subscription_id and username: feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username, feed_type) elif feed_type in uploads_favorites_playlists: feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username, feed_type) else: feed = "http://%s/feeds/users" % (YOUTUBE_SERVER) YouTubeVideoQuery.__init__(self, feed, text_query=text_query, params=params, categories=categories) class YouTubePlaylistQuery(YouTubeVideoQuery): """Subclasses YouTubeVideoQuery to perform playlist-specific queries. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. """ def __init__(self, playlist_id, text_query=None, params=None, categories=None): if playlist_id: feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id) else: feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER) YouTubeVideoQuery.__init__(self, feed, text_query=text_query, params=params, categories=categories)
Python
#!/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. """YouTubeService extends GDataService to streamline YouTube operations. YouTubeService: Provides methods to perform CRUD operations on YouTube feeds. Extends GDataService. """ __author__ = ('api.stephaniel@gmail.com (Stephanie Liu), ' 'api.jhartmann@gmail.com (Jochen Hartmann)') try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import os import atom import gdata import gdata.service import gdata.youtube YOUTUBE_SERVER = 'gdata.youtube.com' YOUTUBE_SERVICE = 'youtube' 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_URI = 'http://uploads.gdata.youtube.com/feeds/api/users' YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken' YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos' YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users' YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists' YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds' YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated') YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_viewed') YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'recently_featured') YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'watch_on_mobile') YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_favorites') YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_recent') YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_discussed') YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_linked') YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_responded') YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas' YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA, 'complaint-reasons.cat') YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA, 'subscriptiontypes.cat') YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS', 'RIGHTS', 'SPAM') YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected') YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family') UNKOWN_ERROR = 1000 YOUTUBE_BAD_REQUEST = 400 YOUTUBE_CONFLICT = 409 YOUTUBE_INTERNAL_SERVER_ERROR = 500 YOUTUBE_INVALID_ARGUMENT = 601 YOUTUBE_INVALID_CONTENT_TYPE = 602 YOUTUBE_NOT_A_VIDEO = 603 YOUTUBE_INVALID_KIND = 604 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 YouTubeService(gdata.service.GDataService): """Client for the YouTube service. Performs all documented Google Data YouTube API functions, such as inserting, updating and deleting videos, comments, playlist, subscriptions etc. YouTube Service requires authentication for any write, update or delete actions. Attributes: email: An optional string identifying the user. Required only for authenticated actions. password: An optional string identifying the user's password. source: An optional string identifying the name of your application. server: An optional address of the YouTube API server. gdata.youtube.com is provided as the default value. additional_headers: An optional dictionary containing additional headers to be passed along with each request. Use to store developer key. client_id: An optional string identifying your application, required for authenticated requests, along with a developer key. developer_key: An optional string value. Register your application at http://code.google.com/apis/youtube/dashboard to obtain a (free) key. """ def __init__(self, email=None, password=None, source=None, server=YOUTUBE_SERVER, additional_headers=None, client_id=None, developer_key=None, **kwargs): """Creates a client for the YouTube service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'gdata.youtube.com'. client_id: string (optional) Identifies your application, required for authenticated requests, along with a developer key. developer_key: string (optional) Register your application at http://code.google.com/apis/youtube/dashboard to obtain a (free) key. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ self.additional_headers = {} if client_id is not None and developer_key is not None: self.additional_headers = {'X-Gdata-Client': client_id, 'X-GData-Key': 'key=%s' % developer_key} elif developer_key and not client_id: raise YouTubeError('You must also specify the clientId') gdata.service.GDataService.__init__( self, email=email, password=password, service=YOUTUBE_SERVICE, source=source, server=server, additional_headers=additional_headers, **kwargs) self.auth_service_url = YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL def GetYouTubeVideoFeed(self, uri): """Retrieve a YouTubeVideoFeed. Args: uri: A string representing the URI of the feed that is to be retrieved. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString) def GetYouTubeVideoEntry(self, uri=None, video_id=None): """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 GetYouTubeVideoEntry() method') elif video_id and not uri: uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id) return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def GetYouTubeContactFeed(self, uri=None, username='default'): """Retrieve a YouTubeContactFeed. Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the contact feed that is to be retrieved. username: An optional string representing the username. Defaults to the currently authenticated user. Returns: A YouTubeContactFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeContactFeed() method. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts') return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString) def GetYouTubeContactEntry(self, uri): """Retrieve a YouTubeContactEntry. Args: uri: A string representing the URI of the contact entry that is to be retrieved. Returns: A YouTubeContactEntry if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString) def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None): """Retrieve a YouTubeVideoCommentFeed. Either a uri or a video_id must be provided. Args: uri: An optional string representing the URI of the comment feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the comment feed. Returns: A YouTubeVideoCommentFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoCommentFeed() 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 GetYouTubeVideoCommentFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments') return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString) def GetYouTubeVideoCommentEntry(self, uri): """Retrieve a YouTubeVideoCommentEntry. Args: uri: A string representing the URI of the comment entry that is to be retrieved. Returns: A YouTubeCommentEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString) def GetYouTubeUserFeed(self, uri=None, username=None): """Retrieve a YouTubeUserFeed. Either a uri or a username must be provided. 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(uri, converter=gdata.youtube.YouTubeUserFeedFromString) def GetYouTubeUserEntry(self, uri=None, username=None): """Retrieve a YouTubeUserEntry. Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the user entry that is to be retrieved. username: An optional string representing the username. Returns: A YouTubeUserEntry if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeUserEntry() method. """ if uri is None and username is None: raise YouTubeError('You must provide at least a uri or a username ' 'to the GetYouTubeUserEntry() method') elif username and not uri: uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username) return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString) def GetYouTubePlaylistFeed(self, uri=None, username='default'): """Retrieve a YouTubePlaylistFeed (a feed of playlists for a user). Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the playlist feed that is to be retrieved. username: An optional string representing the username. Defaults to the currently authenticated user. Returns: A YouTubePlaylistFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubePlaylistFeed() method. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists') return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString) def GetYouTubePlaylistEntry(self, uri): """Retrieve a YouTubePlaylistEntry. Args: uri: A string representing the URI of the playlist feed that is to be retrieved. Returns: A YouTubePlaylistEntry if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None): """Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist). Either a uri or a playlist_id must be provided. Args: uri: An optional string representing the URI of the playlist video feed that is to be retrieved. playlist_id: An optional string representing the Id of the playlist whose playlist video feed is to be retrieved. Returns: A YouTubePlaylistVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a playlist_id to the GetYouTubePlaylistVideoFeed() method. """ if uri is None and playlist_id is None: raise YouTubeError('You must provide at least a uri or a playlist_id ' 'to the GetYouTubePlaylistVideoFeed() method') elif playlist_id and not uri: uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id) return self.Get( uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString) def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None): """Retrieve a YouTubeVideoResponseFeed. Either a uri or a playlist_id must be provided. Args: uri: An optional string representing the URI of the video response feed that is to be retrieved. video_id: An optional string representing the ID of the video whose response feed is to be retrieved. Returns: A YouTubeVideoResponseFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoResponseFeed() 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 GetYouTubeVideoResponseFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses') return self.Get( uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString) def GetYouTubeVideoResponseEntry(self, uri): """Retrieve a YouTubeVideoResponseEntry. Args: uri: A string representing the URI of the video response entry that is to be retrieved. Returns: A YouTubeVideoResponseEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString) def GetYouTubeSubscriptionFeed(self, uri=None, username='default'): """Retrieve a YouTubeSubscriptionFeed. Either the uri of the feed or a username must be provided. Args: uri: An optional string representing the URI of the feed that is to be retrieved. username: An optional string representing the username whose subscription feed is to be retrieved. Defaults to the currently authenticted user. Returns: A YouTubeVideoSubscriptionFeed if successfully retrieved. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions') return self.Get( uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString) def GetYouTubeSubscriptionEntry(self, uri): """Retrieve a YouTubeSubscriptionEntry. Args: uri: A string representing the URI of the entry that is to be retrieved. Returns: A YouTubeVideoSubscriptionEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None): """Retrieve a YouTubeRelatedVideoFeed. Either a uri for the feed or a video_id is required. Args: uri: An optional string representing the URI of the feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the related video feed. Returns: A YouTubeRelatedVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeRelatedVideoFeed() 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 GetYouTubeRelatedVideoFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related') return self.Get( uri, converter=gdata.youtube.YouTubeVideoFeedFromString) def GetTopRatedVideoFeed(self): """Retrieve the 'top_rated' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI) def GetMostViewedVideoFeed(self): """Retrieve the 'most_viewed' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI) def GetRecentlyFeaturedVideoFeed(self): """Retrieve the 'recently_featured' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI) def GetWatchOnMobileVideoFeed(self): """Retrieve the 'watch_on_mobile' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI) def GetTopFavoritesVideoFeed(self): """Retrieve the 'top_favorites' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI) def GetMostRecentVideoFeed(self): """Retrieve the 'most_recent' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI) def GetMostDiscussedVideoFeed(self): """Retrieve the 'most_discussed' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI) def GetMostLinkedVideoFeed(self): """Retrieve the 'most_linked' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI) def GetMostRespondedVideoFeed(self): """Retrieve the 'most_responded' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI) def GetUserFavoritesFeed(self, username='default'): """Retrieve the favorites feed for a given user. Args: username: An optional string representing the username whose favorites feed is to be retrieved. Defaults to the currently authenticated user. Returns: A YouTubeVideoFeed if successfully retrieved. """ favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.GetYouTubeVideoFeed(favorites_feed_uri) def InsertVideoEntry(self, video_entry, filename_or_handle, youtube_username='default', content_type='video/quicktime'): """Upload a new video to YouTube using the direct upload mechanism. Needs authentication. Args: video_entry: The YouTubeVideoEntry to upload. filename_or_handle: A file-like object or file name where the video will be read from. youtube_username: An optional string representing the username into whose account this video is to be uploaded to. Defaults to the currently authenticated user. content_type: An optional string representing internet media type (a.k.a. mime type) of the media object. Currently the YouTube API supports these types: o video/mpeg o video/quicktime o video/x-msvideo o video/mp4 o video/x-flv Returns: The newly created YouTubeVideoEntry if successful. Raises: AssertionError: video_entry must be a gdata.youtube.VideoEntry instance. YouTubeError: An error occurred trying to read the video file provided. gdata.service.RequestError: An error occurred trying to upload the video to the API server. """ # We need to perform a series of checks on the video_entry and on the # file that we plan to upload, such as checking whether we have a valid # video_entry and that the file is the correct type and readable, prior # to performing the actual POST request. try: assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) except AssertionError: raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':'`video_entry` must be a gdata.youtube.VideoEntry instance', 'reason':'Found %s, not VideoEntry' % type(video_entry) }) majtype, mintype = content_type.split('/') try: assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % ['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]}) if (isinstance(filename_or_handle, (str, unicode)) and os.path.exists(filename_or_handle)): mediasource = gdata.MediaSource() mediasource.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'): import StringIO if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'video' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body': '`filename_or_handle` must be a path name or a file-like object', 'reason': ('Found %s, not path name or object ' 'with a .read() method' % type(filename_or_handle))}) upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username, 'uploads') self.additional_headers['Slug'] = mediasource.file_name # Using a nested try statement to retain Python 2.4 compatibility try: try: return self.Post(video_entry, uri=upload_uri, media_source=mediasource, converter=gdata.youtube.YouTubeVideoEntryFromString) except gdata.service.RequestError, e: raise YouTubeError(e.args[0]) finally: del(self.additional_headers['Slug']) def CheckUploadStatus(self, video_entry=None, video_id=None): """Check upload status on a recently uploaded video entry. Needs authentication. Either video_entry or video_id must be provided. Args: video_entry: An optional YouTubeVideoEntry whose upload status to check video_id: An optional string representing the ID of the uploaded video whose status is to be checked. Returns: A tuple containing (video_upload_state, detailed_message) or None if no status information is found. Raises: YouTubeError: You must provide at least a video_entry or a video_id to the CheckUploadStatus() method. """ if video_entry is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the CheckUploadStatus() method') elif video_id and not video_entry: video_entry = self.GetYouTubeVideoEntry(video_id=video_id) control = video_entry.control if control is not None: draft = control.draft if draft is not None: if draft.text == 'yes': yt_state = control.extension_elements[0] if yt_state is not None: state_value = yt_state.attributes['name'] message = '' if yt_state.text is not None: message = yt_state.text return (state_value, message) def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI): """Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry. Needs authentication. Args: video_entry: The YouTubeVideoEntry to upload (meta-data only). uri: An optional string representing the URI from where to fetch the token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI. Returns: A tuple containing the URL to which to post your video file, along with the youtube token that must be included with your upload in the form of: (post_url, youtube_token). """ try: response = self.Post(video_entry, uri) except gdata.service.RequestError, e: raise YouTubeError(e.args[0]) tree = ElementTree.fromstring(response) for child in tree: if child.tag == 'url': post_url = child.text elif child.tag == 'token': youtube_token = child.text return (post_url, youtube_token) def UpdateVideoEntry(self, video_entry): """Updates a video entry's meta-data. Needs authentication. Args: video_entry: The YouTubeVideoEntry to update, containing updated meta-data. Returns: An updated YouTubeVideoEntry on success or None. """ for link in video_entry.link: if link.rel == 'edit': edit_uri = link.href return self.Put(video_entry, uri=edit_uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def DeleteVideoEntry(self, video_entry): """Deletes a video entry. Needs authentication. Args: video_entry: The YouTubeVideoEntry to be deleted. Returns: True if entry was deleted successfully. """ for link in video_entry.link: if link.rel == 'edit': edit_uri = link.href return self.Delete(edit_uri) def AddRating(self, rating_value, video_entry): """Add a rating to a video entry. Needs authentication. Args: rating_value: The integer value for the rating (between 1 and 5). video_entry: The YouTubeVideoEntry to be rated. Returns: True if the rating was added successfully. Raises: YouTubeError: rating_value must be between 1 and 5 in AddRating(). """ if rating_value < 1 or rating_value > 5: raise YouTubeError('rating_value must be between 1 and 5 in AddRating()') entry = gdata.GDataEntry() rating = gdata.youtube.Rating(min='1', max='5') rating.extension_attributes['name'] = 'value' rating.extension_attributes['value'] = str(rating_value) entry.extension_elements.append(rating) for link in video_entry.link: if link.rel == YOUTUBE_RATING_LINK_REL: rating_uri = link.href return self.Post(entry, uri=rating_uri) def AddComment(self, comment_text, video_entry): """Add a comment to a video entry. Needs authentication. Note that each comment that is posted must contain the video entry that it is to be posted to. Args: comment_text: A string representing the text of the comment. video_entry: The YouTubeVideoEntry to be commented on. Returns: True if the comment was added successfully. """ content = atom.Content(text=comment_text) comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content) comment_post_uri = video_entry.comments.feed_link[0].href return self.Post(comment_entry, uri=comment_post_uri) def AddVideoResponse(self, video_id_to_respond_to, video_response): """Add a video response. Needs authentication. Args: video_id_to_respond_to: A string representing the ID of the video to be responded to. video_response: YouTubeVideoEntry to be posted as a response. Returns: True if video response was posted successfully. """ post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to, 'responses') return self.Post(video_response, uri=post_uri) def DeleteVideoResponse(self, video_id, response_video_id): """Delete a video response. Needs authentication. Args: video_id: A string representing the ID of video that contains the response. response_video_id: A string representing the ID of the video that was posted as a response. Returns: True if video response was deleted succcessfully. """ delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses', response_video_id) return self.Delete(delete_uri) def AddComplaint(self, complaint_text, complaint_term, video_id): """Add a complaint for a particular video entry. Needs authentication. Args: complaint_text: A string representing the complaint text. complaint_term: A string representing the complaint category term. video_id: A string representing the ID of YouTubeVideoEntry to complain about. Returns: True if posted successfully. Raises: YouTubeError: Your complaint_term is not valid. """ if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS: raise YouTubeError('Your complaint_term is not valid') content = atom.Content(text=complaint_text) category = atom.Category(term=complaint_term, scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME) complaint_entry = gdata.GDataEntry(content=content, category=[category]) post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints') return self.Post(complaint_entry, post_uri) def AddVideoEntryToFavorites(self, video_entry, username='default'): """Add a video entry to a users favorite feed. Needs authentication. Args: video_entry: The YouTubeVideoEntry to add. username: An optional string representing the username to whose favorite feed you wish to add the entry. Defaults to the currently authenticated user. Returns: The posted YouTubeVideoEntry if successfully posted. """ post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.Post(video_entry, post_uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def DeleteVideoEntryFromFavorites(self, video_id, username='default'): """Delete a video entry from the users favorite feed. Needs authentication. Args: video_id: A string representing the ID of the video that is to be removed username: An optional string representing the username of the user's favorite feed. Defaults to the currently authenticated user. Returns: True if entry was successfully deleted. """ edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites', video_id) return self.Delete(edit_link) def AddPlaylist(self, playlist_title, playlist_description, playlist_private=None): """Add a new playlist to the currently authenticated users account. Needs authentication. Args: playlist_title: A string representing the title for the new playlist. playlist_description: A string representing the description of the playlist. playlist_private: An optional boolean, set to True if the playlist is to be private. Returns: The YouTubePlaylistEntry if successfully posted. """ playlist_entry = gdata.youtube.YouTubePlaylistEntry( title=atom.Title(text=playlist_title), description=gdata.youtube.Description(text=playlist_description)) if playlist_private: playlist_entry.private = gdata.youtube.Private() playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default', 'playlists') return self.Post(playlist_entry, playlist_post_uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def UpdatePlaylist(self, playlist_id, new_playlist_title, new_playlist_description, playlist_private=None, username='default'): """Update a playlist with new meta-data. Needs authentication. Args: playlist_id: A string representing the ID of the playlist to be updated. new_playlist_title: A string representing a new title for the playlist. new_playlist_description: A string representing a new description for the playlist. playlist_private: An optional boolean, set to True if the playlist is to be private. username: An optional string representing the username whose playlist is to be updated. Defaults to the currently authenticated user. Returns: A YouTubePlaylistEntry if the update was successful. """ updated_playlist = gdata.youtube.YouTubePlaylistEntry( title=atom.Title(text=new_playlist_title), description=gdata.youtube.Description(text=new_playlist_description)) if playlist_private: updated_playlist.private = gdata.youtube.Private() playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username, playlist_id) return self.Put(updated_playlist, playlist_put_uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def DeletePlaylist(self, playlist_uri): """Delete a playlist from the currently authenticated users playlists. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist that is to be deleted. Returns: True if successfully deleted. """ return self.Delete(playlist_uri) def AddPlaylistVideoEntryToPlaylist( self, playlist_uri, video_id, custom_video_title=None, custom_video_description=None): """Add a video entry to a playlist, optionally providing a custom title and description. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist to which this video entry is to be added. video_id: A string representing the ID of the video entry to add. custom_video_title: An optional string representing a custom title for the video (only shown on the playlist). custom_video_description: An optional string representing a custom description for the video (only shown on the playlist). Returns: A YouTubePlaylistVideoEntry if successfully posted. """ playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry( atom_id=atom.Id(text=video_id)) if custom_video_title: playlist_video_entry.title = atom.Title(text=custom_video_title) if custom_video_description: playlist_video_entry.description = gdata.youtube.Description( text=custom_video_description) return self.Post(playlist_video_entry, playlist_uri, converter=gdata.youtube.YouTubePlaylistVideoEntryFromString) def UpdatePlaylistVideoEntryMetaData( self, playlist_uri, playlist_entry_id, new_video_title, new_video_description, new_video_position): """Update the meta data for a YouTubePlaylistVideoEntry. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist that contains the entry to be updated. playlist_entry_id: A string representing the ID of the entry to be updated. new_video_title: A string representing the new title for the video entry. new_video_description: A string representing the new description for the video entry. new_video_position: An integer representing the new position on the playlist for the video. Returns: A YouTubePlaylistVideoEntry if the update was successful. """ playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry( title=atom.Title(text=new_video_title), description=gdata.youtube.Description(text=new_video_description), position=gdata.youtube.Position(text=str(new_video_position))) playlist_put_uri = playlist_uri + '/' + playlist_entry_id return self.Put(playlist_video_entry, playlist_put_uri, converter=gdata.youtube.YouTubePlaylistVideoEntryFromString) def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id): """Delete a playlist video entry from a playlist. Needs authentication. Args: playlist_uri: A URI representing the playlist from which the playlist video entry is to be removed from. playlist_video_entry_id: A string representing id of the playlist video entry that is to be removed. Returns: True if entry was successfully deleted. """ delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id) return self.Delete(delete_uri) def AddSubscriptionToChannel(self, username_to_subscribe_to, my_username = 'default'): """Add a new channel subscription to the currently authenticated users account. Needs authentication. Args: username_to_subscribe_to: A string representing the username of the channel to which we want to subscribe to. my_username: An optional string representing the name of the user which we want to subscribe. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successfully posted. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='channel') subscription_username = gdata.youtube.Username( text=username_to_subscribe_to) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, username=subscription_username) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def AddSubscriptionToFavorites(self, username, my_username = 'default'): """Add a new subscription to a users favorites to the currently authenticated user's account. Needs authentication Args: username: A string representing the username of the user's favorite feed to subscribe to. my_username: An optional string representing the username of the user that is to be subscribed. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successful. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='favorites') subscription_username = gdata.youtube.Username(text=username) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, username=subscription_username) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def AddSubscriptionToQuery(self, query, my_username = 'default'): """Add a new subscription to a specific keyword query to the currently authenticated user's account. Needs authentication Args: query: A string representing the keyword query to subscribe to. my_username: An optional string representing the username of the user that is to be subscribed. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successful. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='query') subscription_query_string = gdata.youtube.QueryString(text=query) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, query_string=subscription_query_string) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def DeleteSubscription(self, subscription_uri): """Delete a subscription from the currently authenticated user's account. Needs authentication. Args: subscription_uri: A string representing the URI of the subscription that is to be deleted. Returns: True if deleted successfully. """ return self.Delete(subscription_uri) def AddContact(self, contact_username, my_username='default'): """Add a new contact to the currently authenticated user's contact feed. Needs authentication. Args: contact_username: A string representing the username of the contact that you wish to add. my_username: An optional string representing the username to whose contact the new contact is to be added. Returns: A YouTubeContactEntry if added successfully. """ contact_category = atom.Category( scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat', term = 'Friends') contact_username = gdata.youtube.Username(text=contact_username) contact_entry = gdata.youtube.YouTubeContactEntry( category=contact_category, username=contact_username) contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts') return self.Post(contact_entry, contact_post_uri, converter=gdata.youtube.YouTubeContactEntryFromString) def UpdateContact(self, contact_username, new_contact_status, new_contact_category, my_username='default'): """Update a contact, providing a new status and a new category. Needs authentication. Args: contact_username: A string representing the username of the contact that is to be updated. new_contact_status: A string representing the new status of the contact. This can either be set to 'accepted' or 'rejected'. new_contact_category: A string representing the new category for the contact, either 'Friends' or 'Family'. my_username: An optional string representing the username of the user whose contact feed we are modifying. Defaults to the currently authenticated user. Returns: A YouTubeContactEntry if updated succesfully. Raises: YouTubeError: New contact status must be within the accepted values. Or new contact category must be within the accepted categories. """ if new_contact_status not in YOUTUBE_CONTACT_STATUS: raise YouTubeError('New contact status must be one of %s' % (' '.join(YOUTUBE_CONTACT_STATUS))) if new_contact_category not in YOUTUBE_CONTACT_CATEGORY: raise YouTubeError('New contact category must be one of %s' % (' '.join(YOUTUBE_CONTACT_CATEGORY))) contact_category = atom.Category( scheme='http://gdata.youtube.com/schemas/2007/contact.cat', term=new_contact_category) contact_status = gdata.youtube.Status(text=new_contact_status) contact_entry = gdata.youtube.YouTubeContactEntry( category=contact_category, status=contact_status) contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts', contact_username) return self.Put(contact_entry, contact_put_uri, converter=gdata.youtube.YouTubeContactEntryFromString) def DeleteContact(self, contact_username, my_username='default'): """Delete a contact from a users contact feed. Needs authentication. Args: contact_username: A string representing the username of the contact that is to be deleted. my_username: An optional string representing the username of the user's contact feed from which to delete the contact. Defaults to the currently authenticated user. Returns: True if the contact was deleted successfully """ contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts', contact_username) return self.Delete(contact_edit_uri) def _GetDeveloperKey(self): """Getter for Developer Key property. Returns: If the developer key has been set, a string representing the developer key is returned or None. """ if 'X-GData-Key' in self.additional_headers: return self.additional_headers['X-GData-Key'][4:] else: return None def _SetDeveloperKey(self, developer_key): """Setter for Developer Key property. Sets the developer key in the 'X-GData-Key' header. The actual value that is set is 'key=' plus the developer_key that was passed. """ self.additional_headers['X-GData-Key'] = 'key=' + developer_key developer_key = property(_GetDeveloperKey, _SetDeveloperKey, doc="""The Developer Key property""") def _GetClientId(self): """Getter for Client Id property. Returns: If the client_id has been set, a string representing it is returned or None. """ if 'X-Gdata-Client' in self.additional_headers: return self.additional_headers['X-Gdata-Client'] else: return None def _SetClientId(self, client_id): """Setter for Client Id property. Sets the 'X-Gdata-Client' header. """ self.additional_headers['X-Gdata-Client'] = client_id client_id = property(_GetClientId, _SetClientId, doc="""The ClientId property""") def Query(self, uri): """Performs a query and returns a resulting feed or entry. Args: uri: A string representing the URI of the feed that is to be queried. Returns: On success, a tuple in the form: (boolean succeeded=True, ElementTree._Element result) On failure, a tuple in the form: (boolean succeeded=False, {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response}) """ result = self.Get(uri) return result def YouTubeQuery(self, query): """Performs a YouTube specific query and returns a resulting feed or entry. Args: query: A Query object or one if its sub-classes (YouTubeVideoQuery, YouTubeUserQuery or YouTubePlaylistQuery). Returns: Depending on the type of Query object submitted returns either a YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the Query object provided was not YouTube-related, a tuple is returned. On success the tuple will be in this form: (boolean succeeded=True, ElementTree._Element result) On failure, the tuple will be in this form: (boolean succeeded=False, {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server response}) """ result = self.Query(query.ToUri()) if isinstance(query, YouTubeVideoQuery): return gdata.youtube.YouTubeVideoFeedFromString(result.ToString()) elif isinstance(query, YouTubeUserQuery): return gdata.youtube.YouTubeUserFeedFromString(result.ToString()) elif isinstance(query, YouTubePlaylistQuery): return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString()) else: return result class YouTubeVideoQuery(gdata.service.Query): """Subclasses gdata.service.Query to represent a YouTube Data API query. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. Please refer to the API documentation for details. Attributes: vq: The vq parameter, which is only supported for video feeds, specifies a search query term. Refer to API documentation for further details. orderby: The orderby parameter, which is only supported for video feeds, specifies the value that will be used to sort videos in the search result set. Valid values for this parameter are relevance, published, viewCount and rating. time: The time parameter, which is only available for the top_rated, top_favorites, most_viewed, most_discussed, most_linked and most_responded standard feeds, restricts the search to videos uploaded within the specified time. Valid values for this parameter are today (1 day), this_week (7 days), this_month (1 month) and all_time. The default value for this parameter is all_time. format: The format parameter specifies that videos must be available in a particular video format. Refer to the API documentation for details. racy: The racy parameter allows a search result set to include restricted content as well as standard content. Valid values for this parameter are include and exclude. By default, restricted content is excluded. lr: The lr parameter restricts the search to videos that have a title, description or keywords in a specific language. Valid values for the lr parameter are ISO 639-1 two-letter language codes. restriction: The restriction parameter identifies the IP address that should be used to filter videos that can only be played in specific countries. location: A string of geo coordinates. Note that this is not used when the search is performed but rather to filter the returned videos for ones that match to the location entered. """ def __init__(self, video_id=None, feed_type=None, text_query=None, params=None, categories=None): if feed_type in YOUTUBE_STANDARDFEEDS: feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type) elif feed_type is 'responses' or feed_type is 'comments' and video_id: feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id, feed_type) else: feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER) gdata.service.Query.__init__(self, feed, text_query=text_query, params=params, categories=categories) def _GetVideoQuery(self): if 'vq' in self: return self['vq'] else: return None def _SetVideoQuery(self, val): self['vq'] = val vq = property(_GetVideoQuery, _SetVideoQuery, doc="""The video query (vq) query parameter""") def _GetOrderBy(self): if 'orderby' in self: return self['orderby'] else: return None def _SetOrderBy(self, val): if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS: if val.startswith('relevance_lang_') is False: raise YouTubeError('OrderBy must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS)) self['orderby'] = val orderby = property(_GetOrderBy, _SetOrderBy, doc="""The orderby query parameter""") def _GetTime(self): if 'time' in self: return self['time'] else: return None def _SetTime(self, val): if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS: raise YouTubeError('Time must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS)) self['time'] = val time = property(_GetTime, _SetTime, doc="""The time query parameter""") def _GetFormat(self): if 'format' in self: return self['format'] else: return None def _SetFormat(self, val): if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS: raise YouTubeError('Format must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS)) self['format'] = val format = property(_GetFormat, _SetFormat, doc="""The format query parameter""") def _GetRacy(self): if 'racy' in self: return self['racy'] else: return None def _SetRacy(self, val): if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS: raise YouTubeError('Racy must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS)) self['racy'] = val racy = property(_GetRacy, _SetRacy, doc="""The racy query parameter""") def _GetLanguageRestriction(self): if 'lr' in self: return self['lr'] else: return None def _SetLanguageRestriction(self, val): self['lr'] = val lr = property(_GetLanguageRestriction, _SetLanguageRestriction, doc="""The lr (language restriction) query parameter""") def _GetIPRestriction(self): if 'restriction' in self: return self['restriction'] else: return None def _SetIPRestriction(self, val): self['restriction'] = val restriction = property(_GetIPRestriction, _SetIPRestriction, doc="""The restriction query parameter""") def _GetLocation(self): if 'location' in self: return self['location'] else: return None def _SetLocation(self, val): self['location'] = val location = property(_GetLocation, _SetLocation, doc="""The location query parameter""") class YouTubeUserQuery(YouTubeVideoQuery): """Subclasses YouTubeVideoQuery to perform user-specific queries. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. """ def __init__(self, username=None, feed_type=None, subscription_id=None, text_query=None, params=None, categories=None): uploads_favorites_playlists = ('uploads', 'favorites', 'playlists') if feed_type is 'subscriptions' and subscription_id and username: feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username, feed_type, subscription_id) elif feed_type is 'subscriptions' and not subscription_id and username: feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username, feed_type) elif feed_type in uploads_favorites_playlists: feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username, feed_type) else: feed = "http://%s/feeds/users" % (YOUTUBE_SERVER) YouTubeVideoQuery.__init__(self, feed, text_query=text_query, params=params, categories=categories) class YouTubePlaylistQuery(YouTubeVideoQuery): """Subclasses YouTubeVideoQuery to perform playlist-specific queries. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. """ def __init__(self, playlist_id, text_query=None, params=None, categories=None): if playlist_id: feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id) else: feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER) YouTubeVideoQuery.__init__(self, feed, text_query=text_query, params=params, categories=categories)
Python
#!/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)
Python
#!/usr/bin/python # # Copyright (C) 2007, 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. import cgi import math import random import re import time import types import urllib import atom.http_interface import atom.token_store import atom.url import gdata.oauth as oauth import gdata.oauth.rsa as oauth_rsa import gdata.tlslite.utils.keyfactory as keyfactory import gdata.tlslite.utils.cryptomath as cryptomath __author__ = 'api.jscudder (Jeff Scudder)' PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth=' AUTHSUB_AUTH_LABEL = 'AuthSub token=' """This module provides functions and objects used with Google authentication. Details on Google authorization mechanisms used with the Google Data APIs can be found here: http://code.google.com/apis/gdata/auth.html http://code.google.com/apis/accounts/ The essential functions are the following. Related to ClientLogin: generate_client_login_request_body: Constructs the body of an HTTP request to obtain a ClientLogin token for a specific service. extract_client_login_token: Creates a ClientLoginToken with the token from a success response to a ClientLogin request. get_captcha_challenge: If the server responded to the ClientLogin request with a CAPTCHA challenge, this method extracts the CAPTCHA URL and identifying CAPTCHA token. Related to AuthSub: generate_auth_sub_url: Constructs a full URL for a AuthSub request. The user's browser must be sent to this Google Accounts URL and redirected back to the app to obtain the AuthSub token. extract_auth_sub_token_from_url: Once the user's browser has been redirected back to the web app, use this function to create an AuthSubToken with the correct authorization token and scope. token_from_http_body: Extracts the AuthSubToken value string from the server's response to an AuthSub session token upgrade request. """ def generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): """Creates the body of the autentication request See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request for more details. Args: email: str password: str service: str source: str account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid values are 'GOOGLE' and 'HOSTED' captcha_token: str (optional) captcha_response: str (optional) Returns: The HTTP body to send in a request for a client login token. """ # Create a POST body containing the user's credentials. request_fields = {'Email': email, 'Passwd': password, 'accountType': account_type, 'service': service, 'source': source} if captcha_token and captcha_response: # Send the captcha token and response as part of the POST body if the # user is responding to a captch challenge. request_fields['logintoken'] = captcha_token request_fields['logincaptcha'] = captcha_response return urllib.urlencode(request_fields) GenerateClientLoginRequestBody = generate_client_login_request_body def GenerateClientLoginAuthToken(http_body): """Returns the token value to use in Authorization headers. Reads the token from the server's response to a Client Login request and creates header value to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The value half of an Authorization header. """ token = get_client_login_token(http_body) if token: return 'GoogleLogin auth=%s' % token return None def get_client_login_token(http_body): """Returns the token value for a ClientLoginToken. Reads the token from the server's response to a Client Login request and creates the token value string to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The token value string for a ClientLoginToken. """ for response_line in http_body.splitlines(): if response_line.startswith('Auth='): # Strip off the leading Auth= and return the Authorization value. return response_line[5:] return None def extract_client_login_token(http_body, scopes): """Parses the server's response and returns a ClientLoginToken. Args: http_body: str The body of the server's HTTP response to a Client Login request. It is assumed that the login request was successful. scopes: list containing atom.url.Urls or strs. The scopes list contains all of the partial URLs under which the client login token is valid. For example, if scopes contains ['http://example.com/foo'] then the client login token would be valid for http://example.com/foo/bar/baz Returns: A ClientLoginToken which is valid for the specified scopes. """ token_string = get_client_login_token(http_body) token = ClientLoginToken(scopes=scopes) token.set_token_string(token_string) return token def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str This function returns a full URL for viewing the challenge image which is built from the server's response. This base_url is used as the beginning of the URL because the server only provides the end of the URL. For example the server provides 'Captcha?ctoken=Hi...N' and the URL for the image is 'http://www.google.com/accounts/Captcha?ctoken=Hi...N' Returns: A dictionary containing the information needed to repond to the CAPTCHA challenge, the image URL and the ID token of the challenge. The dictionary is in the form: {'token': string identifying the CAPTCHA image, 'url': string containing the URL of the image} Returns None if there was no CAPTCHA challenge in the response. """ contains_captcha_challenge = False captcha_parameters = {} for response_line in http_body.splitlines(): if response_line.startswith('Error=CaptchaRequired'): contains_captcha_challenge = True elif response_line.startswith('CaptchaToken='): # Strip off the leading CaptchaToken= captcha_parameters['token'] = response_line[13:] elif response_line.startswith('CaptchaUrl='): captcha_parameters['url'] = '%s%s' % (captcha_base_url, response_line[11:]) if contains_captcha_challenge: return captcha_parameters else: return None GetCaptchaChallenge = get_captcha_challenge def GenerateOAuthRequestTokenUrl( oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): """Generate a URL at which a request for OAuth request token is to be sent. Args: oauth_input_params: OAuthInputParams OAuth input parameters. scopes: list of strings The URLs of the services to be accessed. request_token_url: string The beginning of the request token URL. This is normally 'https://www.google.com/accounts/OAuthGetRequestToken' or '/accounts/OAuthGetRequestToken' extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} Returns: atom.url.Url OAuth request token URL. """ scopes_string = ' '.join([str(scope) for scope in scopes]) parameters = {'scope': scopes_string} if extra_parameters: parameters.update(extra_parameters) oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), http_url=request_token_url, parameters=parameters) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), None) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAuthorizationUrl( request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken OAuth request token. authorization_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthAuthorizeToken' or '/accounts/OAuthAuthorizeToken' callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. Returns: atom.url.Url OAuth authorization URL. """ scopes = request_token.scopes if isinstance(scopes, list): scopes = ' '.join(scopes) if include_scopes_in_callback and callback_url: if callback_url.find('?') > -1: callback_url += '&' else: callback_url += '?' callback_url += urllib.urlencode({scopes_param_prefix:scopes}) oauth_token = oauth.OAuthToken(request_token.key, request_token.secret) oauth_request = oauth.OAuthRequest.from_token_and_callback( token=oauth_token, callback=callback_url, http_url=authorization_url, parameters=extra_params) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAccessTokenUrl( authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0'): """Generates URL at which user will login to authorize the request token. Args: authorized_request_token: gdata.auth.OAuthToken OAuth authorized request token. oauth_input_params: OAuthInputParams OAuth input parameters. access_token_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthGetAccessToken' or '/accounts/OAuthGetAccessToken' oauth_version: str (default='1.0') oauth_version parameter. Returns: atom.url.Url OAuth access token URL. """ oauth_token = oauth.OAuthToken(authorized_request_token.key, authorized_request_token.secret) oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), token=oauth_token, http_url=access_token_url, parameters={'oauth_version': oauth_version}) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), oauth_token) return atom.url.parse_url(oauth_request.to_url()) def GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/AuthForWebApps.html Args: request_url: str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' next: string The URL user will be sent to after logging in. scope: string The URL of the service to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. domain: str (optional) The Google Apps domain for this account. If this is not a Google Apps account, use 'default' which is the default value. """ # Translate True/False values for parameters into numeric values acceoted # by the AuthSub service. if secure: secure = 1 else: secure = 0 if session: session = 1 else: session = 0 request_params = urllib.urlencode({'next': next, 'scope': scope, 'secure': secure, 'session': session, 'hd': domain}) if request_url.find('?') == -1: return '%s?%s' % (request_url, request_params) else: # The request URL already contained url parameters so we should add # the parameters using the & seperator return '%s&%s' % (request_url, request_params) def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): """Constructs a URL string for requesting a multiscope AuthSub token. The generated token will contain a URL parameter to pass along the requested scopes to the next URL. When the Google Accounts page redirects the broswser to the 'next' URL, it appends the single use AuthSub token value to the URL as a URL parameter with the key 'token'. However, the information about which scopes were requested is not included by Google Accounts. This method adds the scopes to the next URL before making the request so that the redirect will be sent to a page, and both the token value and the list of scopes can be extracted from the request URL. Args: next: atom.url.URL or string The URL user will be sent to after authorizing this web application to access their data. scopes: list containint strings The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. request_url: atom.url.Url or str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' domain: The domain which the account is part of. This is used for Google Apps accounts, the default value is 'default' which means that the requested account is a Google Account (@gmail.com for example) scopes_param_prefix: str (optional) The requested scopes are added as a URL parameter to the next URL so that the page at the 'next' URL can extract the token value and the valid scopes from the URL. The key for the URL parameter defaults to 'auth_sub_scopes' Returns: An atom.url.Url which the user's browser should be directed to in order to authorize this application to access their information. """ if isinstance(next, (str, unicode)): next = atom.url.parse_url(next) scopes_string = ' '.join([str(scope) for scope in scopes]) next.params[scopes_param_prefix] = scopes_string if isinstance(request_url, (str, unicode)): request_url = atom.url.parse_url(request_url) request_url.params['next'] = str(next) request_url.params['scope'] = scopes_string if session: request_url.params['session'] = 1 else: request_url.params['session'] = 0 if secure: request_url.params['secure'] = 1 else: request_url.params['secure'] = 0 request_url.params['hd'] = domain return request_url def AuthSubTokenFromUrl(url): """Extracts the AuthSub token from the URL. Used after the AuthSub redirect has sent the user to the 'next' page and appended the token to the URL. This function returns the value to be used in the Authorization header. Args: url: str The URL of the current page which contains the AuthSub token as a URL parameter. """ token = TokenFromUrl(url) if token: return 'AuthSub token=%s' % token return None def TokenFromUrl(url): """Extracts the AuthSub token from the URL. Returns the raw token value. Args: url: str The URL or the query portion of the URL string (after the ?) of the current page which contains the AuthSub token as a URL parameter. """ if url.find('?') > -1: query_params = url.split('?')[1] else: query_params = url for pair in query_params.split('&'): if pair.startswith('token='): return pair[6:] return None def extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): """Creates an AuthSubToken and sets the token value and scopes from the URL. After the Google Accounts AuthSub pages redirect the user's broswer back to the web application (using the 'next' URL from the request) the web app must extract the token from the current page's URL. The token is provided as a URL parameter named 'token' and if generate_auth_sub_url was used to create the request, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An AuthSubToken with the token value from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the AuthSubToken defaults to being valid for no scopes. If there was no 'token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_value = url.params['token'] if rsa_key: token = SecureAuthSubToken(rsa_key, scopes=scopes) else: token = AuthSubToken(scopes=scopes) token.set_token_string(token_value) return token def AuthSubTokenFromHttpBody(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The header value to use for Authorization which contains the AuthSub token. """ token_value = token_from_http_body(http_body) if token_value: return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value) return None def token_from_http_body(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The raw token value to use in an AuthSubToken object. """ for response_line in http_body.splitlines(): if response_line.startswith('Token='): # Strip off Token= and return the token value string. return response_line[6:] return None TokenFromHttpBody = token_from_http_body def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): """Creates an OAuthToken and sets token key and scopes (if present) from URL. After the Google Accounts OAuth pages redirect the user's broswer back to the web application (using the 'callback' URL from the request) the web app can extract the token from the current page's URL. The token is same as the request token, but it is either authorized (if user grants access) or unauthorized (if user denies access). The token is provided as a URL parameter named 'oauth_token' and if it was chosen to use GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An OAuthToken with the token key from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the OAuthToken defaults to being valid for no scopes. If there was no 'oauth_token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'oauth_token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_key = url.params['oauth_token'] token = OAuthToken(key=token_key, scopes=scopes) return token def OAuthTokenFromHttpBody(http_body): """Parses the HTTP response body and returns an OAuth token. The returned OAuth token will just have key and secret parameters set. It won't have any knowledge about the scopes or oauth_input_params. It is your responsibility to make it aware of the remaining parameters. Returns: OAuthToken OAuth token. """ token = oauth.OAuthToken.from_string(http_body) oauth_token = OAuthToken(key=token.key, secret=token.secret) return oauth_token class OAuthSignatureMethod(object): """Holds valid OAuth signature methods. RSA_SHA1: Class to build signature according to RSA-SHA1 algorithm. HMAC_SHA1: Class to build signature according to HMAC-SHA1 algorithm. """ HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1 class RSA_SHA1(oauth_rsa.OAuthSignatureMethod_RSA_SHA1): """Provides implementation for abstract methods to return RSA certs.""" def __init__(self, private_key, public_cert): self.private_key = private_key self.public_cert = public_cert def _fetch_public_cert(self, unused_oauth_request): return self.public_cert def _fetch_private_cert(self, unused_oauth_request): return self.private_key class OAuthInputParams(object): """Stores OAuth input parameters. This class is a store for OAuth input parameters viz. consumer key and secret, signature method and RSA key. """ def __init__(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None): """Initializes object with parameters required for using OAuth mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. """ if signature_method == OAuthSignatureMethod.RSA_SHA1: self._signature_method = signature_method(rsa_key, None) else: self._signature_method = signature_method() self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) def GetSignatureMethod(self): """Gets the OAuth signature method. Returns: object of supertype <oauth.oauth.OAuthSignatureMethod> """ return self._signature_method def GetConsumer(self): """Gets the OAuth consumer. Returns: object of type <oauth.oauth.Consumer> """ return self._consumer class ClientLoginToken(atom.http_interface.GenericToken): """Stores the Authorization header in auth_header and adds to requests. This token will add it's Authorization header to an HTTP request as it is made. Ths token class is simple but some Token classes must calculate portions of the Authorization header based on the request being made, which is why the token is responsible for making requests via an http_client parameter. Args: auth_header: str The value for the Authorization header. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, auth_header=None, scopes=None): self.auth_header = auth_header self.scopes = scopes or [] def __str__(self): return self.auth_header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if headers is None: headers = {'Authorization':self.auth_header} else: headers['Authorization'] = self.auth_header return http_client.request(operation, url, data=data, headers=headers) def get_token_string(self): """Removes PROGRAMMATIC_AUTH_LABEL to give just the token value.""" return self.auth_header[len(PROGRAMMATIC_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string) def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class AuthSubToken(ClientLoginToken): def get_token_string(self): """Removes AUTHSUB_AUTH_LABEL to give just the token value.""" return self.auth_header[len(AUTHSUB_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (AUTHSUB_AUTH_LABEL, token_string) class OAuthToken(atom.http_interface.GenericToken): """Stores the token key, token secret and scopes for which token is valid. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the OAuth signature to be added to the authorization header is dependent on the request parameters. Attributes: key: str The value for the OAuth token i.e. token key. secret: str The value for the OAuth token secret. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' oauth_input_params: OAuthInputParams OAuth input parameters. """ def __init__(self, key=None, secret=None, scopes=None, oauth_input_params=None): self.key = key self.secret = secret self.scopes = scopes or [] self.oauth_input_params = oauth_input_params def __str__(self): return self.get_token_string() def get_token_string(self): """Returns the token string. The token string returned is of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. Returns: A token string of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. If self.secret is absent, it just returns oauth_token=[0]. If self.key is absent, it just returns oauth_token_secret=[1]. If both are absent, it returns None. """ if self.key and self.secret: return urllib.urlencode({'oauth_token': self.key, 'oauth_token_secret': self.secret}) elif self.key: return 'oauth_token=%s' % self.key elif self.secret: return 'oauth_token_secret=%s' % self.secret else: return None def set_token_string(self, token_string): """Sets the token key and secret from the token string. Args: token_string: str Token string of form oauth_token=[0]&oauth_token_secret=[1]. If oauth_token is not present, self.key will be None. If oauth_token_secret is not present, self.secret will be None. """ token_params = cgi.parse_qs(token_string, keep_blank_values=False) if 'oauth_token' in token_params: self.key = token_params['oauth_token'][0] if 'oauth_token_secret' in token_params: self.secret = token_params['oauth_token_secret'][0] def GetAuthHeader(self, http_method, http_url, realm=''): """Get the authentication header. Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. realm: string (default='') realm parameter to be included in the authorization header. Returns: dict Header to be sent with every subsequent request after authentication. """ if isinstance(http_url, types.StringTypes): http_url = atom.url.parse_url(http_url) header = None token = None if self.key or self.secret: token = oauth.OAuthToken(self.key, self.secret) oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.oauth_input_params.GetConsumer(), token=token, http_url=str(http_url), http_method=http_method, parameters=http_url.params) oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(), self.oauth_input_params.GetConsumer(), token) header = oauth_request.to_header(realm=realm) header['Authorization'] = header['Authorization'].replace('+', '%2B') return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers) def valid_for_scope(self, url): if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class SecureAuthSubToken(AuthSubToken): """Stores the rsa private key, token, and scopes for the secure AuthSub token. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the secure AuthSub signature to be added to the authorization header is dependent on the request parameters. Attributes: rsa_key: string The RSA private key in PEM format that the token will use to sign requests token_string: string (optional) The value for the AuthSub token. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, rsa_key, token_string=None, scopes=None): self.rsa_key = keyfactory.parsePEMKey(rsa_key) self.token_string = token_string or '' self.scopes = scopes or [] def __str__(self): return self.get_token_string() def get_token_string(self): return str(self.token_string) def set_token_string(self, token_string): self.token_string = token_string def GetAuthHeader(self, http_method, http_url): """Generates the Authorization header. The form of the secure AuthSub Authorization header is Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig" and data represents a string in the form data = http_method http_url timestamp nonce Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. Returns: dict Header to be sent with every subsequent request after authentication. """ timestamp = int(math.floor(time.time())) nonce = '%lu' % random.randrange(1, 2**64) data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce) sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data)) header = {'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' % (AUTHSUB_AUTH_LABEL, self.token_string, data, sig)} return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers)
Python
#!/usr/bin/python # # Copyright (C) 2006 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 classes representing Google Data elements. Extends Atom classes to add Google Data specific elements. """ __author__ = 'api.jscudder (Jeffrey Scudder)' import os import atom try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree # XML namespaces which are often used in GData entities. GDATA_NAMESPACE = 'http://schemas.google.com/g/2005' GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s' OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/' OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s' BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch' GACL_NAMESPACE = 'http://schemas.google.com/acl/2007' GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s' # Labels used in batch request entries to specify the desired CRUD operation. BATCH_INSERT = 'insert' BATCH_UPDATE = 'update' BATCH_DELETE = 'delete' BATCH_QUERY = 'query' class Error(Exception): pass class MissingRequiredParameters(Error): pass class MediaSource(object): """GData Entries can refer to media sources, so this class provides a place to store references to these objects along with some metadata. """ def __init__(self, file_handle=None, content_type=None, content_length=None, file_path=None, file_name=None): """Creates an object of type MediaSource. Args: file_handle: A file handle pointing to the file to be encapsulated in the MediaSource content_type: string The MIME type of the file. Required if a file_handle is given. content_length: int The size of the file. Required if a file_handle is given. file_path: string (optional) A full path name to the file. Used in place of a file_handle. file_name: string The name of the file without any path information. Required if a file_handle is given. """ self.file_handle = file_handle self.content_type = content_type self.content_length = content_length self.file_name = file_name if (file_handle is None and content_type is not None and file_path is not None): self.setFile(file_path, content_type) def setFile(self, file_name, content_type): """A helper function which can create a file handle from a given filename and set the content type and length all at once. Args: file_name: string The path and file name to the file containing the media content_type: string A MIME type representing the type of the media """ self.file_handle = open(file_name, 'rb') self.content_type = content_type self.content_length = os.path.getsize(file_name) self.file_name = os.path.basename(file_name) class LinkFinder(atom.LinkFinder): """An "interface" providing methods to find link elements GData Entry elements often contain multiple links which differ in the rel attribute or content type. Often, developers are interested in a specific type of link so this class provides methods to find specific classes of links. This class is used as a mixin in GData entries. """ def GetSelfLink(self): """Find the first link with rel set to 'self' Returns: An atom.Link or none if none of the links had rel equal to 'self' """ for a_link in self.link: if a_link.rel == 'self': return a_link return None def GetEditLink(self): for a_link in self.link: if a_link.rel == 'edit': return a_link return None def GetEditMediaLink(self): """The Picasa API mistakenly returns media-edit rather than edit-media, but this may change soon. """ for a_link in self.link: if a_link.rel == 'edit-media': return a_link if a_link.rel == 'media-edit': return a_link return None def GetHtmlLink(self): """Find the first link with rel of alternate and type of text/html Returns: An atom.Link or None if no links matched """ for a_link in self.link: if a_link.rel == 'alternate' and a_link.type == 'text/html': return a_link return None def GetPostLink(self): """Get a link containing the POST target URL. The POST target URL is used to insert new entries. Returns: A link object with a rel matching the POST type. """ for a_link in self.link: if a_link.rel == 'http://schemas.google.com/g/2005#post': return a_link return None def GetAclLink(self): for a_link in self.link: if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList': return a_link return None def GetFeedLink(self): for a_link in self.link: if a_link.rel == 'http://schemas.google.com/g/2005#feed': return a_link return None def GetNextLink(self): for a_link in self.link: if a_link.rel == 'next': return a_link return None def GetPrevLink(self): for a_link in self.link: if a_link.rel == 'previous': return a_link return None class TotalResults(atom.AtomBase): """opensearch:TotalResults for a GData feed""" _tag = 'totalResults' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def TotalResultsFromString(xml_string): return atom.CreateClassFromXMLString(TotalResults, xml_string) class StartIndex(atom.AtomBase): """The opensearch:startIndex element in GData feed""" _tag = 'startIndex' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def StartIndexFromString(xml_string): return atom.CreateClassFromXMLString(StartIndex, xml_string) class ItemsPerPage(atom.AtomBase): """The opensearch:itemsPerPage element in GData feed""" _tag = 'itemsPerPage' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ItemsPerPageFromString(xml_string): return atom.CreateClassFromXMLString(ItemsPerPage, xml_string) class ExtendedProperty(atom.AtomBase): """The Google Data extendedProperty element. Used to store arbitrary key-value information specific to your application. The value can either be a text string stored as an XML attribute (.value), or an XML node (XmlBlob) as a child element. This element is used in the Google Calendar data API and the Google Contacts data API. """ _tag = 'extendedProperty' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' def __init__(self, name=None, value=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GetXmlBlobExtensionElement(self): """Returns the XML blob as an atom.ExtensionElement. Returns: An atom.ExtensionElement representing the blob's XML, or None if no blob was set. """ if len(self.extension_elements) < 1: return None else: return self.extension_elements[0] def GetXmlBlobString(self): """Returns the XML blob as a string. Returns: A string containing the blob's XML, or None if no blob was set. """ blob = self.GetXmlBlobExtensionElement() if blob: return blob.ToString() return None def SetXmlBlob(self, blob): """Sets the contents of the extendedProperty to XML as a child node. Since the extendedProperty is only allowed one child element as an XML blob, setting the XML blob will erase any preexisting extension elements in this object. Args: blob: str, ElementTree Element or atom.ExtensionElement representing the XML blob stored in the extendedProperty. """ # Erase any existing extension_elements, clears the child nodes from the # extendedProperty. self.extension_elements = [] if isinstance(blob, atom.ExtensionElement): self.extension_elements.append(blob) elif ElementTree.iselement(blob): self.extension_elements.append(atom._ExtensionElementFromElementTree( blob)) else: self.extension_elements.append(atom.ExtensionElementFromString(blob)) def ExtendedPropertyFromString(xml_string): return atom.CreateClassFromXMLString(ExtendedProperty, xml_string) class GDataEntry(atom.Entry, LinkFinder): """Extends Atom Entry to provide data processing""" _tag = atom.Entry._tag _namespace = atom.Entry._namespace _children = atom.Entry._children.copy() _attributes = atom.Entry._attributes.copy() def __GetId(self): return self.__id # This method was created to strip the unwanted whitespace from the id's # text node. def __SetId(self, id): self.__id = id if id is not None and id.text is not None: self.__id.text = id.text.strip() id = property(__GetId, __SetId) def IsMedia(self): """Determines whether or not an entry is a GData Media entry. """ if (self.GetEditMediaLink()): return True else: return False def GetMediaURL(self): """Returns the URL to the media content, if the entry is a media entry. Otherwise returns None. """ if not self.IsMedia(): return None else: return self.content.src def GDataEntryFromString(xml_string): """Creates a new GDataEntry instance given a string of XML.""" return atom.CreateClassFromXMLString(GDataEntry, xml_string) class GDataFeed(atom.Feed, LinkFinder): """A Feed from a GData service""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = atom.Feed._children.copy() _attributes = atom.Feed._attributes.copy() _children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results', TotalResults) _children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index', StartIndex) _children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page', ItemsPerPage) # Add a conversion rule for atom:entry to make it into a GData # Entry. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry]) def __GetId(self): return self.__id def __SetId(self, id): self.__id = id if id is not None and id.text is not None: self.__id.text = id.text.strip() id = property(__GetId, __SetId) def __GetGenerator(self): return self.__generator def __SetGenerator(self, generator): self.__generator = generator if generator is not None: self.__generator.text = generator.text.strip() generator = property(__GetGenerator, __SetGenerator) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Source Args: author: list (optional) A list of Author instances which belong to this class. category: list (optional) A list of Category instances contributor: list (optional) A list on Contributor instances generator: Generator (optional) icon: Icon (optional) id: Id (optional) The entry's Id element link: list (optional) A list of Link instances logo: Logo (optional) rights: Rights (optional) The entry's Rights element subtitle: Subtitle (optional) The entry's subtitle element title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.generator = generator self.icon = icon self.id = atom_id self.link = link or [] self.logo = logo self.rights = rights self.subtitle = subtitle self.title = title self.updated = updated self.entry = entry or [] self.total_results = total_results self.start_index = start_index self.items_per_page = items_per_page self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GDataFeedFromString(xml_string): return atom.CreateClassFromXMLString(GDataFeed, xml_string) class BatchId(atom.AtomBase): _tag = 'id' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def BatchIdFromString(xml_string): return atom.CreateClassFromXMLString(BatchId, xml_string) class BatchOperation(atom.AtomBase): _tag = 'operation' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, op_type=None, extension_elements=None, extension_attributes=None, text=None): self.type = op_type atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchOperationFromString(xml_string): return atom.CreateClassFromXMLString(BatchOperation, xml_string) class BatchStatus(atom.AtomBase): """The batch:status element present in a batch response entry. A status element contains the code (HTTP response code) and reason as elements. In a single request these fields would be part of the HTTP response, but in a batch request each Entry operation has a corresponding Entry in the response feed which includes status information. See http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _tag = 'status' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['code'] = 'code' _attributes['reason'] = 'reason' _attributes['content-type'] = 'content_type' def __init__(self, code=None, reason=None, content_type=None, extension_elements=None, extension_attributes=None, text=None): self.code = code self.reason = reason self.content_type = content_type atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchStatusFromString(xml_string): return atom.CreateClassFromXMLString(BatchStatus, xml_string) class BatchEntry(GDataEntry): """An atom:entry for use in batch requests. The BatchEntry contains additional members to specify the operation to be performed on this entry and a batch ID so that the server can reference individual operations in the response feed. For more information, see: http://code.google.com/apis/gdata/batch.html """ _tag = GDataEntry._tag _namespace = GDataEntry._namespace _children = GDataEntry._children.copy() _children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation) _children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId) _children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus) _attributes = GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, batch_operation=None, batch_id=None, batch_status=None, extension_elements=None, extension_attributes=None, text=None): self.batch_operation = batch_operation self.batch_id = batch_id self.batch_status = batch_status GDataEntry.__init__(self, author=author, category=category, content=content, contributor=contributor, atom_id=atom_id, link=link, published=published, rights=rights, source=source, summary=summary, control=control, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchEntryFromString(xml_string): return atom.CreateClassFromXMLString(BatchEntry, xml_string) class BatchInterrupted(atom.AtomBase): """The batch:interrupted element sent if batch request was interrupted. Only appears in a feed if some of the batch entries could not be processed. See: http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _tag = 'interrupted' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['reason'] = 'reason' _attributes['success'] = 'success' _attributes['failures'] = 'failures' _attributes['parsed'] = 'parsed' def __init__(self, reason=None, success=None, failures=None, parsed=None, extension_elements=None, extension_attributes=None, text=None): self.reason = reason self.success = success self.failures = failures self.parsed = parsed atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchInterruptedFromString(xml_string): return atom.CreateClassFromXMLString(BatchInterrupted, xml_string) class BatchFeed(GDataFeed): """A feed containing a list of batch request entries.""" _tag = GDataFeed._tag _namespace = GDataFeed._namespace _children = GDataFeed._children.copy() _attributes = GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry]) _children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, interrupted=None, extension_elements=None, extension_attributes=None, text=None): self.interrupted = interrupted GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def AddBatchEntry(self, entry=None, id_url_string=None, batch_id_string=None, operation_string=None): """Logic for populating members of a BatchEntry and adding to the feed. If the entry is not a BatchEntry, it is converted to a BatchEntry so that the batch specific members will be present. The id_url_string can be used in place of an entry if the batch operation applies to a URL. For example query and delete operations require just the URL of an entry, no body is sent in the HTTP request. If an id_url_string is sent instead of an entry, a BatchEntry is created and added to the feed. This method also assigns the desired batch id to the entry so that it can be referenced in the server's response. If the batch_id_string is None, this method will assign a batch_id to be the index at which this entry will be in the feed's entry list. Args: entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The entry which will be sent to the server as part of the batch request. The item must have a valid atom id so that the server knows which entry this request references. id_url_string: str (optional) The URL of the entry to be acted on. You can find this URL in the text member of the atom id for an entry. If an entry is not sent, this id will be used to construct a new BatchEntry which will be added to the request feed. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. operation_string: str (optional) The desired batch operation which will set the batch_operation.type member of the entry. Options are 'insert', 'update', 'delete', and 'query' Raises: MissingRequiredParameters: Raised if neither an id_ url_string nor an entry are provided in the request. Returns: The added entry. """ if entry is None and id_url_string is None: raise MissingRequiredParameters('supply either an entry or URL string') if entry is None and id_url_string is not None: entry = BatchEntry(atom_id=atom.Id(text=id_url_string)) # TODO: handle cases in which the entry lacks batch_... members. #if not isinstance(entry, BatchEntry): # Convert the entry to a batch entry. if batch_id_string is not None: entry.batch_id = BatchId(text=batch_id_string) elif entry.batch_id is None or entry.batch_id.text is None: entry.batch_id = BatchId(text=str(len(self.entry))) if operation_string is not None: entry.batch_operation = BatchOperation(op_type=operation_string) self.entry.append(entry) return entry def AddInsert(self, entry, batch_id_string=None): """Add an insert request to the operations in this batch request feed. If the entry doesn't yet have an operation or a batch id, these will be set to the insert operation and a batch_id specified as a parameter. Args: entry: BatchEntry The entry which will be sent in the batch feed as an insert request. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. """ entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_INSERT) def AddUpdate(self, entry, batch_id_string=None): """Add an update request to the list of batch operations in this feed. Sets the operation type of the entry to insert if it is not already set and assigns the desired batch id to the entry so that it can be referenced in the server's response. Args: entry: BatchEntry The entry which will be sent to the server as an update (HTTP PUT) request. The item must have a valid atom id so that the server knows which entry to replace. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. See also comments for AddInsert. """ entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_UPDATE) def AddDelete(self, url_string=None, entry=None, batch_id_string=None): """Adds a delete request to the batch request feed. This method takes either the url_string which is the atom id of the item to be deleted, or the entry itself. The atom id of the entry must be present so that the server knows which entry should be deleted. Args: url_string: str (optional) The URL of the entry to be deleted. You can find this URL in the text member of the atom id for an entry. entry: BatchEntry (optional) The entry to be deleted. batch_id_string: str (optional) Raises: MissingRequiredParameters: Raised if neither a url_string nor an entry are provided in the request. """ entry = self.AddBatchEntry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_DELETE) def AddQuery(self, url_string=None, entry=None, batch_id_string=None): """Adds a query request to the batch request feed. This method takes either the url_string which is the query URL whose results will be added to the result feed. The query URL will be encapsulated in a BatchEntry, and you may pass in the BatchEntry with a query URL instead of sending a url_string. Args: url_string: str (optional) entry: BatchEntry (optional) batch_id_string: str (optional) Raises: MissingRequiredParameters """ entry = self.AddBatchEntry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_QUERY) def GetBatchLink(self): for link in self.link: if link.rel == 'http://schemas.google.com/g/2005#batch': return link return None def BatchFeedFromString(xml_string): return atom.CreateClassFromXMLString(BatchFeed, xml_string) class EntryLink(atom.AtomBase): """The gd:entryLink element""" _tag = 'entryLink' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() # The entry used to be an atom.Entry, now it is a GDataEntry. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry) _attributes['rel'] = 'rel' _attributes['readOnly'] = 'read_only' _attributes['href'] = 'href' def __init__(self, href=None, read_only=None, rel=None, entry=None, extension_elements=None, extension_attributes=None, text=None): self.href = href self.read_only = read_only self.rel = rel self.entry = entry self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EntryLinkFromString(xml_string): return atom.CreateClassFromXMLString(EntryLink, xml_string) class FeedLink(atom.AtomBase): """The gd:feedLink element""" _tag = 'feedLink' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed) _attributes['rel'] = 'rel' _attributes['readOnly'] = 'read_only' _attributes['countHint'] = 'count_hint' _attributes['href'] = 'href' def __init__(self, count_hint=None, href=None, read_only=None, rel=None, feed=None, extension_elements=None, extension_attributes=None, text=None): self.count_hint = count_hint self.href = href self.read_only = read_only self.rel = rel self.feed = feed self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def FeedLinkFromString(xml_string): return atom.CreateClassFromXMLString(EntryLink, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2006,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. """GDataService provides CRUD ops. and programmatic login for GData services. Error: A base exception class for all exceptions in the gdata_client module. CaptchaRequired: This exception is thrown when a login attempt results in a captcha challenge from the ClientLogin service. When this exception is thrown, the captcha_token and captcha_url are set to the values provided in the server's response. BadAuthentication: Raised when a login attempt is made with an incorrect username or password. NotAuthenticated: Raised if an operation requiring authentication is called before a user has authenticated. NonAuthSubToken: Raised if a method to modify an AuthSub token is used when the user is either not authenticated or is authenticated through another authentication mechanism. NonOAuthToken: Raised if a method to modify an OAuth token is used when the user is either not authenticated or is authenticated through another authentication mechanism. RequestError: Raised if a CRUD request returned a non-success code. UnexpectedReturnType: Raised if the response from the server was not of the desired type. For example, this would be raised if the server sent a feed when the client requested an entry. GDataService: Encapsulates user credentials needed to perform insert, update and delete operations with the GData API. An instance can perform user authentication, query, insertion, deletion, and update. Query: Eases query URI creation by allowing URI parameters to be set as dictionary attributes. For example a query with a feed of '/base/feeds/snippets' and ['bq'] set to 'digital camera' will produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is called on it. """ __author__ = 'api.jscudder (Jeffrey Scudder)' import re import urllib import urlparse try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom.service import gdata import atom import atom.http_interface import atom.token_store import gdata.auth AUTH_SERVER_HOST = 'https://www.google.com' # When requesting an AuthSub token, it is often helpful to track the scope # which is being requested. One way to accomplish this is to add a URL # parameter to the 'next' URL which contains the requested scope. This # constant is the default name (AKA key) for the URL parameter. SCOPE_URL_PARAM_NAME = 'authsub_token_scope' # When requesting an OAuth access token or authorization of an existing OAuth # request token, it is often helpful to track the scope(s) which is/are being # requested. One way to accomplish this is to add a URL parameter to the # 'callback' URL which contains the requested scope. This constant is the # default name (AKA key) for the URL parameter. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope' # Maps the service names used in ClientLogin to scope URLs. CLIENT_LOGIN_SCOPES = { 'cl': [ # Google Calendar 'https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'], 'gbase': [ # Google Base 'http://base.google.com/base/feeds/', 'http://www.google.com/base/feeds/'], 'blogger': [ # Blogger 'http://www.blogger.com/feeds/'], 'codesearch': [ # Google Code Search 'http://www.google.com/codesearch/feeds/'], 'cp': [ # Contacts API 'https://www.google.com/m8/feeds/', 'http://www.google.com/m8/feeds/'], 'finance': [ # Google Finance 'http://finance.google.com/finance/feeds/'], 'health': [ # Google Health 'https://www.google.com/health/feeds/'], 'writely': [ # Documents List API 'https://docs.google.com/feeds/', 'http://docs.google.com/feeds/'], 'lh2': [ # Picasa Web Albums 'http://picasaweb.google.com/data/'], 'apps': [ # Google Apps Provisioning API 'http://www.google.com/a/feeds/', 'https://www.google.com/a/feeds/', 'http://apps-apis.google.com/a/feeds/', 'https://apps-apis.google.com/a/feeds/'], 'weaver': [ # Health H9 Sandbox 'https://www.google.com/h9/'], 'wise': [ # Spreadsheets Data API 'https://spreadsheets.google.com/feeds/', 'http://spreadsheets.google.com/feeds/'], 'sitemaps': [ # Google Webmaster Tools 'https://www.google.com/webmasters/tools/feeds/'], 'youtube': [ # YouTube 'http://gdata.youtube.com/feeds/api/', 'http://uploads.gdata.youtube.com/feeds/api', 'http://gdata.youtube.com/action/GetUploadToken']} def lookup_scopes(service_name): """Finds the scope URLs for the desired service. In some cases, an unknown service may be used, and in those cases this function will return None. """ if service_name in CLIENT_LOGIN_SCOPES: return CLIENT_LOGIN_SCOPES[service_name] return None # Module level variable specifies which module should be used by GDataService # objects to make HttpRequests. This setting can be overridden on each # instance of GDataService. # This module level variable is deprecated. Reassign the http_client member # of a GDataService object instead. http_request_handler = atom.service class Error(Exception): pass class CaptchaRequired(Error): pass class BadAuthentication(Error): pass class NotAuthenticated(Error): pass class NonAuthSubToken(Error): pass class NonOAuthToken(Error): pass class RequestError(Error): pass class UnexpectedReturnType(Error): pass class BadAuthenticationServiceURL(Error): pass class FetchingOAuthRequestTokenFailed(RequestError): pass class TokenUpgradeFailed(RequestError): pass class RevokingOAuthTokenFailed(RequestError): pass class AuthorizationRequired(Error): pass class TokenHadNoScope(Error): pass class GDataService(atom.service.AtomService): """Contains elements needed for GData login and CRUD request headers. Maintains additional headers (tokens for example) needed for the GData services to allow a user to perform inserts, updates, and deletes. """ # The hander member is deprecated, use http_client instead. handler = None # The auth_token member is deprecated, use the token_store instead. auth_token = None # The tokens dict is deprecated in favor of the token_store. tokens = None def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE', service=None, auth_service_url=None, source=None, server=None, additional_headers=None, handler=None, tokens=None, http_client=None, token_store=None): """Creates an object of type GDataService. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. account_type: string (optional) The type of account to use. Use 'GOOGLE' for regular Google accounts or 'HOSTED' for Google Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED account first and, if it doesn't exist, try finding a regular GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'. service: string (optional) The desired service for which credentials will be obtained. auth_service_url: string (optional) User-defined auth token request URL allows users to explicitly specify where to send auth token requests. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'base.google.com'. additional_headers: dictionary (optional) Any additional headers which should be included with CRUD operations. handler: module (optional) This parameter is deprecated and has been replaced by http_client. tokens: This parameter is deprecated, calls should be made to token_store instead. http_client: An object responsible for making HTTP requests using a request method. If none is provided, a new instance of atom.http.ProxiedHttpClient will be used. token_store: Keeps a collection of authorization tokens which can be applied to requests for a specific URLs. Critical methods are find_token based on a URL (atom.url.Url or a string), add_token, and remove_token. """ atom.service.AtomService.__init__(self, http_client=http_client, token_store=token_store) self.email = email self.password = password self.account_type = account_type self.service = service self.auth_service_url = auth_service_url self.server = server self.additional_headers = additional_headers or {} self._oauth_input_params = None self.__SetSource(source) self.__captcha_token = None self.__captcha_url = None self.__gsessionid = None if http_request_handler.__name__ == 'gdata.urlfetch': import gdata.alt.appengine self.http_client = gdata.alt.appengine.AppEngineHttpClient() # Define properties for GDataService def _SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self.SetAuthSubToken(auth_token, scopes=scopes) def __SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self._SetAuthSubToken(auth_token, scopes=scopes) def _GetAuthToken(self): """Returns the auth token used for authenticating requests. Returns: string """ current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if hasattr(token, 'auth_header'): return token.auth_header return None def _GetCaptchaToken(self): """Returns a captcha token if the most recent login attempt generated one. The captcha token is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_token def __GetCaptchaToken(self): return self._GetCaptchaToken() captcha_token = property(__GetCaptchaToken, doc="""Get the captcha token for a login request.""") def _GetCaptchaURL(self): """Returns the URL of the captcha image if a login attempt generated one. The captcha URL is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_url def __GetCaptchaURL(self): return self._GetCaptchaURL() captcha_url = property(__GetCaptchaURL, doc="""Get the captcha URL for a login request.""") def SetOAuthInputParameters(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, two_legged_oauth=False): """Sets parameters required for using OAuth authentication mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. two_legged_oauth: string (default=False) Enables two-legged OAuth process. """ self._oauth_input_params = gdata.auth.OAuthInputParams( signature_method, consumer_key, consumer_secret=consumer_secret, rsa_key=rsa_key) if two_legged_oauth: oauth_token = gdata.auth.OAuthToken( oauth_input_params=self._oauth_input_params) self.SetOAuthToken(oauth_token) def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None, request_url='%s/accounts/OAuthGetRequestToken' % \ AUTH_SERVER_HOST): """Fetches OAuth request token and returns it. Args: scopes: string or list of string base URL(s) of the service(s) to be accessed. If None, then this method tries to determine the scope(s) from the current service. extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} request_url: Request token URL. The default is 'https://www.google.com/accounts/OAuthGetRequestToken'. Returns: The fetched request token as a gdata.auth.OAuthToken object. Raises: FetchingOAuthRequestTokenFailed if the server responded to the request with an error. """ if scopes is None: scopes = lookup_scopes(self.service) if not isinstance(scopes, (list, tuple)): scopes = [scopes,] request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl( self._oauth_input_params, scopes, request_token_url=request_url, extra_parameters=extra_parameters) response = self.http_client.request('GET', str(request_token_url)) if response.status == 200: token = gdata.auth.OAuthToken() token.set_token_string(response.read()) token.scopes = scopes token.oauth_input_params = self._oauth_input_params return token error = { 'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response.read() } raise FetchingOAuthRequestTokenFailed(error) def SetOAuthToken(self, oauth_token): """Attempts to set the current token and add it to the token store. The oauth_token can be any OAuth token i.e. unauthorized request token, authorized request token or access token. This method also attempts to add the token to the token store. Use this method any time you want the current token to point to the oauth_token passed. For e.g. call this method with the request token you receive from FetchOAuthRequestToken. Args: request_token: gdata.auth.OAuthToken OAuth request token. """ if self.auto_set_current_token: self.current_token = oauth_token if self.auto_store_tokens: self.token_store.add_token(oauth_token) def GenerateOAuthAuthorizationURL( self, request_token=None, callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME, request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. request_url: Authorization URL. The default is 'https://www.google.com/accounts/OAuthAuthorizeToken'. Returns: A string URL at which the user is required to login. Raises: NonOAuthToken if the user's request token is not an OAuth token or if a request token was not available. """ if request_token and not isinstance(request_token, gdata.auth.OAuthToken): raise NonOAuthToken if not request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): request_token = token if not request_token: raise NonOAuthToken return str(gdata.auth.GenerateOAuthAuthorizationUrl( request_token, authorization_url=request_url, callback_url=callback_url, extra_params=extra_params, include_scopes_in_callback=include_scopes_in_callback, scopes_param_prefix=scopes_param_prefix)) def UpgradeToOAuthAccessToken(self, authorized_request_token=None, request_url='%s/accounts/OAuthGetAccessToken' \ % AUTH_SERVER_HOST, oauth_version='1.0'): """Upgrades the authorized request token to an access token. Args: authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. oauth_version: str (default='1.0') oauth_version parameter. All other 'oauth_' parameters are added by default. This parameter too, is added by default but here you can override it's value. request_url: Access token URL. The default is 'https://www.google.com/accounts/OAuthGetAccessToken'. Raises: NonOAuthToken if the user's authorized request token is not an OAuth token or if an authorized request token was not available. TokenUpgradeFailed if the server responded to the request with an error. """ if (authorized_request_token and not isinstance(authorized_request_token, gdata.auth.OAuthToken)): raise NonOAuthToken if not authorized_request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): authorized_request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): authorized_request_token = token if not authorized_request_token: raise NonOAuthToken access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl( authorized_request_token, self._oauth_input_params, access_token_url=request_url, oauth_version=oauth_version) response = self.http_client.request('GET', str(access_token_url)) if response.status == 200: token = gdata.auth.OAuthTokenFromHttpBody(response.read()) token.scopes = authorized_request_token.scopes token.oauth_input_params = authorized_request_token.oauth_input_params self.SetOAuthToken(token) else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response.read()}) def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \ AUTH_SERVER_HOST): """Revokes an existing OAuth token. request_url: Token revoke URL. The default is 'https://www.google.com/accounts/AuthSubRevokeToken'. Raises: NonOAuthToken if the user's auth token is not an OAuth token. RevokingOAuthTokenFailed if request for revoking an OAuth token failed. """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.OAuthToken): raise NonOAuthToken response = token.perform_request(self.http_client, 'GET', request_url, headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) else: raise RevokingOAuthTokenFailed def GetAuthSubToken(self): """Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed. This method examines the current_token to see if it is an AuthSubToken or SecureAuthSubToken. If not, it searches the token_store for a token which matches the current scope. The current scope is determined by the service name string member. Returns: If the current_token is set to an AuthSubToken/SecureAuthSubToken, return the token string. If there is no current_token, a token string for a token which matches the service object's default scope is returned. If there are no tokens valid for the scope, returns None. """ if isinstance(self.current_token, gdata.auth.AuthSubToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.AuthSubToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetAuthSubToken(self, token, scopes=None, rsa_key=None): """Sets the token sent in requests to an AuthSub token. Sets the current_token and attempts to add the token to the token_store. Only use this method if you have received a token from the AuthSub service. The auth token is set automatically when UpgradeToSessionToken() is used. See documentation for Google AuthSub here: http://code.google.com/apis/accounts/AuthForWebApps.html Args: token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string The token returned by the AuthSub service. If the token is an AuthSubToken or SecureAuthSubToken, the scope information stored in the token is used. If the token is a string, the scopes parameter is used to determine the valid scopes. scopes: list of URLs for which the token is valid. This is only used if the token parameter is a string. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. This parameter is necessary if the token is a string representing a secure token. """ if not isinstance(token, gdata.auth.AuthSubToken): token_string = token if rsa_key: token = gdata.auth.SecureAuthSubToken(rsa_key) else: token = gdata.auth.AuthSubToken() token.set_token_string(token_string) # If no scopes were set for the token, use the scopes passed in, or # try to determine the scopes based on the current service name. If # all else fails, set the token to match all requests. if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) def GetClientLoginToken(self): """Returns the token string for the current token or a token matching the service scope. If the current_token is a ClientLoginToken, the token string for the current token is returned. If the current_token is not set, this method searches for a token in the token_store which is valid for the service object's current scope. The current scope is determined by the service name string member. The token string is the end of the Authorization header, it doesn not include the ClientLogin label. """ if isinstance(self.current_token, gdata.auth.ClientLoginToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetClientLoginToken(self, token, scopes=None): """Sets the token sent in requests to a ClientLogin token. This method sets the current_token to a new ClientLoginToken and it also attempts to add the ClientLoginToken to the token_store. Only use this method if you have received a token from the ClientLogin service. The auth_token is set automatically when ProgrammaticLogin() is used. See documentation for Google ClientLogin here: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html Args: token: string or instance of a ClientLoginToken. """ if not isinstance(token, gdata.auth.ClientLoginToken): token_string = token token = gdata.auth.ClientLoginToken() token.set_token_string(token_string) if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) # Private methods to create the source property. def __GetSource(self): return self.__source def __SetSource(self, new_source): self.__source = new_source # Update the UserAgent header to include the new application name. self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % ( self.__source,) source = property(__GetSource, __SetSource, doc="""The source is the name of the application making the request. It should be in the form company_id-app_name-app_version""") # Authentication operations def ProgrammaticLogin(self, captcha_token=None, captcha_response=None): """Authenticates the user and sets the GData Auth token. Login retreives a temporary auth token which must be used with all requests to GData services. The auth token is stored in the GData client object. Login is also used to respond to a captcha challenge. If the user's login attempt failed with a CaptchaRequired error, the user can respond by calling Login with the captcha token and the answer to the challenge. Args: captcha_token: string (optional) The identifier for the captcha challenge which was presented to the user. captcha_response: string (optional) The user's answer to the captch challenge. Raises: CaptchaRequired if the login service will require a captcha response BadAuthentication if the login service rejected the username or password Error if the login service responded with a 403 different from the above """ request_body = gdata.auth.generate_client_login_request_body(self.email, self.password, self.service, self.source, self.account_type, captcha_token, captcha_response) # If the user has defined their own authentication service URL, # send the ClientLogin requests to this URL: if not self.auth_service_url: auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin' else: auth_request_url = self.auth_service_url auth_response = self.http_client.request('POST', auth_request_url, data=request_body, headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = auth_response.read() if auth_response.status == 200: # TODO: insert the token into the token_store directly. self.SetClientLoginToken( gdata.auth.get_client_login_token(response_body)) self.__captcha_token = None self.__captcha_url = None elif auth_response.status == 403: # Examine each line to find the error type and the captcha token and # captch URL if they are present. captcha_parameters = gdata.auth.get_captcha_challenge(response_body, captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST) if captcha_parameters: self.__captcha_token = captcha_parameters['token'] self.__captcha_url = captcha_parameters['url'] raise CaptchaRequired, 'Captcha Required' elif response_body.splitlines()[0] == 'Error=BadAuthentication': self.__captcha_token = None self.__captcha_url = None raise BadAuthentication, 'Incorrect username or password' else: self.__captcha_token = None self.__captcha_url = None raise Error, 'Server responded with a 403 code' elif auth_response.status == 302: self.__captcha_token = None self.__captcha_url = None # Google tries to redirect all bad URLs back to # http://www.google.<locale>. If a redirect # attempt is made, assume the user has supplied an incorrect authentication URL raise BadAuthenticationServiceURL, 'Server responded with a 302 code.' def ClientLogin(self, username, password, account_type=None, service=None, auth_service_url=None, source=None, captcha_token=None, captcha_response=None): """Convenience method for authenticating using ProgrammaticLogin. Sets values for email, password, and other optional members. Args: username: password: account_type: string (optional) service: string (optional) auth_service_url: string (optional) captcha_token: string (optional) captcha_response: string (optional) """ self.email = username self.password = password if account_type: self.account_type = account_type if service: self.service = service if source: self.source = source if auth_service_url: self.auth_service_url = auth_service_url self.ProgrammaticLogin(captcha_token, captcha_response) def GenerateAuthSubURL(self, next, scope, secure=False, session=True, domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: string The URL user will be sent to after logging in. scope: string or list of strings. The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. """ if not isinstance(scope, (list, tuple)): scope = (scope,) return gdata.auth.generate_auth_sub_url(next, scope, secure=secure, session=session, request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, domain=domain) def UpgradeToSessionToken(self, token=None): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken (optional) which is good for a single use but can be upgraded to a session token. If no token is passed in, the token is found by looking in the token_store by looking for a token for the current scope. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token TokenUpgradeFailed if the server responded to the request with an error. """ if token is None: scopes = lookup_scopes(self.service) if scopes: token = self.token_store.find_token(scopes[0]) else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken self.SetAuthSubToken(self.upgrade_to_session_token(token)) def upgrade_to_session_token(self, token): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken which is good for a single use but can be upgraded to a session token. Returns: The upgraded token as a gdata.auth.AuthSubToken object. Raises: TokenUpgradeFailed if the server responded to the request with an error. """ response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = response.read() if response.status == 200: token.set_token_string( gdata.auth.token_from_http_body(response_body)) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response_body}) def RevokeAuthSubToken(self): """Revokes an existing AuthSub token. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) def AuthSubTokenInfo(self): """Fetches the AuthSub token's metadata from the server. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', headers={'Content-Type':'application/x-www-form-urlencoded'}) result_body = response.read() if response.status == 200: return result_body else: raise RequestError, {'status': response.status, 'body': result_body} # CRUD operations def Get(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None): """Query the GData API with the given URI The uri is the portion of the URI after the server value (ex: www.google.com). To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. redirects_remaining: int (optional) Tracks the number of additional redirects this method will allow. If the service object receives a redirect and remaining is 0, it will not follow the redirect. This was added to avoid infinite redirect loops. encoding: string (optional) The character encoding for the server's response. Default is UTF-8 converter: func (optional) A function which will transform the server's results before it is returned. Example: use GDataFeedFromString to parse the server response as if it were a GDataFeed. Returns: If there is no ResultsTransformer specified in the call, a GDataFeed or GDataEntry depending on which is sent from the server. If the response is niether a feed or entry and there is no ResultsTransformer, return a string. If there is a ResultsTransformer, the returned value will be that of the ResultsTransformer function. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) server_response = self.request('GET', uri, headers=extra_headers) result_body = server_response.read() if server_response.status == 200: if converter: return converter(result_body) # There was no ResultsTransformer specified, so try to convert the # server's response into a GDataFeed. feed = gdata.GDataFeedFromString(result_body) if not feed: # If conversion to a GDataFeed failed, try to convert the server's # response to a GDataEntry. entry = gdata.GDataEntryFromString(result_body) if not entry: # The server's response wasn't a feed, or an entry, so return the # response body as a string. return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, encoding=encoding, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def GetMedia(self, uri, extra_headers=None): """Returns a MediaSource containing media and its metadata from the given URI string. """ response_handle = self.request('GET', uri, headers=extra_headers) return gdata.MediaSource(response_handle, response_handle.getheader( 'Content-Type'), response_handle.getheader('Content-Length')) def GetEntry(self, uri, extra_headers=None): """Query the GData API with the given URI and receive an Entry. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataEntry built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=atom.EntryFromString) if isinstance(result, atom.Entry): return result else: raise UnexpectedReturnType, 'Server did not send an entry' def GetFeed(self, uri, extra_headers=None, converter=gdata.GDataFeedFromString): """Query the GData API with the given URI and receive a Feed. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataFeed built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=converter) if isinstance(result, atom.Feed): return result else: raise UnexpectedReturnType, 'Server did not send a feed' def GetNext(self, feed): """Requests the next 'page' of results in the feed. This method uses the feed's next link to request an additional feed and uses the class of the feed to convert the results of the GET request. Args: feed: atom.Feed or a subclass. The feed should contain a next link and the type of the feed will be applied to the results from the server. The new feed which is returned will be of the same class as this feed which was passed in. Returns: A new feed representing the next set of results in the server's feed. The type of this feed will match that of the feed argument. """ next_link = feed.GetNextLink() # Create a closure which will convert an XML string to the class of # the feed object passed in. def ConvertToFeedClass(xml_string): return atom.CreateClassFromXMLString(feed.__class__, xml_string) # Make a GET request on the next link and use the above closure for the # converted which processes the XML string from the server. if next_link and next_link.href: return GDataService.Get(self, next_link.href, converter=ConvertToFeedClass) else: return None def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert or update data into a GData service at the given URI. Args: data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'POST', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert data into a GData service at the given URI. Args: verb: string, either 'POST' or 'PUT' data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) if data and media_source: if ElementTree.iselement(data): data_str = ElementTree.tostring(data) else: data_str = str(data) multipart = [] multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \ 'Content-Type: application/atom+xml\r\n\r\n') multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \ media_source.content_type+'\r\n\r\n') multipart.append('\r\n--END_OF_PART--\r\n') extra_headers['MIME-version'] = '1.0' extra_headers['Content-Length'] = str(len(multipart[0]) + len(multipart[1]) + len(multipart[2]) + len(data_str) + media_source.content_length) extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART' server_response = self.request(verb, uri, data=[multipart[0], data_str, multipart[1], media_source.file_handle, multipart[2]], headers=extra_headers) result_body = server_response.read() elif media_source or isinstance(data, gdata.MediaSource): if isinstance(data, gdata.MediaSource): media_source = data extra_headers['Content-Length'] = str(media_source.content_length) extra_headers['Content-Type'] = media_source.content_type server_response = self.request(verb, uri, data=media_source.file_handle, headers=extra_headers) result_body = server_response.read() else: http_data = data content_type = 'application/atom+xml' extra_headers['Content-Type'] = content_type server_response = self.request(verb, uri, data=http_data, headers=extra_headers) result_body = server_response.read() # Server returns 201 for most post requests, but when performing a batch # request the server responds with a 200 on success. if server_response.status == 201 or server_response.status == 200: if converter: return converter(result_body) feed = gdata.GDataFeedFromString(result_body) if not feed: entry = gdata.GDataEntryFromString(result_body) if not entry: return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.PostOrPut(self, verb, data, location, extra_headers, url_params, escape_params, redirects_remaining - 1, media_source, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=3, media_source=None, converter=None): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the put succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'PUT', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: True if the entry was deleted. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) server_response = self.request('DELETE', uri, headers=extra_headers) result_body = server_response.read() if server_response.status == 200: return True elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Delete(self, location, extra_headers, url_params, escape_params, redirects_remaining - 1) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def ExtractToken(url, scopes_included_in_next=True): """Gets the AuthSub token from the current page's URL. Designed to be used on the URL that the browser is sent to after the user authorizes this application at the page given by GenerateAuthSubRequestUrl. Args: url: The current page's URL. It should contain the token as a URL parameter. Example: 'http://example.com/?...&token=abcd435' scopes_included_in_next: If True, this function looks for a scope value associated with the token. The scope is a URL parameter with the key set to SCOPE_URL_PARAM_NAME. This parameter should be present if the AuthSub request URL was generated using GenerateAuthSubRequestUrl with include_scope_in_next set to True. Returns: A tuple containing the token string and a list of scope strings for which this token should be valid. If the scope was not included in the URL, the tuple will contain (token, None). """ parsed = urlparse.urlparse(url) token = gdata.auth.AuthSubTokenFromUrl(parsed[4]) scopes = '' if scopes_included_in_next: for pair in parsed[4].split('&'): if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME): scopes = urllib.unquote_plus(pair.split('=')[1]) return (token, scopes.split(' ')) def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False, session=True, request_url='http://www.google.com/accounts/AuthSubRequest', include_scopes_in_next=True): """Creates a URL to request an AuthSub token to access Google services. For more details on AuthSub, see the documentation here: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: The URL where the browser should be sent after the user authorizes the application. This page is responsible for receiving the token which is embeded in the URL as a parameter. scopes: The base URL to which access will be granted. Example: 'http://www.google.com/calendar/feeds' will grant access to all URLs in the Google Calendar data API. If you would like a token for multiple scopes, pass in a list of URL strings. hd: The domain to which the user's account belongs. This is set to the domain name if you are using Google Apps. Example: 'example.org' Defaults to 'default' secure: If set to True, all requests should be signed. The default is False. session: If set to True, the token received by the 'next' URL can be upgraded to a multiuse session token. If session is set to False, the token may only be used once and cannot be upgraded. Default is True. request_url: The base of the URL to which the user will be sent to authorize this application to access their data. The default is 'http://www.google.com/accounts/AuthSubRequest'. include_scopes_in_next: Boolean if set to true, the 'next' parameter will be modified to include the requested scope as a URL parameter. The key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the next URL, is that the page which receives the AuthSub token will be able to tell which URLs the token grants access to. Returns: A URL string to which the browser should be sent. """ if isinstance(scopes, list): scope = ' '.join(scopes) else: scope = scopes if include_scopes_in_next: if next.find('?') > -1: next += '&%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) else: next += '?%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure, session=session, request_url=request_url, domain=hd) class Query(dict): """Constructs a query URL to be used in GET requests Url parameters are created by adding key-value pairs to this object as a dict. For example, to add &max-results=25 to the URL do my_query['max-results'] = 25 Category queries are created by adding category strings to the categories member. All items in the categories list will be concatenated with the / symbol (symbolizing a category x AND y restriction). If you would like to OR 2 categories, append them as one string with a | between the categories. For example, do query.categories.append('Fritz|Laurie') to create a query like this feed/-/Fritz%7CLaurie . This query will look for results in both categories. """ def __init__(self, feed=None, text_query=None, params=None, categories=None): """Constructor for Query Args: feed: str (optional) The path for the feed (Examples: '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full' text_query: str (optional) The contents of the q query parameter. The contents of the text_query are URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items (key-value pairs). categories: list (optional) List of category strings which should be included as query categories. See http://code.google.com/apis/gdata/reference.html#Queries for details. If you want to get results from category A or B (both categories), specify a single list item 'A|B'. """ self.feed = feed self.categories = [] if text_query: self.text_query = text_query if isinstance(params, dict): for param in params: self[param] = params[param] if isinstance(categories, list): for category in categories: self.categories.append(category) def _GetTextQuery(self): if 'q' in self.keys(): return self['q'] else: return None def _SetTextQuery(self, query): self['q'] = query text_query = property(_GetTextQuery, _SetTextQuery, doc="""The feed query's q parameter""") def _GetAuthor(self): if 'author' in self.keys(): return self['author'] else: return None def _SetAuthor(self, query): self['author'] = query author = property(_GetAuthor, _SetAuthor, doc="""The feed query's author parameter""") def _GetAlt(self): if 'alt' in self.keys(): return self['alt'] else: return None def _SetAlt(self, query): self['alt'] = query alt = property(_GetAlt, _SetAlt, doc="""The feed query's alt parameter""") def _GetUpdatedMin(self): if 'updated-min' in self.keys(): return self['updated-min'] else: return None def _SetUpdatedMin(self, query): self['updated-min'] = query updated_min = property(_GetUpdatedMin, _SetUpdatedMin, doc="""The feed query's updated-min parameter""") def _GetUpdatedMax(self): if 'updated-max' in self.keys(): return self['updated-max'] else: return None def _SetUpdatedMax(self, query): self['updated-max'] = query updated_max = property(_GetUpdatedMax, _SetUpdatedMax, doc="""The feed query's updated-max parameter""") def _GetPublishedMin(self): if 'published-min' in self.keys(): return self['published-min'] else: return None def _SetPublishedMin(self, query): self['published-min'] = query published_min = property(_GetPublishedMin, _SetPublishedMin, doc="""The feed query's published-min parameter""") def _GetPublishedMax(self): if 'published-max' in self.keys(): return self['published-max'] else: return None def _SetPublishedMax(self, query): self['published-max'] = query published_max = property(_GetPublishedMax, _SetPublishedMax, doc="""The feed query's published-max parameter""") def _GetStartIndex(self): if 'start-index' in self.keys(): return self['start-index'] else: return None def _SetStartIndex(self, query): if not isinstance(query, str): query = str(query) self['start-index'] = query start_index = property(_GetStartIndex, _SetStartIndex, doc="""The feed query's start-index parameter""") def _GetMaxResults(self): if 'max-results' in self.keys(): return self['max-results'] else: return None def _SetMaxResults(self, query): if not isinstance(query, str): query = str(query) self['max-results'] = query max_results = property(_GetMaxResults, _SetMaxResults, doc="""The feed query's max-results parameter""") def _GetOrderBy(self): if 'orderby' in self.keys(): return self['orderby'] else: return None def _SetOrderBy(self, query): self['orderby'] = query orderby = property(_GetOrderBy, _SetOrderBy, doc="""The feed query's orderby parameter""") def ToUri(self): q_feed = self.feed or '' category_string = '/'.join( [urllib.quote_plus(c) for c in self.categories]) # Add categories to the feed if there are any. if len(self.categories) > 0: q_feed = q_feed + '/-/' + category_string return atom.service.BuildUri(q_feed, self) def __str__(self): return self.ToUri()
Python
#!/usr/bin/python # # Copyright (C) 2006,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. """GDataService provides CRUD ops. and programmatic login for GData services. Error: A base exception class for all exceptions in the gdata_client module. CaptchaRequired: This exception is thrown when a login attempt results in a captcha challenge from the ClientLogin service. When this exception is thrown, the captcha_token and captcha_url are set to the values provided in the server's response. BadAuthentication: Raised when a login attempt is made with an incorrect username or password. NotAuthenticated: Raised if an operation requiring authentication is called before a user has authenticated. NonAuthSubToken: Raised if a method to modify an AuthSub token is used when the user is either not authenticated or is authenticated through another authentication mechanism. NonOAuthToken: Raised if a method to modify an OAuth token is used when the user is either not authenticated or is authenticated through another authentication mechanism. RequestError: Raised if a CRUD request returned a non-success code. UnexpectedReturnType: Raised if the response from the server was not of the desired type. For example, this would be raised if the server sent a feed when the client requested an entry. GDataService: Encapsulates user credentials needed to perform insert, update and delete operations with the GData API. An instance can perform user authentication, query, insertion, deletion, and update. Query: Eases query URI creation by allowing URI parameters to be set as dictionary attributes. For example a query with a feed of '/base/feeds/snippets' and ['bq'] set to 'digital camera' will produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is called on it. """ __author__ = 'api.jscudder (Jeffrey Scudder)' import re import urllib import urlparse try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom.service import gdata import atom import atom.http_interface import atom.token_store import gdata.auth AUTH_SERVER_HOST = 'https://www.google.com' # When requesting an AuthSub token, it is often helpful to track the scope # which is being requested. One way to accomplish this is to add a URL # parameter to the 'next' URL which contains the requested scope. This # constant is the default name (AKA key) for the URL parameter. SCOPE_URL_PARAM_NAME = 'authsub_token_scope' # When requesting an OAuth access token or authorization of an existing OAuth # request token, it is often helpful to track the scope(s) which is/are being # requested. One way to accomplish this is to add a URL parameter to the # 'callback' URL which contains the requested scope. This constant is the # default name (AKA key) for the URL parameter. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope' # Maps the service names used in ClientLogin to scope URLs. CLIENT_LOGIN_SCOPES = { 'cl': [ # Google Calendar 'https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'], 'gbase': [ # Google Base 'http://base.google.com/base/feeds/', 'http://www.google.com/base/feeds/'], 'blogger': [ # Blogger 'http://www.blogger.com/feeds/'], 'codesearch': [ # Google Code Search 'http://www.google.com/codesearch/feeds/'], 'cp': [ # Contacts API 'https://www.google.com/m8/feeds/', 'http://www.google.com/m8/feeds/'], 'finance': [ # Google Finance 'http://finance.google.com/finance/feeds/'], 'health': [ # Google Health 'https://www.google.com/health/feeds/'], 'writely': [ # Documents List API 'https://docs.google.com/feeds/', 'http://docs.google.com/feeds/'], 'lh2': [ # Picasa Web Albums 'http://picasaweb.google.com/data/'], 'apps': [ # Google Apps Provisioning API 'http://www.google.com/a/feeds/', 'https://www.google.com/a/feeds/', 'http://apps-apis.google.com/a/feeds/', 'https://apps-apis.google.com/a/feeds/'], 'weaver': [ # Health H9 Sandbox 'https://www.google.com/h9/'], 'wise': [ # Spreadsheets Data API 'https://spreadsheets.google.com/feeds/', 'http://spreadsheets.google.com/feeds/'], 'sitemaps': [ # Google Webmaster Tools 'https://www.google.com/webmasters/tools/feeds/'], 'youtube': [ # YouTube 'http://gdata.youtube.com/feeds/api/', 'http://uploads.gdata.youtube.com/feeds/api', 'http://gdata.youtube.com/action/GetUploadToken']} def lookup_scopes(service_name): """Finds the scope URLs for the desired service. In some cases, an unknown service may be used, and in those cases this function will return None. """ if service_name in CLIENT_LOGIN_SCOPES: return CLIENT_LOGIN_SCOPES[service_name] return None # Module level variable specifies which module should be used by GDataService # objects to make HttpRequests. This setting can be overridden on each # instance of GDataService. # This module level variable is deprecated. Reassign the http_client member # of a GDataService object instead. http_request_handler = atom.service class Error(Exception): pass class CaptchaRequired(Error): pass class BadAuthentication(Error): pass class NotAuthenticated(Error): pass class NonAuthSubToken(Error): pass class NonOAuthToken(Error): pass class RequestError(Error): pass class UnexpectedReturnType(Error): pass class BadAuthenticationServiceURL(Error): pass class FetchingOAuthRequestTokenFailed(RequestError): pass class TokenUpgradeFailed(RequestError): pass class RevokingOAuthTokenFailed(RequestError): pass class AuthorizationRequired(Error): pass class TokenHadNoScope(Error): pass class GDataService(atom.service.AtomService): """Contains elements needed for GData login and CRUD request headers. Maintains additional headers (tokens for example) needed for the GData services to allow a user to perform inserts, updates, and deletes. """ # The hander member is deprecated, use http_client instead. handler = None # The auth_token member is deprecated, use the token_store instead. auth_token = None # The tokens dict is deprecated in favor of the token_store. tokens = None def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE', service=None, auth_service_url=None, source=None, server=None, additional_headers=None, handler=None, tokens=None, http_client=None, token_store=None): """Creates an object of type GDataService. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. account_type: string (optional) The type of account to use. Use 'GOOGLE' for regular Google accounts or 'HOSTED' for Google Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED account first and, if it doesn't exist, try finding a regular GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'. service: string (optional) The desired service for which credentials will be obtained. auth_service_url: string (optional) User-defined auth token request URL allows users to explicitly specify where to send auth token requests. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'base.google.com'. additional_headers: dictionary (optional) Any additional headers which should be included with CRUD operations. handler: module (optional) This parameter is deprecated and has been replaced by http_client. tokens: This parameter is deprecated, calls should be made to token_store instead. http_client: An object responsible for making HTTP requests using a request method. If none is provided, a new instance of atom.http.ProxiedHttpClient will be used. token_store: Keeps a collection of authorization tokens which can be applied to requests for a specific URLs. Critical methods are find_token based on a URL (atom.url.Url or a string), add_token, and remove_token. """ atom.service.AtomService.__init__(self, http_client=http_client, token_store=token_store) self.email = email self.password = password self.account_type = account_type self.service = service self.auth_service_url = auth_service_url self.server = server self.additional_headers = additional_headers or {} self._oauth_input_params = None self.__SetSource(source) self.__captcha_token = None self.__captcha_url = None self.__gsessionid = None if http_request_handler.__name__ == 'gdata.urlfetch': import gdata.alt.appengine self.http_client = gdata.alt.appengine.AppEngineHttpClient() # Define properties for GDataService def _SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self.SetAuthSubToken(auth_token, scopes=scopes) def __SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self._SetAuthSubToken(auth_token, scopes=scopes) def _GetAuthToken(self): """Returns the auth token used for authenticating requests. Returns: string """ current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if hasattr(token, 'auth_header'): return token.auth_header return None def _GetCaptchaToken(self): """Returns a captcha token if the most recent login attempt generated one. The captcha token is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_token def __GetCaptchaToken(self): return self._GetCaptchaToken() captcha_token = property(__GetCaptchaToken, doc="""Get the captcha token for a login request.""") def _GetCaptchaURL(self): """Returns the URL of the captcha image if a login attempt generated one. The captcha URL is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_url def __GetCaptchaURL(self): return self._GetCaptchaURL() captcha_url = property(__GetCaptchaURL, doc="""Get the captcha URL for a login request.""") def SetOAuthInputParameters(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, two_legged_oauth=False): """Sets parameters required for using OAuth authentication mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. two_legged_oauth: string (default=False) Enables two-legged OAuth process. """ self._oauth_input_params = gdata.auth.OAuthInputParams( signature_method, consumer_key, consumer_secret=consumer_secret, rsa_key=rsa_key) if two_legged_oauth: oauth_token = gdata.auth.OAuthToken( oauth_input_params=self._oauth_input_params) self.SetOAuthToken(oauth_token) def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None, request_url='%s/accounts/OAuthGetRequestToken' % \ AUTH_SERVER_HOST): """Fetches OAuth request token and returns it. Args: scopes: string or list of string base URL(s) of the service(s) to be accessed. If None, then this method tries to determine the scope(s) from the current service. extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} request_url: Request token URL. The default is 'https://www.google.com/accounts/OAuthGetRequestToken'. Returns: The fetched request token as a gdata.auth.OAuthToken object. Raises: FetchingOAuthRequestTokenFailed if the server responded to the request with an error. """ if scopes is None: scopes = lookup_scopes(self.service) if not isinstance(scopes, (list, tuple)): scopes = [scopes,] request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl( self._oauth_input_params, scopes, request_token_url=request_url, extra_parameters=extra_parameters) response = self.http_client.request('GET', str(request_token_url)) if response.status == 200: token = gdata.auth.OAuthToken() token.set_token_string(response.read()) token.scopes = scopes token.oauth_input_params = self._oauth_input_params return token error = { 'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response.read() } raise FetchingOAuthRequestTokenFailed(error) def SetOAuthToken(self, oauth_token): """Attempts to set the current token and add it to the token store. The oauth_token can be any OAuth token i.e. unauthorized request token, authorized request token or access token. This method also attempts to add the token to the token store. Use this method any time you want the current token to point to the oauth_token passed. For e.g. call this method with the request token you receive from FetchOAuthRequestToken. Args: request_token: gdata.auth.OAuthToken OAuth request token. """ if self.auto_set_current_token: self.current_token = oauth_token if self.auto_store_tokens: self.token_store.add_token(oauth_token) def GenerateOAuthAuthorizationURL( self, request_token=None, callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME, request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. request_url: Authorization URL. The default is 'https://www.google.com/accounts/OAuthAuthorizeToken'. Returns: A string URL at which the user is required to login. Raises: NonOAuthToken if the user's request token is not an OAuth token or if a request token was not available. """ if request_token and not isinstance(request_token, gdata.auth.OAuthToken): raise NonOAuthToken if not request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): request_token = token if not request_token: raise NonOAuthToken return str(gdata.auth.GenerateOAuthAuthorizationUrl( request_token, authorization_url=request_url, callback_url=callback_url, extra_params=extra_params, include_scopes_in_callback=include_scopes_in_callback, scopes_param_prefix=scopes_param_prefix)) def UpgradeToOAuthAccessToken(self, authorized_request_token=None, request_url='%s/accounts/OAuthGetAccessToken' \ % AUTH_SERVER_HOST, oauth_version='1.0'): """Upgrades the authorized request token to an access token. Args: authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. oauth_version: str (default='1.0') oauth_version parameter. All other 'oauth_' parameters are added by default. This parameter too, is added by default but here you can override it's value. request_url: Access token URL. The default is 'https://www.google.com/accounts/OAuthGetAccessToken'. Raises: NonOAuthToken if the user's authorized request token is not an OAuth token or if an authorized request token was not available. TokenUpgradeFailed if the server responded to the request with an error. """ if (authorized_request_token and not isinstance(authorized_request_token, gdata.auth.OAuthToken)): raise NonOAuthToken if not authorized_request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): authorized_request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): authorized_request_token = token if not authorized_request_token: raise NonOAuthToken access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl( authorized_request_token, self._oauth_input_params, access_token_url=request_url, oauth_version=oauth_version) response = self.http_client.request('GET', str(access_token_url)) if response.status == 200: token = gdata.auth.OAuthTokenFromHttpBody(response.read()) token.scopes = authorized_request_token.scopes token.oauth_input_params = authorized_request_token.oauth_input_params self.SetOAuthToken(token) else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response.read()}) def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \ AUTH_SERVER_HOST): """Revokes an existing OAuth token. request_url: Token revoke URL. The default is 'https://www.google.com/accounts/AuthSubRevokeToken'. Raises: NonOAuthToken if the user's auth token is not an OAuth token. RevokingOAuthTokenFailed if request for revoking an OAuth token failed. """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.OAuthToken): raise NonOAuthToken response = token.perform_request(self.http_client, 'GET', request_url, headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) else: raise RevokingOAuthTokenFailed def GetAuthSubToken(self): """Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed. This method examines the current_token to see if it is an AuthSubToken or SecureAuthSubToken. If not, it searches the token_store for a token which matches the current scope. The current scope is determined by the service name string member. Returns: If the current_token is set to an AuthSubToken/SecureAuthSubToken, return the token string. If there is no current_token, a token string for a token which matches the service object's default scope is returned. If there are no tokens valid for the scope, returns None. """ if isinstance(self.current_token, gdata.auth.AuthSubToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.AuthSubToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetAuthSubToken(self, token, scopes=None, rsa_key=None): """Sets the token sent in requests to an AuthSub token. Sets the current_token and attempts to add the token to the token_store. Only use this method if you have received a token from the AuthSub service. The auth token is set automatically when UpgradeToSessionToken() is used. See documentation for Google AuthSub here: http://code.google.com/apis/accounts/AuthForWebApps.html Args: token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string The token returned by the AuthSub service. If the token is an AuthSubToken or SecureAuthSubToken, the scope information stored in the token is used. If the token is a string, the scopes parameter is used to determine the valid scopes. scopes: list of URLs for which the token is valid. This is only used if the token parameter is a string. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. This parameter is necessary if the token is a string representing a secure token. """ if not isinstance(token, gdata.auth.AuthSubToken): token_string = token if rsa_key: token = gdata.auth.SecureAuthSubToken(rsa_key) else: token = gdata.auth.AuthSubToken() token.set_token_string(token_string) # If no scopes were set for the token, use the scopes passed in, or # try to determine the scopes based on the current service name. If # all else fails, set the token to match all requests. if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) def GetClientLoginToken(self): """Returns the token string for the current token or a token matching the service scope. If the current_token is a ClientLoginToken, the token string for the current token is returned. If the current_token is not set, this method searches for a token in the token_store which is valid for the service object's current scope. The current scope is determined by the service name string member. The token string is the end of the Authorization header, it doesn not include the ClientLogin label. """ if isinstance(self.current_token, gdata.auth.ClientLoginToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetClientLoginToken(self, token, scopes=None): """Sets the token sent in requests to a ClientLogin token. This method sets the current_token to a new ClientLoginToken and it also attempts to add the ClientLoginToken to the token_store. Only use this method if you have received a token from the ClientLogin service. The auth_token is set automatically when ProgrammaticLogin() is used. See documentation for Google ClientLogin here: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html Args: token: string or instance of a ClientLoginToken. """ if not isinstance(token, gdata.auth.ClientLoginToken): token_string = token token = gdata.auth.ClientLoginToken() token.set_token_string(token_string) if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) # Private methods to create the source property. def __GetSource(self): return self.__source def __SetSource(self, new_source): self.__source = new_source # Update the UserAgent header to include the new application name. self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % ( self.__source,) source = property(__GetSource, __SetSource, doc="""The source is the name of the application making the request. It should be in the form company_id-app_name-app_version""") # Authentication operations def ProgrammaticLogin(self, captcha_token=None, captcha_response=None): """Authenticates the user and sets the GData Auth token. Login retreives a temporary auth token which must be used with all requests to GData services. The auth token is stored in the GData client object. Login is also used to respond to a captcha challenge. If the user's login attempt failed with a CaptchaRequired error, the user can respond by calling Login with the captcha token and the answer to the challenge. Args: captcha_token: string (optional) The identifier for the captcha challenge which was presented to the user. captcha_response: string (optional) The user's answer to the captch challenge. Raises: CaptchaRequired if the login service will require a captcha response BadAuthentication if the login service rejected the username or password Error if the login service responded with a 403 different from the above """ request_body = gdata.auth.generate_client_login_request_body(self.email, self.password, self.service, self.source, self.account_type, captcha_token, captcha_response) # If the user has defined their own authentication service URL, # send the ClientLogin requests to this URL: if not self.auth_service_url: auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin' else: auth_request_url = self.auth_service_url auth_response = self.http_client.request('POST', auth_request_url, data=request_body, headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = auth_response.read() if auth_response.status == 200: # TODO: insert the token into the token_store directly. self.SetClientLoginToken( gdata.auth.get_client_login_token(response_body)) self.__captcha_token = None self.__captcha_url = None elif auth_response.status == 403: # Examine each line to find the error type and the captcha token and # captch URL if they are present. captcha_parameters = gdata.auth.get_captcha_challenge(response_body, captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST) if captcha_parameters: self.__captcha_token = captcha_parameters['token'] self.__captcha_url = captcha_parameters['url'] raise CaptchaRequired, 'Captcha Required' elif response_body.splitlines()[0] == 'Error=BadAuthentication': self.__captcha_token = None self.__captcha_url = None raise BadAuthentication, 'Incorrect username or password' else: self.__captcha_token = None self.__captcha_url = None raise Error, 'Server responded with a 403 code' elif auth_response.status == 302: self.__captcha_token = None self.__captcha_url = None # Google tries to redirect all bad URLs back to # http://www.google.<locale>. If a redirect # attempt is made, assume the user has supplied an incorrect authentication URL raise BadAuthenticationServiceURL, 'Server responded with a 302 code.' def ClientLogin(self, username, password, account_type=None, service=None, auth_service_url=None, source=None, captcha_token=None, captcha_response=None): """Convenience method for authenticating using ProgrammaticLogin. Sets values for email, password, and other optional members. Args: username: password: account_type: string (optional) service: string (optional) auth_service_url: string (optional) captcha_token: string (optional) captcha_response: string (optional) """ self.email = username self.password = password if account_type: self.account_type = account_type if service: self.service = service if source: self.source = source if auth_service_url: self.auth_service_url = auth_service_url self.ProgrammaticLogin(captcha_token, captcha_response) def GenerateAuthSubURL(self, next, scope, secure=False, session=True, domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: string The URL user will be sent to after logging in. scope: string or list of strings. The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. """ if not isinstance(scope, (list, tuple)): scope = (scope,) return gdata.auth.generate_auth_sub_url(next, scope, secure=secure, session=session, request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, domain=domain) def UpgradeToSessionToken(self, token=None): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken (optional) which is good for a single use but can be upgraded to a session token. If no token is passed in, the token is found by looking in the token_store by looking for a token for the current scope. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token TokenUpgradeFailed if the server responded to the request with an error. """ if token is None: scopes = lookup_scopes(self.service) if scopes: token = self.token_store.find_token(scopes[0]) else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken self.SetAuthSubToken(self.upgrade_to_session_token(token)) def upgrade_to_session_token(self, token): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken which is good for a single use but can be upgraded to a session token. Returns: The upgraded token as a gdata.auth.AuthSubToken object. Raises: TokenUpgradeFailed if the server responded to the request with an error. """ response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = response.read() if response.status == 200: token.set_token_string( gdata.auth.token_from_http_body(response_body)) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response_body}) def RevokeAuthSubToken(self): """Revokes an existing AuthSub token. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) def AuthSubTokenInfo(self): """Fetches the AuthSub token's metadata from the server. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', headers={'Content-Type':'application/x-www-form-urlencoded'}) result_body = response.read() if response.status == 200: return result_body else: raise RequestError, {'status': response.status, 'body': result_body} # CRUD operations def Get(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None): """Query the GData API with the given URI The uri is the portion of the URI after the server value (ex: www.google.com). To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. redirects_remaining: int (optional) Tracks the number of additional redirects this method will allow. If the service object receives a redirect and remaining is 0, it will not follow the redirect. This was added to avoid infinite redirect loops. encoding: string (optional) The character encoding for the server's response. Default is UTF-8 converter: func (optional) A function which will transform the server's results before it is returned. Example: use GDataFeedFromString to parse the server response as if it were a GDataFeed. Returns: If there is no ResultsTransformer specified in the call, a GDataFeed or GDataEntry depending on which is sent from the server. If the response is niether a feed or entry and there is no ResultsTransformer, return a string. If there is a ResultsTransformer, the returned value will be that of the ResultsTransformer function. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) server_response = self.request('GET', uri, headers=extra_headers) result_body = server_response.read() if server_response.status == 200: if converter: return converter(result_body) # There was no ResultsTransformer specified, so try to convert the # server's response into a GDataFeed. feed = gdata.GDataFeedFromString(result_body) if not feed: # If conversion to a GDataFeed failed, try to convert the server's # response to a GDataEntry. entry = gdata.GDataEntryFromString(result_body) if not entry: # The server's response wasn't a feed, or an entry, so return the # response body as a string. return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, encoding=encoding, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def GetMedia(self, uri, extra_headers=None): """Returns a MediaSource containing media and its metadata from the given URI string. """ response_handle = self.request('GET', uri, headers=extra_headers) return gdata.MediaSource(response_handle, response_handle.getheader( 'Content-Type'), response_handle.getheader('Content-Length')) def GetEntry(self, uri, extra_headers=None): """Query the GData API with the given URI and receive an Entry. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataEntry built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=atom.EntryFromString) if isinstance(result, atom.Entry): return result else: raise UnexpectedReturnType, 'Server did not send an entry' def GetFeed(self, uri, extra_headers=None, converter=gdata.GDataFeedFromString): """Query the GData API with the given URI and receive a Feed. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataFeed built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=converter) if isinstance(result, atom.Feed): return result else: raise UnexpectedReturnType, 'Server did not send a feed' def GetNext(self, feed): """Requests the next 'page' of results in the feed. This method uses the feed's next link to request an additional feed and uses the class of the feed to convert the results of the GET request. Args: feed: atom.Feed or a subclass. The feed should contain a next link and the type of the feed will be applied to the results from the server. The new feed which is returned will be of the same class as this feed which was passed in. Returns: A new feed representing the next set of results in the server's feed. The type of this feed will match that of the feed argument. """ next_link = feed.GetNextLink() # Create a closure which will convert an XML string to the class of # the feed object passed in. def ConvertToFeedClass(xml_string): return atom.CreateClassFromXMLString(feed.__class__, xml_string) # Make a GET request on the next link and use the above closure for the # converted which processes the XML string from the server. if next_link and next_link.href: return GDataService.Get(self, next_link.href, converter=ConvertToFeedClass) else: return None def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert or update data into a GData service at the given URI. Args: data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'POST', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert data into a GData service at the given URI. Args: verb: string, either 'POST' or 'PUT' data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) if data and media_source: if ElementTree.iselement(data): data_str = ElementTree.tostring(data) else: data_str = str(data) multipart = [] multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \ 'Content-Type: application/atom+xml\r\n\r\n') multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \ media_source.content_type+'\r\n\r\n') multipart.append('\r\n--END_OF_PART--\r\n') extra_headers['MIME-version'] = '1.0' extra_headers['Content-Length'] = str(len(multipart[0]) + len(multipart[1]) + len(multipart[2]) + len(data_str) + media_source.content_length) extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART' server_response = self.request(verb, uri, data=[multipart[0], data_str, multipart[1], media_source.file_handle, multipart[2]], headers=extra_headers) result_body = server_response.read() elif media_source or isinstance(data, gdata.MediaSource): if isinstance(data, gdata.MediaSource): media_source = data extra_headers['Content-Length'] = str(media_source.content_length) extra_headers['Content-Type'] = media_source.content_type server_response = self.request(verb, uri, data=media_source.file_handle, headers=extra_headers) result_body = server_response.read() else: http_data = data content_type = 'application/atom+xml' extra_headers['Content-Type'] = content_type server_response = self.request(verb, uri, data=http_data, headers=extra_headers) result_body = server_response.read() # Server returns 201 for most post requests, but when performing a batch # request the server responds with a 200 on success. if server_response.status == 201 or server_response.status == 200: if converter: return converter(result_body) feed = gdata.GDataFeedFromString(result_body) if not feed: entry = gdata.GDataEntryFromString(result_body) if not entry: return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.PostOrPut(self, verb, data, location, extra_headers, url_params, escape_params, redirects_remaining - 1, media_source, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=3, media_source=None, converter=None): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the put succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'PUT', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: True if the entry was deleted. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) server_response = self.request('DELETE', uri, headers=extra_headers) result_body = server_response.read() if server_response.status == 200: return True elif server_response.status == 302: if redirects_remaining > 0: location = server_response.getheader('Location') if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Delete(self, location, extra_headers, url_params, escape_params, redirects_remaining - 1) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def ExtractToken(url, scopes_included_in_next=True): """Gets the AuthSub token from the current page's URL. Designed to be used on the URL that the browser is sent to after the user authorizes this application at the page given by GenerateAuthSubRequestUrl. Args: url: The current page's URL. It should contain the token as a URL parameter. Example: 'http://example.com/?...&token=abcd435' scopes_included_in_next: If True, this function looks for a scope value associated with the token. The scope is a URL parameter with the key set to SCOPE_URL_PARAM_NAME. This parameter should be present if the AuthSub request URL was generated using GenerateAuthSubRequestUrl with include_scope_in_next set to True. Returns: A tuple containing the token string and a list of scope strings for which this token should be valid. If the scope was not included in the URL, the tuple will contain (token, None). """ parsed = urlparse.urlparse(url) token = gdata.auth.AuthSubTokenFromUrl(parsed[4]) scopes = '' if scopes_included_in_next: for pair in parsed[4].split('&'): if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME): scopes = urllib.unquote_plus(pair.split('=')[1]) return (token, scopes.split(' ')) def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False, session=True, request_url='http://www.google.com/accounts/AuthSubRequest', include_scopes_in_next=True): """Creates a URL to request an AuthSub token to access Google services. For more details on AuthSub, see the documentation here: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: The URL where the browser should be sent after the user authorizes the application. This page is responsible for receiving the token which is embeded in the URL as a parameter. scopes: The base URL to which access will be granted. Example: 'http://www.google.com/calendar/feeds' will grant access to all URLs in the Google Calendar data API. If you would like a token for multiple scopes, pass in a list of URL strings. hd: The domain to which the user's account belongs. This is set to the domain name if you are using Google Apps. Example: 'example.org' Defaults to 'default' secure: If set to True, all requests should be signed. The default is False. session: If set to True, the token received by the 'next' URL can be upgraded to a multiuse session token. If session is set to False, the token may only be used once and cannot be upgraded. Default is True. request_url: The base of the URL to which the user will be sent to authorize this application to access their data. The default is 'http://www.google.com/accounts/AuthSubRequest'. include_scopes_in_next: Boolean if set to true, the 'next' parameter will be modified to include the requested scope as a URL parameter. The key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the next URL, is that the page which receives the AuthSub token will be able to tell which URLs the token grants access to. Returns: A URL string to which the browser should be sent. """ if isinstance(scopes, list): scope = ' '.join(scopes) else: scope = scopes if include_scopes_in_next: if next.find('?') > -1: next += '&%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) else: next += '?%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure, session=session, request_url=request_url, domain=hd) class Query(dict): """Constructs a query URL to be used in GET requests Url parameters are created by adding key-value pairs to this object as a dict. For example, to add &max-results=25 to the URL do my_query['max-results'] = 25 Category queries are created by adding category strings to the categories member. All items in the categories list will be concatenated with the / symbol (symbolizing a category x AND y restriction). If you would like to OR 2 categories, append them as one string with a | between the categories. For example, do query.categories.append('Fritz|Laurie') to create a query like this feed/-/Fritz%7CLaurie . This query will look for results in both categories. """ def __init__(self, feed=None, text_query=None, params=None, categories=None): """Constructor for Query Args: feed: str (optional) The path for the feed (Examples: '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full' text_query: str (optional) The contents of the q query parameter. The contents of the text_query are URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items (key-value pairs). categories: list (optional) List of category strings which should be included as query categories. See http://code.google.com/apis/gdata/reference.html#Queries for details. If you want to get results from category A or B (both categories), specify a single list item 'A|B'. """ self.feed = feed self.categories = [] if text_query: self.text_query = text_query if isinstance(params, dict): for param in params: self[param] = params[param] if isinstance(categories, list): for category in categories: self.categories.append(category) def _GetTextQuery(self): if 'q' in self.keys(): return self['q'] else: return None def _SetTextQuery(self, query): self['q'] = query text_query = property(_GetTextQuery, _SetTextQuery, doc="""The feed query's q parameter""") def _GetAuthor(self): if 'author' in self.keys(): return self['author'] else: return None def _SetAuthor(self, query): self['author'] = query author = property(_GetAuthor, _SetAuthor, doc="""The feed query's author parameter""") def _GetAlt(self): if 'alt' in self.keys(): return self['alt'] else: return None def _SetAlt(self, query): self['alt'] = query alt = property(_GetAlt, _SetAlt, doc="""The feed query's alt parameter""") def _GetUpdatedMin(self): if 'updated-min' in self.keys(): return self['updated-min'] else: return None def _SetUpdatedMin(self, query): self['updated-min'] = query updated_min = property(_GetUpdatedMin, _SetUpdatedMin, doc="""The feed query's updated-min parameter""") def _GetUpdatedMax(self): if 'updated-max' in self.keys(): return self['updated-max'] else: return None def _SetUpdatedMax(self, query): self['updated-max'] = query updated_max = property(_GetUpdatedMax, _SetUpdatedMax, doc="""The feed query's updated-max parameter""") def _GetPublishedMin(self): if 'published-min' in self.keys(): return self['published-min'] else: return None def _SetPublishedMin(self, query): self['published-min'] = query published_min = property(_GetPublishedMin, _SetPublishedMin, doc="""The feed query's published-min parameter""") def _GetPublishedMax(self): if 'published-max' in self.keys(): return self['published-max'] else: return None def _SetPublishedMax(self, query): self['published-max'] = query published_max = property(_GetPublishedMax, _SetPublishedMax, doc="""The feed query's published-max parameter""") def _GetStartIndex(self): if 'start-index' in self.keys(): return self['start-index'] else: return None def _SetStartIndex(self, query): if not isinstance(query, str): query = str(query) self['start-index'] = query start_index = property(_GetStartIndex, _SetStartIndex, doc="""The feed query's start-index parameter""") def _GetMaxResults(self): if 'max-results' in self.keys(): return self['max-results'] else: return None def _SetMaxResults(self, query): if not isinstance(query, str): query = str(query) self['max-results'] = query max_results = property(_GetMaxResults, _SetMaxResults, doc="""The feed query's max-results parameter""") def _GetOrderBy(self): if 'orderby' in self.keys(): return self['orderby'] else: return None def _SetOrderBy(self, query): self['orderby'] = query orderby = property(_GetOrderBy, _SetOrderBy, doc="""The feed query's orderby parameter""") def ToUri(self): q_feed = self.feed or '' category_string = '/'.join( [urllib.quote_plus(c) for c in self.categories]) # Add categories to the feed if there are any. if len(self.categories) > 0: q_feed = q_feed + '/-/' + category_string return atom.service.BuildUri(q_feed, self) def __str__(self): return self.ToUri()
Python
#!/usr/bin/python # # Copyright (C) 2006 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 extensions to Atom objects used with Google Documents.""" __author__ = 'api.jfisher (Jeff Fisher)' import atom import gdata class DocumentListEntry(gdata.GDataEntry): """The Google Documents version of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def DocumentListEntryFromString(xml_string): """Converts an XML string into a DocumentListEntry object. Args: xml_string: string The XML describing a Document List feed entry. Returns: A DocumentListEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListEntry, xml_string) class DocumentListFeed(gdata.GDataFeed): """A feed containing a list of Google Documents Items""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [DocumentListEntry]) def DocumentListFeedFromString(xml_string): """Converts an XML string into a DocumentListFeed object. Args: xml_string: string The XML describing a DocumentList feed. Returns: A DocumentListFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2006 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. """DocsService extends the GDataService to streamline Google Documents operations. DocsService: Provides methods to query feeds and manipulate items. Extends GDataService. DocumentQuery: Queries a Google Document list feed. """ __author__ = 'api.jfisher (Jeff Fisher)' import urllib import atom import gdata.service import gdata.docs # XML Namespaces used in Google Documents entities. DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind' DOCUMENT_KIND_TERM = 'http://schemas.google.com/docs/2007#document' SPREADSHEET_KIND_TERM = 'http://schemas.google.com/docs/2007#spreadsheet' PRESENTATION_KIND_TERM = 'http://schemas.google.com/docs/2007#presentation' # File extensions of documents that are permitted to be uploaded. SUPPORTED_FILETYPES = { 'CSV': 'text/csv', 'TSV': 'text/tab-separated-values', 'TAB': 'text/tab-separated-values', 'DOC': 'application/msword', 'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet', 'ODT': 'application/vnd.oasis.opendocument.text', 'RTF': 'application/rtf', 'SXW': 'application/vnd.sun.xml.writer', 'TXT': 'text/plain', 'XLS': 'application/vnd.ms-excel', 'PPT': 'application/vnd.ms-powerpoint', 'PPS': 'application/vnd.ms-powerpoint', 'HTM': 'text/html', 'HTML' : 'text/html'} class DocsService(gdata.service.GDataService): """Client extension for the Google Documents service Document List feed.""" def __init__(self, email=None, password=None, source=None, server='docs.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Documents service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'docs.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='writely', source=source, server=server, additional_headers=additional_headers, **kwargs) def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString): """Queries the Document List feed and returns the resulting feed of entries. Args: uri: string The full URI to be queried. This can contain query parameters, a hostname, or simply the relative path to a Document List feed. The DocumentQuery object is useful when constructing query parameters. converter: func (optional) A function which will be executed on the retrieved item, generally to render it into a Python object. By default the DocumentListFeedFromString function is used to return a DocumentListFeed object. This is because most feed queries will result in a feed and not a single entry. """ return self.Get(uri, converter=converter) def QueryDocumentListFeed(self, uri): """Retrieves a DocumentListFeed by retrieving a URI based off the Document List feed, including any query parameters. A DocumentQuery object can be used to construct these parameters. Args: uri: string The URI of the feed being retrieved possibly with query parameters. Returns: A DocumentListFeed object representing the feed returned by the server. """ return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString) def GetDocumentListEntry(self, uri): """Retrieves a particular DocumentListEntry by its unique URI. Args: uri: string The unique URI of an entry in a Document List feed. Returns: A DocumentListEntry object representing the retrieved entry. """ return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString) def GetDocumentListFeed(self): """Retrieves a feed containing all of a user's documents.""" q = gdata.docs.service.DocumentQuery(); return self.QueryDocumentListFeed(q.ToUri()) def UploadPresentation(self, media_source, title): """Uploads a presentation inside of a MediaSource object to the Document List feed with the given title. Args: media_source: MediaSource The MediaSource object containing a presentation file to be uploaded. title: string The title of the presentation on the server after being uploaded. Returns: A GDataEntry containing information about the presentation created on the Google Documents service. """ category = atom.Category(scheme=DATA_KIND_SCHEME, term=PRESENTATION_KIND_TERM) return self._UploadFile(media_source, title, category) def UploadSpreadsheet(self, media_source, title): """Uploads a spreadsheet inside of a MediaSource object to the Document List feed with the given title. Args: media_source: MediaSource The MediaSource object containing a spreadsheet file to be uploaded. title: string The title of the spreadsheet on the server after being uploaded. Returns: A GDataEntry containing information about the spreadsheet created on the Google Documents service. """ category = atom.Category(scheme=DATA_KIND_SCHEME, term=SPREADSHEET_KIND_TERM) return self._UploadFile(media_source, title, category) def UploadDocument(self, media_source, title): """Uploads a document inside of a MediaSource object to the Document List feed with the given title. Args: media_source: MediaSource The gdata.MediaSource object containing a document file to be uploaded. title: string The title of the document on the server after being uploaded. Returns: A GDataEntry containing information about the document created on the Google Documents service. """ category = atom.Category(scheme=DATA_KIND_SCHEME, term=DOCUMENT_KIND_TERM) return self._UploadFile(media_source, title, category) def _UploadFile(self, media_source, title, category): """Uploads a file to the Document List feed. Args: media_source: A gdata.MediaSource object containing the file to be uploaded. title: string The title of the document on the server after being uploaded. category: An atom.Category object specifying the appropriate document type Returns: A GDataEntry containing information about the document created on the Google Documents service. """ media_entry = gdata.GDataEntry() media_entry.title = atom.Title(text=title) media_entry.category.append(category) media_entry = self.Post(media_entry, '/feeds/documents/private/full', media_source = media_source, extra_headers = {'Slug' : media_source.file_name }) return media_entry class DocumentQuery(gdata.service.Query): """Object used to construct a URI to query the Google Document List feed""" def __init__(self, feed='/feeds/documents', visibility='private', projection='full', text_query=None, params=None, categories=None): """Constructor for Document List Query Args: feed: string (optional) The path for the feed. (e.g. '/feeds/documents') visibility: string (optional) The visibility chosen for the current feed. projection: string (optional) The projection chosen for the current feed. text_query: string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items. categories: list (optional) List of category strings which should be included as query categories. See gdata.service.Query for additional documentation. Yields: A DocumentQuery object used to construct a URI based on the Document List feed. """ self.visibility = visibility self.projection = projection gdata.service.Query.__init__(self, feed, text_query, params, categories) def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Document List feed. """ old_feed = self.feed self.feed = '/'.join([old_feed, self.visibility, self.projection]) new_feed = gdata.service.Query.ToUri(self) self.feed = old_feed return new_feed def AddNamedFolder(self, email, folder_name): """Adds a named folder category, qualified by a schema. This function lets you query for documents that are contained inside a named folder without fear of collision with other categories. Args: email: string The email of the user who owns the folder. folder_name: string The name of the folder. Returns: The string of the category that was added to the object. """ category = '{http://schemas.google.com/docs/2007/folders/' category += email + '}' + folder_name self.categories.append(category) return category def RemoveNamedFolder(self, email, folder_name): """Removes a named folder category, qualified by a schema. Args: email: string The email of the user who owns the folder. folder_name: string The name of the folder. Returns: The string of the category that was removed to the object. """ category = '{http://schemas.google.com/docs/2007/folders/' category += email + '}' + folder_name self.categories.remove(category) return category
Python
#!/usr/bin/python # # Copyright (C) 2006 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. """DocsService extends the GDataService to streamline Google Documents operations. DocsService: Provides methods to query feeds and manipulate items. Extends GDataService. DocumentQuery: Queries a Google Document list feed. """ __author__ = 'api.jfisher (Jeff Fisher)' import urllib import atom import gdata.service import gdata.docs # XML Namespaces used in Google Documents entities. DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind' DOCUMENT_KIND_TERM = 'http://schemas.google.com/docs/2007#document' SPREADSHEET_KIND_TERM = 'http://schemas.google.com/docs/2007#spreadsheet' PRESENTATION_KIND_TERM = 'http://schemas.google.com/docs/2007#presentation' # File extensions of documents that are permitted to be uploaded. SUPPORTED_FILETYPES = { 'CSV': 'text/csv', 'TSV': 'text/tab-separated-values', 'TAB': 'text/tab-separated-values', 'DOC': 'application/msword', 'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet', 'ODT': 'application/vnd.oasis.opendocument.text', 'RTF': 'application/rtf', 'SXW': 'application/vnd.sun.xml.writer', 'TXT': 'text/plain', 'XLS': 'application/vnd.ms-excel', 'PPT': 'application/vnd.ms-powerpoint', 'PPS': 'application/vnd.ms-powerpoint', 'HTM': 'text/html', 'HTML' : 'text/html'} class DocsService(gdata.service.GDataService): """Client extension for the Google Documents service Document List feed.""" def __init__(self, email=None, password=None, source=None, server='docs.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Documents service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'docs.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='writely', source=source, server=server, additional_headers=additional_headers, **kwargs) def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString): """Queries the Document List feed and returns the resulting feed of entries. Args: uri: string The full URI to be queried. This can contain query parameters, a hostname, or simply the relative path to a Document List feed. The DocumentQuery object is useful when constructing query parameters. converter: func (optional) A function which will be executed on the retrieved item, generally to render it into a Python object. By default the DocumentListFeedFromString function is used to return a DocumentListFeed object. This is because most feed queries will result in a feed and not a single entry. """ return self.Get(uri, converter=converter) def QueryDocumentListFeed(self, uri): """Retrieves a DocumentListFeed by retrieving a URI based off the Document List feed, including any query parameters. A DocumentQuery object can be used to construct these parameters. Args: uri: string The URI of the feed being retrieved possibly with query parameters. Returns: A DocumentListFeed object representing the feed returned by the server. """ return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString) def GetDocumentListEntry(self, uri): """Retrieves a particular DocumentListEntry by its unique URI. Args: uri: string The unique URI of an entry in a Document List feed. Returns: A DocumentListEntry object representing the retrieved entry. """ return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString) def GetDocumentListFeed(self): """Retrieves a feed containing all of a user's documents.""" q = gdata.docs.service.DocumentQuery(); return self.QueryDocumentListFeed(q.ToUri()) def UploadPresentation(self, media_source, title): """Uploads a presentation inside of a MediaSource object to the Document List feed with the given title. Args: media_source: MediaSource The MediaSource object containing a presentation file to be uploaded. title: string The title of the presentation on the server after being uploaded. Returns: A GDataEntry containing information about the presentation created on the Google Documents service. """ category = atom.Category(scheme=DATA_KIND_SCHEME, term=PRESENTATION_KIND_TERM) return self._UploadFile(media_source, title, category) def UploadSpreadsheet(self, media_source, title): """Uploads a spreadsheet inside of a MediaSource object to the Document List feed with the given title. Args: media_source: MediaSource The MediaSource object containing a spreadsheet file to be uploaded. title: string The title of the spreadsheet on the server after being uploaded. Returns: A GDataEntry containing information about the spreadsheet created on the Google Documents service. """ category = atom.Category(scheme=DATA_KIND_SCHEME, term=SPREADSHEET_KIND_TERM) return self._UploadFile(media_source, title, category) def UploadDocument(self, media_source, title): """Uploads a document inside of a MediaSource object to the Document List feed with the given title. Args: media_source: MediaSource The gdata.MediaSource object containing a document file to be uploaded. title: string The title of the document on the server after being uploaded. Returns: A GDataEntry containing information about the document created on the Google Documents service. """ category = atom.Category(scheme=DATA_KIND_SCHEME, term=DOCUMENT_KIND_TERM) return self._UploadFile(media_source, title, category) def _UploadFile(self, media_source, title, category): """Uploads a file to the Document List feed. Args: media_source: A gdata.MediaSource object containing the file to be uploaded. title: string The title of the document on the server after being uploaded. category: An atom.Category object specifying the appropriate document type Returns: A GDataEntry containing information about the document created on the Google Documents service. """ media_entry = gdata.GDataEntry() media_entry.title = atom.Title(text=title) media_entry.category.append(category) media_entry = self.Post(media_entry, '/feeds/documents/private/full', media_source = media_source, extra_headers = {'Slug' : media_source.file_name }) return media_entry class DocumentQuery(gdata.service.Query): """Object used to construct a URI to query the Google Document List feed""" def __init__(self, feed='/feeds/documents', visibility='private', projection='full', text_query=None, params=None, categories=None): """Constructor for Document List Query Args: feed: string (optional) The path for the feed. (e.g. '/feeds/documents') visibility: string (optional) The visibility chosen for the current feed. projection: string (optional) The projection chosen for the current feed. text_query: string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items. categories: list (optional) List of category strings which should be included as query categories. See gdata.service.Query for additional documentation. Yields: A DocumentQuery object used to construct a URI based on the Document List feed. """ self.visibility = visibility self.projection = projection gdata.service.Query.__init__(self, feed, text_query, params, categories) def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Document List feed. """ old_feed = self.feed self.feed = '/'.join([old_feed, self.visibility, self.projection]) new_feed = gdata.service.Query.ToUri(self) self.feed = old_feed return new_feed def AddNamedFolder(self, email, folder_name): """Adds a named folder category, qualified by a schema. This function lets you query for documents that are contained inside a named folder without fear of collision with other categories. Args: email: string The email of the user who owns the folder. folder_name: string The name of the folder. Returns: The string of the category that was added to the object. """ category = '{http://schemas.google.com/docs/2007/folders/' category += email + '}' + folder_name self.categories.append(category) return category def RemoveNamedFolder(self, email, folder_name): """Removes a named folder category, qualified by a schema. Args: email: string The email of the user who owns the folder. folder_name: string The name of the folder. Returns: The string of the category that was removed to the object. """ category = '{http://schemas.google.com/docs/2007/folders/' category += email + '}' + folder_name self.categories.remove(category) return category
Python
#!/usr/bin/python # # Copyright (C) 2006 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 extensions to Atom objects used with Google Documents.""" __author__ = 'api.jfisher (Jeff Fisher)' import atom import gdata class DocumentListEntry(gdata.GDataEntry): """The Google Documents version of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def DocumentListEntryFromString(xml_string): """Converts an XML string into a DocumentListEntry object. Args: xml_string: string The XML describing a Document List feed entry. Returns: A DocumentListEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListEntry, xml_string) class DocumentListFeed(gdata.GDataFeed): """A feed containing a list of Google Documents Items""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [DocumentListEntry]) def DocumentListFeedFromString(xml_string): """Converts an XML string into a DocumentListFeed object. Args: xml_string: string The XML describing a DocumentList feed. Returns: A DocumentListFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListFeed, xml_string)
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.media, implementing parts of the MediaRSS spec in gdata structures # # $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions copyright 2007 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. """Essential attributes of photos in Google Photos/Picasa Web Albums are expressed using elements from the `media' namespace, defined in the MediaRSS specification[1]. Due to copyright issues, the elements herein are documented sparingly, please consult with the Google Photos API Reference Guide[2], alternatively the official MediaRSS specification[1] for details. (If there is a version conflict between the two sources, stick to the Google Photos API). [1]: http://search.yahoo.com/mrss (version 1.1.1) [2]: http://code.google.com/apis/picasaweb/reference.html#media_reference Keep in mind that Google Photos only uses a subset of the MediaRSS elements (and some of the attributes are trimmed down, too): media:content media:credit media:description media:group media:keywords media:thumbnail media:title """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/' YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007' class MediaBaseElement(atom.AtomBase): """Base class for elements in the MEDIA_NAMESPACE. To add new elements, you only need to add the element tag name to self._tag """ _tag = '' _namespace = MEDIA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Content(MediaBaseElement): """(attribute container) This element describes the original content, e.g. an image or a video. There may be multiple Content elements in a media:Group. For example, a video may have a <media:content medium="image"> element that specifies a JPEG representation of the video, and a <media:content medium="video"> element that specifies the URL of the video itself. Attributes: url: non-ambigous reference to online object width: width of the object frame, in pixels height: width of the object frame, in pixels medium: one of `image' or `video', allowing the api user to quickly determine the object's type type: Internet media Type[1] (a.k.a. mime type) of the object -- a more verbose way of determining the media type (optional) fileSize: the size of the object, in bytes [1]: http://en.wikipedia.org/wiki/Internet_media_type """ _tag = 'content' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' _attributes['medium'] = 'medium' _attributes['type'] = 'type' _attributes['fileSize'] = 'fileSize' def __init__(self, url=None, width=None, height=None, medium=None, content_type=None, fileSize=None, format=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.url = url self.width = width self.height = height self.medium = medium self.type = content_type self.fileSize = fileSize def ContentFromString(xml_string): return atom.CreateClassFromXMLString(Content, xml_string) class Credit(MediaBaseElement): """(string) Contains the nickname of the user who created the content, e.g. `Liz Bennet'. This is a user-specified value that should be used when referring to the user by name. Note that none of the attributes from the MediaRSS spec are supported. """ _tag = 'credit' def CreditFromString(xml_string): return atom.CreateClassFromXMLString(Credit, xml_string) class Description(MediaBaseElement): """(string) A description of the media object. Either plain unicode text, or entity-encoded html (look at the `type' attribute). E.g `A set of photographs I took while vacationing in Italy.' For `api' projections, the description is in plain text; for `base' projections, the description is in HTML. Attributes: type: either `text' or `html'. """ _tag = 'description' _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, description_type=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.type = description_type def DescriptionFromString(xml_string): return atom.CreateClassFromXMLString(Description, xml_string) class Keywords(MediaBaseElement): """(string) Lists the tags associated with the entry, e.g `italy, vacation, sunset'. Contains a comma-separated list of tags that have been added to the photo, or all tags that have been added to photos in the album. """ _tag = 'keywords' def KeywordsFromString(xml_string): return atom.CreateClassFromXMLString(Keywords, xml_string) class Thumbnail(MediaBaseElement): """(attributes) Contains the URL of a thumbnail of a photo or album cover. There can be multiple <media:thumbnail> elements for a given <media:group>; for example, a given item may have multiple thumbnails at different sizes. Photos generally have two thumbnails at different sizes; albums generally have one cropped thumbnail. If the thumbsize parameter is set to the initial query, this element points to thumbnails of the requested sizes; otherwise the thumbnails are the default thumbnail size. This element must not be confused with the <gphoto:thumbnail> element. Attributes: url: The URL of the thumbnail image. height: The height of the thumbnail image, in pixels. width: The width of the thumbnail image, in pixels. """ _tag = 'thumbnail' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' def __init__(self, url=None, width=None, height=None, extension_attributes=None, text=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.url = url self.width = width self.height = height def ThumbnailFromString(xml_string): return atom.CreateClassFromXMLString(Thumbnail, xml_string) class Title(MediaBaseElement): """(string) Contains the title of the entry's media content, in plain text. Attributes: type: Always set to plain """ _tag = 'title' _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, title_type=None, extension_attributes=None, text=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.type = title_type def TitleFromString(xml_string): return atom.CreateClassFromXMLString(Title, xml_string) class Player(MediaBaseElement): """(string) Contains the embeddable player URL for the entry's media content if the media is a video. Attributes: url: Always set to plain """ _tag = 'player' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' def __init__(self, player_url=None, extension_attributes=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes) self.url= player_url class Private(atom.AtomBase): """The YouTube Private element""" _tag = 'private' _namespace = YOUTUBE_NAMESPACE class Duration(atom.AtomBase): """The YouTube Duration element""" _tag = 'duration' _namespace = YOUTUBE_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['seconds'] = 'seconds' class Category(MediaBaseElement): """The mediagroup:category element""" _tag = 'category' _attributes = atom.AtomBase._attributes.copy() _attributes['term'] = 'term' _attributes['scheme'] = 'scheme' _attributes['label'] = 'label' def __init__(self, term=None, scheme=None, label=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Category Args: term: str scheme: str label: str text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.term = term self.scheme = scheme self.label = label self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Group(MediaBaseElement): """Container element for all media elements. The <media:group> element can appear as a child of an album, photo or video entry.""" _tag = 'group' _children = atom.AtomBase._children.copy() _children['{%s}content' % MEDIA_NAMESPACE] = ('content', [Content,]) _children['{%s}credit' % MEDIA_NAMESPACE] = ('credit', Credit) _children['{%s}description' % MEDIA_NAMESPACE] = ('description', Description) _children['{%s}keywords' % MEDIA_NAMESPACE] = ('keywords', Keywords) _children['{%s}thumbnail' % MEDIA_NAMESPACE] = ('thumbnail', [Thumbnail,]) _children['{%s}title' % MEDIA_NAMESPACE] = ('title', Title) _children['{%s}category' % MEDIA_NAMESPACE] = ('category', [Category,]) _children['{%s}duration' % YOUTUBE_NAMESPACE] = ('duration', Duration) _children['{%s}private' % YOUTUBE_NAMESPACE] = ('private', Private) _children['{%s}player' % MEDIA_NAMESPACE] = ('player', Player) def __init__(self, content=None, credit=None, description=None, keywords=None, thumbnail=None, title=None, duration=None, private=None, category=None, player=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.content=content self.credit=credit self.description=description self.keywords=keywords self.thumbnail=thumbnail or [] self.title=title self.duration=duration self.private=private self.category=category or [] self.player=player def GroupFromString(xml_string): return atom.CreateClassFromXMLString(Group, xml_string)
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.geo, implementing geological positioning in gdata structures # # $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions copyright 2007 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. """Picasa Web Albums uses the georss and gml namespaces for elements defined in the GeoRSS and Geography Markup Language specifications. Specifically, Picasa Web Albums uses the following elements: georss:where gml:Point gml:pos http://code.google.com/apis/picasaweb/reference.html#georss_reference Picasa Web Albums also accepts geographic-location data in two other formats: W3C format and plain-GeoRSS (without GML) format. """ # #Over the wire, the Picasa Web Albums only accepts and sends the #elements mentioned above, but this module will let you seamlessly convert #between the different formats (TODO 2007-10-18 hg) __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#' GML_NAMESPACE = 'http://www.opengis.net/gml' GEORSS_NAMESPACE = 'http://www.georss.org/georss' class GeoBaseElement(atom.AtomBase): """Base class for elements. To add new elements, you only need to add the element tag name to self._tag and the namespace to self._namespace """ _tag = '' _namespace = GML_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Pos(GeoBaseElement): """(string) Specifies a latitude and longitude, separated by a space, e.g. `35.669998 139.770004'""" _tag = 'pos' def PosFromString(xml_string): return atom.CreateClassFromXMLString(Pos, xml_string) class Point(GeoBaseElement): """(container) Specifies a particular geographical point, by means of a <gml:pos> element.""" _tag = 'Point' _children = atom.AtomBase._children.copy() _children['{%s}pos' % GML_NAMESPACE] = ('pos', Pos) def __init__(self, pos=None, extension_elements=None, extension_attributes=None, text=None): GeoBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) if pos is None: pos = Pos() self.pos=pos def PointFromString(xml_string): return atom.CreateClassFromXMLString(Point, xml_string) class Where(GeoBaseElement): """(container) Specifies a geographical location or region. A container element, containing a single <gml:Point> element. (Not to be confused with <gd:where>.) Note that the (only) child attribute, .Point, is title-cased. This reflects the names of elements in the xml stream (principle of least surprise). As a convenience, you can get a tuple of (lat, lon) with Where.location(), and set the same data with Where.setLocation( (lat, lon) ). Similarly, there are methods to set and get only latitude and longitude. """ _tag = 'where' _namespace = GEORSS_NAMESPACE _children = atom.AtomBase._children.copy() _children['{%s}Point' % GML_NAMESPACE] = ('Point', Point) def __init__(self, point=None, extension_elements=None, extension_attributes=None, text=None): GeoBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) if point is None: point = Point() self.Point=point def location(self): "(float, float) Return Where.Point.pos.text as a (lat,lon) tuple" try: return tuple([float(z) for z in self.Point.pos.text.split(' ')]) except AttributeError: return tuple() def set_location(self, latlon): """(bool) Set Where.Point.pos.text from a (lat,lon) tuple. Arguments: lat (float): The latitude in degrees, from -90.0 to 90.0 lon (float): The longitude in degrees, from -180.0 to 180.0 Returns True on success. """ assert(isinstance(latlon[0], float)) assert(isinstance(latlon[1], float)) try: self.Point.pos.text = "%s %s" % (latlon[0], latlon[1]) return True except AttributeError: return False def latitude(self): "(float) Get the latitude value of the geo-tag. See also .location()" lat, lon = self.location() return lat def longitude(self): "(float) Get the longtitude value of the geo-tag. See also .location()" lat, lon = self.location() return lon longtitude = longitude def set_latitude(self, lat): """(bool) Set the latitude value of the geo-tag. Args: lat (float): The new latitude value See also .set_location() """ _lat, lon = self.location() return self.set_location(lat, lon) def set_longitude(self, lon): """(bool) Set the longtitude value of the geo-tag. Args: lat (float): The new latitude value See also .set_location() """ lat, _lon = self.location() return self.set_location(lat, lon) set_longtitude = set_longitude def WhereFromString(xml_string): return atom.CreateClassFromXMLString(Where, xml_string)
Python
#!/usr/bin/env python # -*-*- encoding: utf-8 -*-*- # # This is the service file for the Google Photo python client. # It is used for higher level operations. # # $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # # 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. """Google PhotoService provides a human-friendly interface to Google Photo (a.k.a Picasa Web) services[1]. It extends gdata.service.GDataService and as such hides all the nasty details about authenticating, parsing and communicating with Google Photos. [1]: http://code.google.com/apis/picasaweb/gdata.html Example: import gdata.photos, gdata.photos.service pws = gdata.photos.service.PhotosService() pws.ClientLogin(username, password) #Get all albums albums = pws.GetUserFeed().entry # Get all photos in second album photos = pws.GetFeed(albums[1].GetPhotosUri()).entry # Get all tags for photos in second album and print them tags = pws.GetFeed(albums[1].GetTagsUri()).entry print [ tag.summary.text for tag in tags ] # Get all comments for the first photos in list and print them comments = pws.GetCommentFeed(photos[0].GetCommentsUri()).entry print [ c.summary.text for c in comments ] # Get a photo to work with photo = photos[0] # Update metadata # Attributes from the <gphoto:*> namespace photo.summary.text = u'A nice view from my veranda' photo.title.text = u'Verandaview.jpg' # Attributes from the <media:*> namespace photo.media.keywords.text = u'Home, Long-exposure, Sunset' # Comma-separated # Adding attributes to media object # Rotate 90 degrees clockwise photo.rotation = gdata.photos.Rotation(text='90') # Submit modified photo object photo = pws.UpdatePhotoMetadata(photo) # Make sure you only modify the newly returned object, else you'll get # versioning errors. See Optimistic-concurrency # Add comment to a picture comment = pws.InsertComment(photo, u'I wish the water always was this warm') # Remove comment because it was silly print "*blush*" pws.Delete(comment.GetEditLink().href) """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' __version__ = '$Revision: 176 $'[11:-2] import sys, os.path, StringIO import time import gdata.service import gdata import atom.service import atom import gdata.photos SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png') UNKOWN_ERROR=1000 GPHOTOS_BAD_REQUEST=400 GPHOTOS_CONFLICT=409 GPHOTOS_INTERNAL_SERVER_ERROR=500 GPHOTOS_INVALID_ARGUMENT=601 GPHOTOS_INVALID_CONTENT_TYPE=602 GPHOTOS_NOT_AN_IMAGE=603 GPHOTOS_INVALID_KIND=604 class GooglePhotosException(Exception): def __init__(self, response): self.error_code = response['status'] self.reason = response['reason'].strip() if '<html>' in str(response['body']): #general html message, discard it response['body'] = "" self.body = response['body'].strip() self.message = "(%(status)s) %(body)s -- %(reason)s" % response #return explicit error codes error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE, 'kind: That is not one of the acceptable values': GPHOTOS_INVALID_KIND, } for msg, code in error_map.iteritems(): if self.body == msg: self.error_code = code break self.args = [self.error_code, self.reason, self.body] class PhotosService(gdata.service.GDataService): userUri = '/data/feed/api/user/%s' def __init__(self, email=None, password=None, source=None, server='picasaweb.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Photos service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'picasaweb.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ self.email = email self.client = source gdata.service.GDataService.__init__( self, email=email, password=password, service='lh2', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetFeed(self, uri, limit=None, start_index=None): """Get a feed. The results are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: uri: the uri to fetch limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumFeed, gdata.photos.UserFeed, gdata.photos.PhotoFeed, gdata.photos.CommentFeed, gdata.photos.TagFeed, depending on the results of the query. Raises: GooglePhotosException See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyFeedFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetEntry(self, uri, limit=None, start_index=None): """Get an Entry. Arguments: uri: the uri to the entry limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumEntry, gdata.photos.UserEntry, gdata.photos.PhotoEntry, gdata.photos.CommentEntry, gdata.photos.TagEntry, depending on the results of the query. Raises: GooglePhotosException """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetUserFeed(self, kind='album', user='default', limit=None): """Get user-based feed, containing albums, photos, comments or tags; defaults to albums. The entries are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: kind: the kind of entries to get, either `album', `photo', `comment' or `tag', or a python list of these. Defaults to `album'. user (optional): whose albums we're querying. Defaults to current user. limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed, containing appropriate Entry elements See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual http://googledataapis.blogspot.com/2007/07/picasa-web-albums-adds-new-api-features.html """ if isinstance(kind, (list, tuple) ): kind = ",".join(kind) uri = '/data/feed/api/user/%s?kind=%s' % (user, kind) return self.GetFeed(uri, limit=limit) def GetTaggedPhotos(self, tag, user='default', limit=None): """Get all photos belonging to a specific user, tagged by the given keyword Arguments: tag: The tag you're looking for, e.g. `dog' user (optional): Whose images/videos you want to search, defaults to current user limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed containing PhotoEntry elements """ # Lower-casing because of # http://code.google.com/p/gdata-issues/issues/detail?id=194 uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower()) return self.GetFeed(uri, limit) def SearchUserPhotos(self, query, user='default', limit=100): """Search through all photos for a specific user and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' user (optional): The username of whose photos you want to search, defaults to current user. limit (optional): Don't return more than `limit' hits, defaults to 100 Only public photos are searched, unless you are authenticated and searching through your own photos. Returns: gdata.photos.UserFeed with PhotoEntry elements """ uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query) return self.GetFeed(uri, limit=limit) def SearchCommunityPhotos(self, query, limit=100): """Search through all public photos and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' limit (optional): Don't return more than `limit' hits, defaults to 100 Returns: gdata.GDataFeed with PhotoEntry elements """ uri='/data/feed/api/all?q=%s' % query return self.GetFeed(uri, limit=limit) def GetContacts(self, user='default', limit=None): """Retrieve a feed that contains a list of your contacts Arguments: user: Username of the user whose contacts you want Returns gdata.photos.UserFeed, with UserEntry entries See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=user' % user return self.GetFeed(uri, limit=limit) def SearchContactsPhotos(self, user='default', search=None, limit=None): """Search over your contacts' photos and return a feed Arguments: user: Username of the user whose contacts you want search (optional): What to search for (photo title, description and keywords) Returns gdata.photos.UserFeed, with PhotoEntry elements See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search) return self.GetFeed(uri, limit=limit) def InsertAlbum(self, title, summary, location=None, access='public', commenting_enabled='true', timestamp=None): """Add an album. Needs authentication, see self.ClientLogin() Arguments: title: Album title summary: Album summary / description access (optional): `private' or `public'. Public albums are searchable by everyone on the internet. Defaults to `public' commenting_enabled (optional): `true' or `false'. Defaults to `true'. timestamp (optional): A date and time for the album, in milliseconds since Unix epoch[1] UTC. Defaults to now. Returns: The newly created gdata.photos.AlbumEntry See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ album = gdata.photos.AlbumEntry() album.title = atom.Title(text=title, title_type='text') album.summary = atom.Summary(text=summary, summary_type='text') if location is not None: album.location = gdata.photos.Location(text=location) album.access = gdata.photos.Access(text=access) if commenting_enabled in ('true', 'false'): album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled) if timestamp is None: timestamp = '%i' % int(time.time() * 1000) album.timestamp = gdata.photos.Timestamp(text=timestamp) try: return self.Post(album, uri=self.userUri % self.email, converter=gdata.photos.AlbumEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhoto(self, album_or_uri, photo, filename_or_handle, content_type='image/jpeg'): """Add a PhotoEntry Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go photo: PhotoEntry to add filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' """ try: assert(isinstance(photo, gdata.photos.PhotoEntry)) except AssertionError: raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`photo` must be a gdata.photos.PhotoEntry instance', 'reason':'Found %s, not PhotoEntry' % type(photo) }) try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name mediasource = gdata.MediaSource() mediasource.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or object with a .read() method' % \ type(filename_or_handle) }) if isinstance(album_or_uri, (str, unicode)): # it's a uri feed_uri = album_or_uri elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object feed_uri = album_or_uri.GetFeedLink().href try: return self.Post(photo, uri=feed_uri, media_source=mediasource, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhotoSimple(self, album_or_uri, title, summary, filename_or_handle, content_type='image/jpeg', keywords=None): """Add a photo without constructing a PhotoEntry. Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go title: Photo title summary: Photo summary / description filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' keywords (optional): a 1) comma separated string or 2) a python list() of keywords (a.k.a. tags) to add to the image. E.g. 1) `dog, vacation, happy' 2) ['dog', 'happy', 'vacation'] Returns: The newly created gdata.photos.PhotoEntry or GooglePhotosException on errors See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ metadata = gdata.photos.PhotoEntry() metadata.title=atom.Title(text=title) metadata.summary = atom.Summary(text=summary, summary_type='text') if keywords is not None: if isinstance(keywords, list): keywords = ','.join(keywords) metadata.media.keywords = gdata.media.Keywords(text=keywords) return self.InsertPhoto(album_or_uri, metadata, filename_or_handle, content_type) def UpdatePhotoMetadata(self, photo): """Update a photo's metadata. Needs authentication, see self.ClientLogin() You can update any or all of the following metadata properties: * <title> * <media:description> * <gphoto:checksum> * <gphoto:client> * <gphoto:rotation> * <gphoto:timestamp> * <gphoto:commentingEnabled> Arguments: photo: a gdata.photos.PhotoEntry object with updated elements Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(uri).entry[0] p.title.text = u'My new text' p.commentingEnabled.text = 'false' p = UpdatePhotoMetadata(p) It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: return self.Put(data=photo, uri=photo.GetEditLink().href, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle, content_type = 'image/jpeg'): """Update a photo's binary data. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be updated, or a `edit-media' uri pointing to it filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(PhotoUri) p = UpdatePhotoBlob(p, '/tmp/newPic.jpg') It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name photoblob = gdata.MediaSource() photoblob.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or an object with .read() method' % \ type(filename_or_handle) }) if isinstance(photo_or_uri, (str, unicode)): entry_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): entry_uri = photo_or_uri.GetEditMediaLink().href try: return self.Put(photoblob, entry_uri, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertTag(self, photo_or_uri, tag): """Add a tag (a.k.a. keyword) to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be tagged, or a `post' uri pointing to it (string) tag: The tag/keyword Returns: The new gdata.photos.TagEntry Example: p = GetFeed(PhotoUri) tag = InsertTag(p, 'Beautiful sunsets') """ tag = gdata.photos.TagEntry(title=atom.Title(text=tag)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=tag, uri=post_uri, converter=gdata.photos.TagEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertComment(self, photo_or_uri, comment): """Add a comment to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that is about to be commented , or a `post' uri pointing to it (string) comment: The actual comment Returns: The new gdata.photos.CommentEntry Example: p = GetFeed(PhotoUri) tag = InsertComment(p, 'OOOH! I would have loved to be there. Who's that in the back?') """ comment = gdata.photos.CommentEntry(content=atom.Content(text=comment)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=comment, uri=post_uri, converter=gdata.photos.CommentEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def Delete(self, object_or_uri, *args, **kwargs): """Delete an object. Re-implementing the GDataService.Delete method, to add some convenience. Arguments: object_or_uri: Any object that has a GetEditLink() method that returns a link, or a uri to that object. Returns: ? or GooglePhotosException on errors """ try: uri = object_or_uri.GetEditLink().href except AttributeError: uri = object_or_uri try: return gdata.service.GDataService.Delete(self, uri, *args, **kwargs) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetSmallestThumbnail(media_thumbnail_list): """Helper function to get the smallest thumbnail of a list of gdata.media.Thumbnail. Returns gdata.media.Thumbnail """ r = {} for thumb in media_thumbnail_list: r[int(thumb.width)*int(thumb.height)] = thumb keys = r.keys() keys.sort() return r[keys[0]] def ConvertAtomTimestampToEpoch(timestamp): """Helper function to convert a timestamp string, for instance from atom:updated or atom:published, to milliseconds since Unix epoch (a.k.a. POSIX time). `2007-07-22T00:45:10.000Z' -> """ return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z')) ## TODO: Timezone aware
Python
#!/usr/bin/env python # -*-*- encoding: utf-8 -*-*- # # This is the service file for the Google Photo python client. # It is used for higher level operations. # # $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # # 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. """Google PhotoService provides a human-friendly interface to Google Photo (a.k.a Picasa Web) services[1]. It extends gdata.service.GDataService and as such hides all the nasty details about authenticating, parsing and communicating with Google Photos. [1]: http://code.google.com/apis/picasaweb/gdata.html Example: import gdata.photos, gdata.photos.service pws = gdata.photos.service.PhotosService() pws.ClientLogin(username, password) #Get all albums albums = pws.GetUserFeed().entry # Get all photos in second album photos = pws.GetFeed(albums[1].GetPhotosUri()).entry # Get all tags for photos in second album and print them tags = pws.GetFeed(albums[1].GetTagsUri()).entry print [ tag.summary.text for tag in tags ] # Get all comments for the first photos in list and print them comments = pws.GetCommentFeed(photos[0].GetCommentsUri()).entry print [ c.summary.text for c in comments ] # Get a photo to work with photo = photos[0] # Update metadata # Attributes from the <gphoto:*> namespace photo.summary.text = u'A nice view from my veranda' photo.title.text = u'Verandaview.jpg' # Attributes from the <media:*> namespace photo.media.keywords.text = u'Home, Long-exposure, Sunset' # Comma-separated # Adding attributes to media object # Rotate 90 degrees clockwise photo.rotation = gdata.photos.Rotation(text='90') # Submit modified photo object photo = pws.UpdatePhotoMetadata(photo) # Make sure you only modify the newly returned object, else you'll get # versioning errors. See Optimistic-concurrency # Add comment to a picture comment = pws.InsertComment(photo, u'I wish the water always was this warm') # Remove comment because it was silly print "*blush*" pws.Delete(comment.GetEditLink().href) """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' __version__ = '$Revision: 176 $'[11:-2] import sys, os.path, StringIO import time import gdata.service import gdata import atom.service import atom import gdata.photos SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png') UNKOWN_ERROR=1000 GPHOTOS_BAD_REQUEST=400 GPHOTOS_CONFLICT=409 GPHOTOS_INTERNAL_SERVER_ERROR=500 GPHOTOS_INVALID_ARGUMENT=601 GPHOTOS_INVALID_CONTENT_TYPE=602 GPHOTOS_NOT_AN_IMAGE=603 GPHOTOS_INVALID_KIND=604 class GooglePhotosException(Exception): def __init__(self, response): self.error_code = response['status'] self.reason = response['reason'].strip() if '<html>' in str(response['body']): #general html message, discard it response['body'] = "" self.body = response['body'].strip() self.message = "(%(status)s) %(body)s -- %(reason)s" % response #return explicit error codes error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE, 'kind: That is not one of the acceptable values': GPHOTOS_INVALID_KIND, } for msg, code in error_map.iteritems(): if self.body == msg: self.error_code = code break self.args = [self.error_code, self.reason, self.body] class PhotosService(gdata.service.GDataService): userUri = '/data/feed/api/user/%s' def __init__(self, email=None, password=None, source=None, server='picasaweb.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Photos service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'picasaweb.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ self.email = email self.client = source gdata.service.GDataService.__init__( self, email=email, password=password, service='lh2', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetFeed(self, uri, limit=None, start_index=None): """Get a feed. The results are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: uri: the uri to fetch limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumFeed, gdata.photos.UserFeed, gdata.photos.PhotoFeed, gdata.photos.CommentFeed, gdata.photos.TagFeed, depending on the results of the query. Raises: GooglePhotosException See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyFeedFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetEntry(self, uri, limit=None, start_index=None): """Get an Entry. Arguments: uri: the uri to the entry limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumEntry, gdata.photos.UserEntry, gdata.photos.PhotoEntry, gdata.photos.CommentEntry, gdata.photos.TagEntry, depending on the results of the query. Raises: GooglePhotosException """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetUserFeed(self, kind='album', user='default', limit=None): """Get user-based feed, containing albums, photos, comments or tags; defaults to albums. The entries are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: kind: the kind of entries to get, either `album', `photo', `comment' or `tag', or a python list of these. Defaults to `album'. user (optional): whose albums we're querying. Defaults to current user. limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed, containing appropriate Entry elements See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual http://googledataapis.blogspot.com/2007/07/picasa-web-albums-adds-new-api-features.html """ if isinstance(kind, (list, tuple) ): kind = ",".join(kind) uri = '/data/feed/api/user/%s?kind=%s' % (user, kind) return self.GetFeed(uri, limit=limit) def GetTaggedPhotos(self, tag, user='default', limit=None): """Get all photos belonging to a specific user, tagged by the given keyword Arguments: tag: The tag you're looking for, e.g. `dog' user (optional): Whose images/videos you want to search, defaults to current user limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed containing PhotoEntry elements """ # Lower-casing because of # http://code.google.com/p/gdata-issues/issues/detail?id=194 uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower()) return self.GetFeed(uri, limit) def SearchUserPhotos(self, query, user='default', limit=100): """Search through all photos for a specific user and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' user (optional): The username of whose photos you want to search, defaults to current user. limit (optional): Don't return more than `limit' hits, defaults to 100 Only public photos are searched, unless you are authenticated and searching through your own photos. Returns: gdata.photos.UserFeed with PhotoEntry elements """ uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query) return self.GetFeed(uri, limit=limit) def SearchCommunityPhotos(self, query, limit=100): """Search through all public photos and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' limit (optional): Don't return more than `limit' hits, defaults to 100 Returns: gdata.GDataFeed with PhotoEntry elements """ uri='/data/feed/api/all?q=%s' % query return self.GetFeed(uri, limit=limit) def GetContacts(self, user='default', limit=None): """Retrieve a feed that contains a list of your contacts Arguments: user: Username of the user whose contacts you want Returns gdata.photos.UserFeed, with UserEntry entries See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=user' % user return self.GetFeed(uri, limit=limit) def SearchContactsPhotos(self, user='default', search=None, limit=None): """Search over your contacts' photos and return a feed Arguments: user: Username of the user whose contacts you want search (optional): What to search for (photo title, description and keywords) Returns gdata.photos.UserFeed, with PhotoEntry elements See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search) return self.GetFeed(uri, limit=limit) def InsertAlbum(self, title, summary, location=None, access='public', commenting_enabled='true', timestamp=None): """Add an album. Needs authentication, see self.ClientLogin() Arguments: title: Album title summary: Album summary / description access (optional): `private' or `public'. Public albums are searchable by everyone on the internet. Defaults to `public' commenting_enabled (optional): `true' or `false'. Defaults to `true'. timestamp (optional): A date and time for the album, in milliseconds since Unix epoch[1] UTC. Defaults to now. Returns: The newly created gdata.photos.AlbumEntry See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ album = gdata.photos.AlbumEntry() album.title = atom.Title(text=title, title_type='text') album.summary = atom.Summary(text=summary, summary_type='text') if location is not None: album.location = gdata.photos.Location(text=location) album.access = gdata.photos.Access(text=access) if commenting_enabled in ('true', 'false'): album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled) if timestamp is None: timestamp = '%i' % int(time.time() * 1000) album.timestamp = gdata.photos.Timestamp(text=timestamp) try: return self.Post(album, uri=self.userUri % self.email, converter=gdata.photos.AlbumEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhoto(self, album_or_uri, photo, filename_or_handle, content_type='image/jpeg'): """Add a PhotoEntry Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go photo: PhotoEntry to add filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' """ try: assert(isinstance(photo, gdata.photos.PhotoEntry)) except AssertionError: raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`photo` must be a gdata.photos.PhotoEntry instance', 'reason':'Found %s, not PhotoEntry' % type(photo) }) try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name mediasource = gdata.MediaSource() mediasource.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or object with a .read() method' % \ type(filename_or_handle) }) if isinstance(album_or_uri, (str, unicode)): # it's a uri feed_uri = album_or_uri elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object feed_uri = album_or_uri.GetFeedLink().href try: return self.Post(photo, uri=feed_uri, media_source=mediasource, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhotoSimple(self, album_or_uri, title, summary, filename_or_handle, content_type='image/jpeg', keywords=None): """Add a photo without constructing a PhotoEntry. Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go title: Photo title summary: Photo summary / description filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' keywords (optional): a 1) comma separated string or 2) a python list() of keywords (a.k.a. tags) to add to the image. E.g. 1) `dog, vacation, happy' 2) ['dog', 'happy', 'vacation'] Returns: The newly created gdata.photos.PhotoEntry or GooglePhotosException on errors See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ metadata = gdata.photos.PhotoEntry() metadata.title=atom.Title(text=title) metadata.summary = atom.Summary(text=summary, summary_type='text') if keywords is not None: if isinstance(keywords, list): keywords = ','.join(keywords) metadata.media.keywords = gdata.media.Keywords(text=keywords) return self.InsertPhoto(album_or_uri, metadata, filename_or_handle, content_type) def UpdatePhotoMetadata(self, photo): """Update a photo's metadata. Needs authentication, see self.ClientLogin() You can update any or all of the following metadata properties: * <title> * <media:description> * <gphoto:checksum> * <gphoto:client> * <gphoto:rotation> * <gphoto:timestamp> * <gphoto:commentingEnabled> Arguments: photo: a gdata.photos.PhotoEntry object with updated elements Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(uri).entry[0] p.title.text = u'My new text' p.commentingEnabled.text = 'false' p = UpdatePhotoMetadata(p) It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: return self.Put(data=photo, uri=photo.GetEditLink().href, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle, content_type = 'image/jpeg'): """Update a photo's binary data. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be updated, or a `edit-media' uri pointing to it filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(PhotoUri) p = UpdatePhotoBlob(p, '/tmp/newPic.jpg') It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name photoblob = gdata.MediaSource() photoblob.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or an object with .read() method' % \ type(filename_or_handle) }) if isinstance(photo_or_uri, (str, unicode)): entry_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): entry_uri = photo_or_uri.GetEditMediaLink().href try: return self.Put(photoblob, entry_uri, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertTag(self, photo_or_uri, tag): """Add a tag (a.k.a. keyword) to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be tagged, or a `post' uri pointing to it (string) tag: The tag/keyword Returns: The new gdata.photos.TagEntry Example: p = GetFeed(PhotoUri) tag = InsertTag(p, 'Beautiful sunsets') """ tag = gdata.photos.TagEntry(title=atom.Title(text=tag)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=tag, uri=post_uri, converter=gdata.photos.TagEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertComment(self, photo_or_uri, comment): """Add a comment to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that is about to be commented , or a `post' uri pointing to it (string) comment: The actual comment Returns: The new gdata.photos.CommentEntry Example: p = GetFeed(PhotoUri) tag = InsertComment(p, 'OOOH! I would have loved to be there. Who's that in the back?') """ comment = gdata.photos.CommentEntry(content=atom.Content(text=comment)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=comment, uri=post_uri, converter=gdata.photos.CommentEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def Delete(self, object_or_uri, *args, **kwargs): """Delete an object. Re-implementing the GDataService.Delete method, to add some convenience. Arguments: object_or_uri: Any object that has a GetEditLink() method that returns a link, or a uri to that object. Returns: ? or GooglePhotosException on errors """ try: uri = object_or_uri.GetEditLink().href except AttributeError: uri = object_or_uri try: return gdata.service.GDataService.Delete(self, uri, *args, **kwargs) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetSmallestThumbnail(media_thumbnail_list): """Helper function to get the smallest thumbnail of a list of gdata.media.Thumbnail. Returns gdata.media.Thumbnail """ r = {} for thumb in media_thumbnail_list: r[int(thumb.width)*int(thumb.height)] = thumb keys = r.keys() keys.sort() return r[keys[0]] def ConvertAtomTimestampToEpoch(timestamp): """Helper function to convert a timestamp string, for instance from atom:updated or atom:published, to milliseconds since Unix epoch (a.k.a. POSIX time). `2007-07-22T00:45:10.000Z' -> """ return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z')) ## TODO: Timezone aware
Python
# -*-*- encoding: utf-8 -*-*- # # This is the base file for the PicasaWeb python client. # It is used for lower level operations. # # $Id: __init__.py 148 2007-10-28 15:09:19Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions (C) 2006 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. """This module provides a pythonic, gdata-centric interface to Google Photos (a.k.a. Picasa Web Services. It is modelled after the gdata/* interfaces from the gdata-python-client project[1] by Google. You'll find the user-friendly api in photos.service. Please see the documentation or live help() system for available methods. [1]: http://gdata-python-client.googlecode.com/ """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' __version__ = '$Revision: 164 $'[11:-2] import re try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata # importing google photo submodules import gdata.media as Media, gdata.exif as Exif, gdata.geo as Geo # XML namespaces which are often used in Google Photo elements PHOTOS_NAMESPACE = 'http://schemas.google.com/photos/2007' MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/' EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007' OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/' GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#' GML_NAMESPACE = 'http://www.opengis.net/gml' GEORSS_NAMESPACE = 'http://www.georss.org/georss' PHEED_NAMESPACE = 'http://www.pheed.com/pheed/' BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch' class PhotosBaseElement(atom.AtomBase): """Base class for elements in the PHOTO_NAMESPACE. To add new elements, you only need to add the element tag name to self._tag """ _tag = '' _namespace = PHOTOS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} #def __str__(self): #return str(self.text) #def __unicode__(self): #return unicode(self.text) def __int__(self): return int(self.text) def bool(self): return self.text == 'true' class GPhotosBaseFeed(gdata.GDataFeed, gdata.LinkFinder): "Base class for all Feeds in gdata.photos" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _attributes = gdata.GDataFeed._attributes.copy() _children = gdata.GDataFeed._children.copy() # We deal with Entry elements ourselves del _children['{%s}entry' % atom.ATOM_NAMESPACE] def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def kind(self): "(string) Returns the kind" try: return self.category[0].term.split('#')[1] except IndexError: return None def _feedUri(self, kind): "Convenience method to return a uri to a feed of a special kind" assert(kind in ('album', 'tag', 'photo', 'comment', 'user')) here_href = self.GetSelfLink().href if 'kind=%s' % kind in here_href: return here_href if not 'kind=' in here_href: sep = '?' if '?' in here_href: sep = '&' return here_href + "%skind=%s" % (sep, kind) rx = re.match('.*(kind=)(album|tag|photo|comment)', here_href) return here_href[:rx.end(1)] + kind + here_href[rx.end(2):] def _ConvertElementTreeToMember(self, child_tree): """Re-implementing the method from AtomBase, since we deal with Entry elements specially""" category = child_tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: return atom.AtomBase._ConvertElementTreeToMember(self, child_tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: return atom.AtomBase._ConvertElementTreeToMember(self, child_tree) ## TODO: is it safe to use getattr on gdata.photos? entry_class = getattr(gdata.photos, '%sEntry' % kind.title()) if not hasattr(self, 'entry') or self.entry is None: self.entry = [] self.entry.append(atom._CreateClassFromElementTree( entry_class, child_tree)) class GPhotosBaseEntry(gdata.GDataEntry, gdata.LinkFinder): "Base class for all Entry elements in gdata.photos" _tag = 'entry' _kind = '' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, extended_property=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, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.category.append( atom.Category(scheme='http://schemas.google.com/g/2005#kind', term = 'http://schemas.google.com/photos/2007#%s' % self._kind)) def kind(self): "(string) Returns the kind" try: return self.category[0].term.split('#')[1] except IndexError: return None def _feedUri(self, kind): "Convenience method to get the uri to this entry's feed of the some kind" try: href = self.GetFeedLink().href except AttributeError: return None sep = '?' if '?' in href: sep = '&' return '%s%skind=%s' % (href, sep, kind) class PhotosBaseEntry(GPhotosBaseEntry): pass class PhotosBaseFeed(GPhotosBaseFeed): pass class GPhotosBaseData(object): pass class Access(PhotosBaseElement): """The Google Photo `Access' element. The album's access level. Valid values are `public' or `private'. In documentation, access level is also referred to as `visibility.'""" _tag = 'access' def AccessFromString(xml_string): return atom.CreateClassFromXMLString(Access, xml_string) class Albumid(PhotosBaseElement): "The Google Photo `Albumid' element" _tag = 'albumid' def AlbumidFromString(xml_string): return atom.CreateClassFromXMLString(Albumid, xml_string) class BytesUsed(PhotosBaseElement): "The Google Photo `BytesUsed' element" _tag = 'bytesUsed' def BytesUsedFromString(xml_string): return atom.CreateClassFromXMLString(BytesUsed, xml_string) class Client(PhotosBaseElement): "The Google Photo `Client' element" _tag = 'client' def ClientFromString(xml_string): return atom.CreateClassFromXMLString(Client, xml_string) class Checksum(PhotosBaseElement): "The Google Photo `Checksum' element" _tag = 'checksum' def ChecksumFromString(xml_string): return atom.CreateClassFromXMLString(Checksum, xml_string) class CommentCount(PhotosBaseElement): "The Google Photo `CommentCount' element" _tag = 'commentCount' def CommentCountFromString(xml_string): return atom.CreateClassFromXMLString(CommentCount, xml_string) class CommentingEnabled(PhotosBaseElement): "The Google Photo `CommentingEnabled' element" _tag = 'commentingEnabled' def CommentingEnabledFromString(xml_string): return atom.CreateClassFromXMLString(CommentingEnabled, xml_string) class Height(PhotosBaseElement): "The Google Photo `Height' element" _tag = 'height' def HeightFromString(xml_string): return atom.CreateClassFromXMLString(Height, xml_string) class Id(PhotosBaseElement): "The Google Photo `Id' element" _tag = 'id' def IdFromString(xml_string): return atom.CreateClassFromXMLString(Id, xml_string) class Location(PhotosBaseElement): "The Google Photo `Location' element" _tag = 'location' def LocationFromString(xml_string): return atom.CreateClassFromXMLString(Location, xml_string) class MaxPhotosPerAlbum(PhotosBaseElement): "The Google Photo `MaxPhotosPerAlbum' element" _tag = 'maxPhotosPerAlbum' def MaxPhotosPerAlbumFromString(xml_string): return atom.CreateClassFromXMLString(MaxPhotosPerAlbum, xml_string) class Name(PhotosBaseElement): "The Google Photo `Name' element" _tag = 'name' def NameFromString(xml_string): return atom.CreateClassFromXMLString(Name, xml_string) class Nickname(PhotosBaseElement): "The Google Photo `Nickname' element" _tag = 'nickname' def NicknameFromString(xml_string): return atom.CreateClassFromXMLString(Nickname, xml_string) class Numphotos(PhotosBaseElement): "The Google Photo `Numphotos' element" _tag = 'numphotos' def NumphotosFromString(xml_string): return atom.CreateClassFromXMLString(Numphotos, xml_string) class Numphotosremaining(PhotosBaseElement): "The Google Photo `Numphotosremaining' element" _tag = 'numphotosremaining' def NumphotosremainingFromString(xml_string): return atom.CreateClassFromXMLString(Numphotosremaining, xml_string) class Position(PhotosBaseElement): "The Google Photo `Position' element" _tag = 'position' def PositionFromString(xml_string): return atom.CreateClassFromXMLString(Position, xml_string) class Photoid(PhotosBaseElement): "The Google Photo `Photoid' element" _tag = 'photoid' def PhotoidFromString(xml_string): return atom.CreateClassFromXMLString(Photoid, xml_string) class Quotacurrent(PhotosBaseElement): "The Google Photo `Quotacurrent' element" _tag = 'quotacurrent' def QuotacurrentFromString(xml_string): return atom.CreateClassFromXMLString(Quotacurrent, xml_string) class Quotalimit(PhotosBaseElement): "The Google Photo `Quotalimit' element" _tag = 'quotalimit' def QuotalimitFromString(xml_string): return atom.CreateClassFromXMLString(Quotalimit, xml_string) class Rotation(PhotosBaseElement): "The Google Photo `Rotation' element" _tag = 'rotation' def RotationFromString(xml_string): return atom.CreateClassFromXMLString(Rotation, xml_string) class Size(PhotosBaseElement): "The Google Photo `Size' element" _tag = 'size' def SizeFromString(xml_string): return atom.CreateClassFromXMLString(Size, xml_string) class Snippet(PhotosBaseElement): """The Google Photo `snippet' element. When searching, the snippet element will contain a string with the word you're looking for, highlighted in html markup E.g. when your query is `hafjell', this element may contain: `... here at <b>Hafjell</b>.' You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:truncated and gphoto:snippettype. """ _tag = 'snippet' def SnippetFromString(xml_string): return atom.CreateClassFromXMLString(Snippet, xml_string) class Snippettype(PhotosBaseElement): """The Google Photo `Snippettype' element When searching, this element will tell you the type of element that matches. You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:snippet and gphoto:truncated. Possible values and their interpretation: o ALBUM_TITLE - The album title matches o PHOTO_TAGS - The match is a tag/keyword o PHOTO_DESCRIPTION - The match is in the photo's description If you discover a value not listed here, please submit a patch to update this docstring. """ _tag = 'snippettype' def SnippettypeFromString(xml_string): return atom.CreateClassFromXMLString(Snippettype, xml_string) class Thumbnail(PhotosBaseElement): """The Google Photo `Thumbnail' element Used to display user's photo thumbnail (hackergotchi). (Not to be confused with the <media:thumbnail> element, which gives you small versions of the photo object.)""" _tag = 'thumbnail' def ThumbnailFromString(xml_string): return atom.CreateClassFromXMLString(Thumbnail, xml_string) class Timestamp(PhotosBaseElement): """The Google Photo `Timestamp' element Represented as the number of milliseconds since January 1st, 1970. Take a look at the convenience methods .isoformat() and .datetime(): photo_epoch = Time.text # 1180294337000 photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z' Alternatively: photo_datetime = Time.datetime() # (requires python >= 2.3) """ _tag = 'timestamp' def isoformat(self): """(string) Return the timestamp as a ISO 8601 formatted string, e.g. '2007-05-27T19:32:17.000Z' """ import time epoch = float(self.text)/1000 return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch)) def datetime(self): """(datetime.datetime) Return the timestamp as a datetime.datetime object Requires python 2.3 """ import datetime epoch = float(self.text)/1000 return datetime.datetime.fromtimestamp(epoch) def TimestampFromString(xml_string): return atom.CreateClassFromXMLString(Timestamp, xml_string) class Truncated(PhotosBaseElement): """The Google Photo `Truncated' element You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:snippet and gphoto:snippettype. Possible values and their interpretation: 0 -- unknown """ _tag = 'Truncated' def TruncatedFromString(xml_string): return atom.CreateClassFromXMLString(Truncated, xml_string) class User(PhotosBaseElement): "The Google Photo `User' element" _tag = 'user' def UserFromString(xml_string): return atom.CreateClassFromXMLString(User, xml_string) class Version(PhotosBaseElement): "The Google Photo `Version' element" _tag = 'version' def VersionFromString(xml_string): return atom.CreateClassFromXMLString(Version, xml_string) class Width(PhotosBaseElement): "The Google Photo `Width' element" _tag = 'width' def WidthFromString(xml_string): return atom.CreateClassFromXMLString(Width, xml_string) class Weight(PhotosBaseElement): """The Google Photo `Weight' element. The weight of the tag is the number of times the tag appears in the collection of tags currently being viewed. The default weight is 1, in which case this tags is omitted.""" _tag = 'weight' def WeightFromString(xml_string): return atom.CreateClassFromXMLString(Weight, xml_string) class CommentAuthor(atom.Author): """The Atom `Author' element in CommentEntry entries is augmented to contain elements from the PHOTOS_NAMESPACE http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ _children = atom.Author._children.copy() _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail) def CommentAuthorFromString(xml_string): return atom.CreateClassFromXMLString(CommentAuthor, xml_string) ########################## ################################ class AlbumData(object): _children = {} _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}name' % PHOTOS_NAMESPACE] = ('name', Name) _children['{%s}location' % PHOTOS_NAMESPACE] = ('location', Location) _children['{%s}access' % PHOTOS_NAMESPACE] = ('access', Access) _children['{%s}bytesUsed' % PHOTOS_NAMESPACE] = ('bytesUsed', BytesUsed) _children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp) _children['{%s}numphotos' % PHOTOS_NAMESPACE] = ('numphotos', Numphotos) _children['{%s}numphotosremaining' % PHOTOS_NAMESPACE] = \ ('numphotosremaining', Numphotosremaining) _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \ ('commentingEnabled', CommentingEnabled) _children['{%s}commentCount' % PHOTOS_NAMESPACE] = \ ('commentCount', CommentCount) ## NOTE: storing media:group as self.media, to create a self-explaining api gphoto_id = None name = None location = None access = None bytesUsed = None timestamp = None numphotos = None numphotosremaining = None user = None nickname = None commentingEnabled = None commentCount = None class AlbumEntry(GPhotosBaseEntry, AlbumData): """All metadata for a Google Photos Album Take a look at AlbumData for metadata accessible as attributes to this object. Notes: To avoid name clashes, and to create a more sensible api, some objects have names that differ from the original elements: o media:group -> self.media, o geo:where -> self.geo, o photo:id -> self.gphoto_id """ _kind = 'album' _children = GPhotosBaseEntry._children.copy() _children.update(AlbumData._children.copy()) # child tags only for Album entries, not feeds _children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where) _children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group) media = Media.Group() geo = Geo.Where() def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, #GPHOTO NAMESPACE: gphoto_id=None, name=None, location=None, access=None, timestamp=None, numphotos=None, user=None, nickname=None, commentingEnabled=None, commentCount=None, thumbnail=None, # MEDIA NAMESPACE: media=None, # GEORSS NAMESPACE: geo=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id self.gphoto_id = gphoto_id self.name = name self.location = location self.access = access self.timestamp = timestamp self.numphotos = numphotos self.user = user self.nickname = nickname self.commentingEnabled = commentingEnabled self.commentCount = commentCount self.thumbnail = thumbnail self.extended_property = extended_property or [] self.text = text ## NOTE: storing media:group as self.media, and geo:where as geo, ## to create a self-explaining api self.media = media or Media.Group() self.geo = geo or Geo.Where() def GetAlbumId(self): "Return the id of this album" return self.GetFeedLink().href.split('/')[-1] def GetPhotosUri(self): "(string) Return the uri to this albums feed of the PhotoEntry kind" return self._feedUri('photo') def GetCommentsUri(self): "(string) Return the uri to this albums feed of the CommentEntry kind" return self._feedUri('comment') def GetTagsUri(self): "(string) Return the uri to this albums feed of the TagEntry kind" return self._feedUri('tag') def AlbumEntryFromString(xml_string): return atom.CreateClassFromXMLString(AlbumEntry, xml_string) class AlbumFeed(GPhotosBaseFeed, AlbumData): """All metadata for a Google Photos Album, including its sub-elements This feed represents an album as the container for other objects. A Album feed contains entries of PhotoEntry, CommentEntry or TagEntry, depending on the `kind' parameter in the original query. Take a look at AlbumData for accessible attributes. """ _children = GPhotosBaseFeed._children.copy() _children.update(AlbumData._children.copy()) def GetPhotosUri(self): "(string) Return the uri to the same feed, but of the PhotoEntry kind" return self._feedUri('photo') def GetTagsUri(self): "(string) Return the uri to the same feed, but of the TagEntry kind" return self._feedUri('tag') def GetCommentsUri(self): "(string) Return the uri to the same feed, but of the CommentEntry kind" return self._feedUri('comment') def AlbumFeedFromString(xml_string): return atom.CreateClassFromXMLString(AlbumFeed, xml_string) class PhotoData(object): _children = {} ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid) _children['{%s}checksum' % PHOTOS_NAMESPACE] = ('checksum', Checksum) _children['{%s}client' % PHOTOS_NAMESPACE] = ('client', Client) _children['{%s}height' % PHOTOS_NAMESPACE] = ('height', Height) _children['{%s}position' % PHOTOS_NAMESPACE] = ('position', Position) _children['{%s}rotation' % PHOTOS_NAMESPACE] = ('rotation', Rotation) _children['{%s}size' % PHOTOS_NAMESPACE] = ('size', Size) _children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp) _children['{%s}version' % PHOTOS_NAMESPACE] = ('version', Version) _children['{%s}width' % PHOTOS_NAMESPACE] = ('width', Width) _children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \ ('commentingEnabled', CommentingEnabled) _children['{%s}commentCount' % PHOTOS_NAMESPACE] = \ ('commentCount', CommentCount) ## NOTE: storing media:group as self.media, exif:tags as self.exif, and ## geo:where as self.geo, to create a self-explaining api _children['{%s}tags' % EXIF_NAMESPACE] = ('exif', Exif.Tags) _children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where) _children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group) # These elements show up in search feeds _children['{%s}snippet' % PHOTOS_NAMESPACE] = ('snippet', Snippet) _children['{%s}snippettype' % PHOTOS_NAMESPACE] = ('snippettype', Snippettype) _children['{%s}truncated' % PHOTOS_NAMESPACE] = ('truncated', Truncated) gphoto_id = None albumid = None checksum = None client = None height = None position = None rotation = None size = None timestamp = None version = None width = None commentingEnabled = None commentCount = None snippet=None snippettype=None truncated=None media = Media.Group() geo = Geo.Where() tags = Exif.Tags() class PhotoEntry(GPhotosBaseEntry, PhotoData): """All metadata for a Google Photos Photo Take a look at PhotoData for metadata accessible as attributes to this object. Notes: To avoid name clashes, and to create a more sensible api, some objects have names that differ from the original elements: o media:group -> self.media, o exif:tags -> self.exif, o geo:where -> self.geo, o photo:id -> self.gphoto_id """ _kind = 'photo' _children = GPhotosBaseEntry._children.copy() _children.update(PhotoData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, text=None, # GPHOTO NAMESPACE: gphoto_id=None, albumid=None, checksum=None, client=None, height=None, position=None, rotation=None, size=None, timestamp=None, version=None, width=None, commentCount=None, commentingEnabled=None, # MEDIARSS NAMESPACE: media=None, # EXIF_NAMESPACE: exif=None, # GEORSS NAMESPACE: geo=None, extension_elements=None, extension_attributes=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id self.gphoto_id = gphoto_id self.albumid = albumid self.checksum = checksum self.client = client self.height = height self.position = position self.rotation = rotation self.size = size self.timestamp = timestamp self.version = version self.width = width self.commentingEnabled = commentingEnabled self.commentCount = commentCount ## NOTE: storing media:group as self.media, to create a self-explaining api self.media = media or Media.Group() self.exif = exif or Exif.Tags() self.geo = geo or Geo.Where() def GetPostLink(self): "Return the uri to this photo's `POST' link (use it for updates of the object)" return self.GetFeedLink() def GetCommentsUri(self): "Return the uri to this photo's feed of CommentEntry comments" return self._feedUri('comment') def GetTagsUri(self): "Return the uri to this photo's feed of TagEntry tags" return self._feedUri('tag') def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this photo""" href = self.GetSelfLink().href return href[:href.find('/photoid')] def PhotoEntryFromString(xml_string): return atom.CreateClassFromXMLString(PhotoEntry, xml_string) class PhotoFeed(GPhotosBaseFeed, PhotoData): """All metadata for a Google Photos Photo, including its sub-elements This feed represents a photo as the container for other objects. A Photo feed contains entries of CommentEntry or TagEntry, depending on the `kind' parameter in the original query. Take a look at PhotoData for metadata accessible as attributes to this object. """ _children = GPhotosBaseFeed._children.copy() _children.update(PhotoData._children.copy()) def GetTagsUri(self): "(string) Return the uri to the same feed, but of the TagEntry kind" return self._feedUri('tag') def GetCommentsUri(self): "(string) Return the uri to the same feed, but of the CommentEntry kind" return self._feedUri('comment') def PhotoFeedFromString(xml_string): return atom.CreateClassFromXMLString(PhotoFeed, xml_string) class TagData(GPhotosBaseData): _children = {} _children['{%s}weight' % PHOTOS_NAMESPACE] = ('weight', Weight) weight=None class TagEntry(GPhotosBaseEntry, TagData): """All metadata for a Google Photos Tag The actual tag is stored in the .title.text attribute """ _kind = 'tag' _children = GPhotosBaseEntry._children.copy() _children.update(TagData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: weight=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.weight = weight def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this tag""" href = self.GetSelfLink().href pos = href.find('/photoid') if pos == -1: return None return href[:pos] def GetPhotoUri(self): """Return the uri to the PhotoEntry containing this tag""" href = self.GetSelfLink().href pos = href.find('/tag') if pos == -1: return None return href[:pos] def TagEntryFromString(xml_string): return atom.CreateClassFromXMLString(TagEntry, xml_string) class TagFeed(GPhotosBaseFeed, TagData): """All metadata for a Google Photos Tag, including its sub-elements""" _children = GPhotosBaseFeed._children.copy() _children.update(TagData._children.copy()) def TagFeedFromString(xml_string): return atom.CreateClassFromXMLString(TagFeed, xml_string) class CommentData(GPhotosBaseData): _children = {} ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid) _children['{%s}photoid' % PHOTOS_NAMESPACE] = ('photoid', Photoid) _children['{%s}author' % atom.ATOM_NAMESPACE] = ('author', [CommentAuthor,]) gphoto_id=None albumid=None photoid=None author=None class CommentEntry(GPhotosBaseEntry, CommentData): """All metadata for a Google Photos Comment The comment is stored in the .content.text attribute, with a content type in .content.type. """ _kind = 'comment' _children = GPhotosBaseEntry._children.copy() _children.update(CommentData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: gphoto_id=None, albumid=None, photoid=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__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) self.gphoto_id = gphoto_id self.albumid = albumid self.photoid = photoid def GetCommentId(self): """Return the globally unique id of this comment""" return self.GetSelfLink().href.split('/')[-1] def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this comment""" href = self.GetSelfLink().href return href[:href.find('/photoid')] def GetPhotoUri(self): """Return the uri to the PhotoEntry containing this comment""" href = self.GetSelfLink().href return href[:href.find('/commentid')] def CommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(CommentEntry, xml_string) class CommentFeed(GPhotosBaseFeed, CommentData): """All metadata for a Google Photos Comment, including its sub-elements""" _children = GPhotosBaseFeed._children.copy() _children.update(CommentData._children.copy()) def CommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(CommentFeed, xml_string) class UserData(GPhotosBaseData): _children = {} _children['{%s}maxPhotosPerAlbum' % PHOTOS_NAMESPACE] = ('maxPhotosPerAlbum', MaxPhotosPerAlbum) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}quotalimit' % PHOTOS_NAMESPACE] = ('quotalimit', Quotalimit) _children['{%s}quotacurrent' % PHOTOS_NAMESPACE] = ('quotacurrent', Quotacurrent) _children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail) _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) maxPhotosPerAlbum=None nickname=None quotalimit=None quotacurrent=None thumbnail=None user=None gphoto_id=None class UserEntry(GPhotosBaseEntry, UserData): """All metadata for a Google Photos User This entry represents an album owner and all appropriate metadata. Take a look at at the attributes of the UserData for metadata available. """ _children = GPhotosBaseEntry._children.copy() _children.update(UserData._children.copy()) _kind = 'user' def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: gphoto_id=None, maxPhotosPerAlbum=None, nickname=None, quotalimit=None, quotacurrent=None, thumbnail=None, user=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__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) self.gphoto_id=gphoto_id self.maxPhotosPerAlbum=maxPhotosPerAlbum self.nickname=nickname self.quotalimit=quotalimit self.quotacurrent=quotacurrent self.thumbnail=thumbnail self.user=user def GetAlbumsUri(self): "(string) Return the uri to this user's feed of the AlbumEntry kind" return self._feedUri('album') def GetPhotosUri(self): "(string) Return the uri to this user's feed of the PhotoEntry kind" return self._feedUri('photo') def GetCommentsUri(self): "(string) Return the uri to this user's feed of the CommentEntry kind" return self._feedUri('comment') def GetTagsUri(self): "(string) Return the uri to this user's feed of the TagEntry kind" return self._feedUri('tag') def UserEntryFromString(xml_string): return atom.CreateClassFromXMLString(UserEntry, xml_string) class UserFeed(GPhotosBaseFeed, UserData): """Feed for a User in the google photos api. This feed represents a user as the container for other objects. A User feed contains entries of AlbumEntry, PhotoEntry, CommentEntry, UserEntry or TagEntry, depending on the `kind' parameter in the original query. The user feed itself also contains all of the metadata available as part of a UserData object.""" _children = GPhotosBaseFeed._children.copy() _children.update(UserData._children.copy()) def GetAlbumsUri(self): """Get the uri to this feed, but with entries of the AlbumEntry kind.""" return self._feedUri('album') def GetTagsUri(self): """Get the uri to this feed, but with entries of the TagEntry kind.""" return self._feedUri('tag') def GetPhotosUri(self): """Get the uri to this feed, but with entries of the PhotosEntry kind.""" return self._feedUri('photo') def GetCommentsUri(self): """Get the uri to this feed, but with entries of the CommentsEntry kind.""" return self._feedUri('comment') def UserFeedFromString(xml_string): return atom.CreateClassFromXMLString(UserFeed, xml_string) def AnyFeedFromString(xml_string): """Creates an instance of the appropriate feed class from the xml string contents. Args: xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. Returns: An instance of the target class with members assigned according to the contents of the XML - or a basic gdata.GDataFeed instance if it is impossible to determine the appropriate class (look for extra elements in GDataFeed's .FindExtensions() and extension_elements[] ). """ tree = ElementTree.fromstring(xml_string) category = tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree) ## TODO: is getattr safe this way? feed_class = getattr(gdata.photos, '%sFeed' % kind.title()) return atom._CreateClassFromElementTree(feed_class, tree) def AnyEntryFromString(xml_string): """Creates an instance of the appropriate entry class from the xml string contents. Args: xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. Returns: An instance of the target class with members assigned according to the contents of the XML - or a basic gdata.GDataEndry instance if it is impossible to determine the appropriate class (look for extra elements in GDataEntry's .FindExtensions() and extension_elements[] ). """ tree = ElementTree.fromstring(xml_string) category = tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree) ## TODO: is getattr safe this way? feed_class = getattr(gdata.photos, '%sEntry' % kind.title()) return atom._CreateClassFromElementTree(feed_class, tree)
Python
#!/usr/bin/python """ requires tlslite - http://trevp.net/tlslite/ """ import binascii from gdata.tlslite.utils import keyfactory from gdata.tlslite.utils import cryptomath # XXX andy: ugly local import due to module name, oauth.oauth import gdata.oauth as oauth class OAuthSignatureMethod_RSA_SHA1(oauth.OAuthSignatureMethod): def get_name(self): return "RSA-SHA1" def _fetch_public_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # (2) fetch via http using a url provided by the requester # (3) some sort of specific discovery code based on request # # either way should return a string representation of the certificate raise NotImplementedError def _fetch_private_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # # either way should return a string representation of the certificate raise NotImplementedError def build_signature_base_string(self, oauth_request, consumer, token): sig = ( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), ) key = '' raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the private key cert based on the request cert = self._fetch_private_cert(oauth_request) # Pull the private key from the certificate privatekey = keyfactory.parsePrivateKey(cert) # Convert base_string to bytes #base_string_bytes = cryptomath.createByteArraySequence(base_string) # Sign using the key signed = privatekey.hashAndSign(base_string) return binascii.b2a_base64(signed)[:-1] def check_signature(self, oauth_request, consumer, token, signature): decoded_sig = base64.b64decode(signature); key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the public key cert based on the request cert = self._fetch_public_cert(oauth_request) # Pull the public key from the certificate publickey = keyfactory.parsePEMKey(cert, public=True) # Check the signature ok = publickey.hashAndVerify(decoded_sig, base_string) return ok class TestOAuthSignatureMethod_RSA_SHA1(OAuthSignatureMethod_RSA_SHA1): def _fetch_public_cert(self, oauth_request): cert = """ -----BEGIN CERTIFICATE----- MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0 IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3 DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d 4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J -----END CERTIFICATE----- """ return cert def _fetch_private_cert(self, oauth_request): cert = """ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+ 3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8 AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54 Lw03eHTNQghS0A== -----END PRIVATE KEY----- """ return cert
Python
#!/usr/bin/python """ requires tlslite - http://trevp.net/tlslite/ """ import binascii from gdata.tlslite.utils import keyfactory from gdata.tlslite.utils import cryptomath # XXX andy: ugly local import due to module name, oauth.oauth import gdata.oauth as oauth class OAuthSignatureMethod_RSA_SHA1(oauth.OAuthSignatureMethod): def get_name(self): return "RSA-SHA1" def _fetch_public_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # (2) fetch via http using a url provided by the requester # (3) some sort of specific discovery code based on request # # either way should return a string representation of the certificate raise NotImplementedError def _fetch_private_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # # either way should return a string representation of the certificate raise NotImplementedError def build_signature_base_string(self, oauth_request, consumer, token): sig = ( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), ) key = '' raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the private key cert based on the request cert = self._fetch_private_cert(oauth_request) # Pull the private key from the certificate privatekey = keyfactory.parsePrivateKey(cert) # Convert base_string to bytes #base_string_bytes = cryptomath.createByteArraySequence(base_string) # Sign using the key signed = privatekey.hashAndSign(base_string) return binascii.b2a_base64(signed)[:-1] def check_signature(self, oauth_request, consumer, token, signature): decoded_sig = base64.b64decode(signature); key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the public key cert based on the request cert = self._fetch_public_cert(oauth_request) # Pull the public key from the certificate publickey = keyfactory.parsePEMKey(cert, public=True) # Check the signature ok = publickey.hashAndVerify(decoded_sig, base_string) return ok class TestOAuthSignatureMethod_RSA_SHA1(OAuthSignatureMethod_RSA_SHA1): def _fetch_public_cert(self, oauth_request): cert = """ -----BEGIN CERTIFICATE----- MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0 IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3 DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d 4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J -----END CERTIFICATE----- """ return cert def _fetch_private_cert(self, oauth_request): cert = """ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+ 3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8 AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54 Lw03eHTNQghS0A== -----END PRIVATE KEY----- """ return cert
Python